@speakableio/core 0.1.77 → 0.1.79

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.
@@ -1,3239 +0,0 @@
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_WRITE_CARD_SUBMITTED: "respond_write_card_submitted",
837
- RESPOND_WRITE_CARD_ERROR: "respond_write_card_error",
838
- RESPOND_CARD_ERROR: "respond_card_error",
839
- RESPOND_CARD_SUBMITTED: "respond_card_submitted",
840
- RESPOND_FREE_PLAN: "respond_free_plan",
841
- RESPOND_WRITE_FREE_PLAN: "respond_write_free_plan",
842
- SUBMISSION: "assignment_submitted",
843
- ASSIGNMENT_STARTED: "assignment_started",
844
- CREATE_ASSIGNMENT: "create_assignment",
845
- MC_SUCCESS: "multiple_choice_success",
846
- MC_FAIL: "multiple_choice_fail",
847
- MC_ERROR: "multiple_choice_error",
848
- ACTFL_LEVEL: "actfl_level",
849
- WIDA_LEVEL: "wida_level"
850
- };
851
-
852
- // src/lib/firebase/firebase-analytics/assignment.ts
853
- var logOpenAssignment = (data = {}) => {
854
- api.logEvent("open_assignment", data);
855
- };
856
- var logOpenActivityPreview = (data = {}) => {
857
- api.logEvent("open_activity_preview", data);
858
- };
859
- var logSubmitAssignment = (data = {}) => {
860
- var _a, _b, _c;
861
- (_c = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "handleCouresAnalyticsEvent")) == null ? void 0 : _c({
862
- eventType: ANALYTICS_EVENT_TYPES.SUBMISSION,
863
- ...data
864
- });
865
- api.logEvent(ANALYTICS_EVENT_TYPES.SUBMISSION, data);
866
- };
867
- var logStartAssignment = (data = {}) => {
868
- var _a, _b, _c;
869
- if (data.courseId) {
870
- (_c = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "handleCouresAnalyticsEvent")) == null ? void 0 : _c({
871
- eventType: ANALYTICS_EVENT_TYPES.ASSIGNMENT_STARTED,
872
- ...data
873
- });
874
- }
875
- api.logEvent(ANALYTICS_EVENT_TYPES.ASSIGNMENT_STARTED, data);
876
- };
877
-
878
- // src/domains/assignment/utils/create-default-score.ts
879
- var defaultScore = (props) => {
880
- const { serverTimestamp: serverTimestamp2 } = api.accessHelpers();
881
- const score = {
882
- progress: 0,
883
- score: 0,
884
- startDate: serverTimestamp2(),
885
- status: "IN_PROGRESS",
886
- submitted: false,
887
- cards: {},
888
- lastPlayed: serverTimestamp2(),
889
- owners: props.owners,
890
- userId: props.userId
891
- };
892
- if (props.googleClassroomUserId) {
893
- score.googleClassroomUserId = props.googleClassroomUserId;
894
- }
895
- if (props.courseId) {
896
- score.courseId = props.courseId;
897
- }
898
- return score;
899
- };
900
-
901
- // src/domains/assignment/score-practice.constants.ts
902
- var SCORES_PRACTICE_COLLECTION = "users";
903
- var SCORES_PRACTICE_SUBCOLLECTION = "practice";
904
- var refsScoresPractice = {
905
- practiceScores: (params) => `${SCORES_PRACTICE_COLLECTION}/${params.userId}/${SCORES_PRACTICE_SUBCOLLECTION}/${params.setId}`,
906
- practiceScoreHistoryRefDoc: (params) => `${SCORES_PRACTICE_COLLECTION}/${params.userId}/${SCORES_PRACTICE_SUBCOLLECTION}/${params.setId}/attempts/${params.date}`
907
- };
908
-
909
- // src/domains/assignment/services/create-score.service.ts
910
- async function _createScore(params) {
911
- var _a, _b, _c;
912
- if (params.isAssignment) {
913
- const ref = refsAssignmentFiresotre.assignmentScores({
914
- id: params.activityId,
915
- userId: params.userId
916
- });
917
- await ((_c = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "updateAssignmentGradebookStatus")) == null ? void 0 : _c({
918
- assignmentId: params.activityId,
919
- userId: params.userId,
920
- status: "IN_PROGRESS",
921
- score: null
922
- }));
923
- await api.setDoc(ref, params.scoreData, { merge: true });
924
- return {
925
- id: params.userId
926
- };
927
- } else {
928
- const ref = refsScoresPractice.practiceScores({
929
- userId: params.userId,
930
- setId: params.activityId
931
- });
932
- await api.setDoc(ref, params.scoreData);
933
- return {
934
- id: params.userId
935
- };
936
- }
937
- }
938
- var createScore = withErrorHandler(_createScore, "createScore");
939
-
940
- // src/domains/assignment/services/get-score.service.ts
941
- async function getAssignmentScore({
942
- userId,
943
- assignment,
944
- googleClassroomUserId
945
- }) {
946
- const path = refsAssignmentFiresotre.assignmentScores({
947
- id: assignment.id,
948
- userId
949
- });
950
- const response = await api.getDoc(path);
951
- if (response.data == null) {
952
- const newScore = {
953
- ...defaultScore({
954
- owners: [userId],
955
- userId,
956
- courseId: assignment.courseId,
957
- googleClassroomUserId
958
- }),
959
- assignmentId: assignment.id
960
- };
961
- logStartAssignment({
962
- courseId: assignment.courseId
963
- });
964
- const result = await createScore({
965
- activityId: assignment.id,
966
- userId,
967
- isAssignment: true,
968
- scoreData: newScore
969
- });
970
- return {
971
- ...newScore,
972
- id: result.id
973
- };
974
- }
975
- return response.data;
976
- }
977
- async function getPracticeScore({ userId, setId }) {
978
- const path = refsScoresPractice.practiceScores({ userId, setId });
979
- const response = await api.getDoc(path);
980
- if (response.data == null) {
981
- const newScore = {
982
- ...defaultScore({
983
- owners: [userId],
984
- userId
985
- }),
986
- setId
987
- };
988
- const result = await createScore({
989
- activityId: setId,
990
- userId,
991
- isAssignment: false,
992
- scoreData: newScore
993
- });
994
- return {
995
- ...newScore,
996
- id: result.id
997
- };
998
- }
999
- return response.data;
1000
- }
1001
- async function _getScore(params) {
1002
- if (params.isAssignment) {
1003
- return await getAssignmentScore({
1004
- userId: params.userId,
1005
- assignment: {
1006
- id: params.activityId,
1007
- courseId: params.courseId
1008
- },
1009
- googleClassroomUserId: params.googleClassroomUserId
1010
- });
1011
- } else {
1012
- return await getPracticeScore({
1013
- userId: params.userId,
1014
- setId: params.activityId
1015
- });
1016
- }
1017
- }
1018
- var getScore = withErrorHandler(_getScore, "getScore");
1019
-
1020
- // src/domains/assignment/utils/calculateScoreAndProgress.ts
1021
- var calculateScoreAndProgress = (scores, cardsList, weights) => {
1022
- const totalSetPoints = cardsList.reduce((acc, cardId) => {
1023
- acc += (weights == null ? void 0 : weights[cardId]) || 1;
1024
- return acc;
1025
- }, 0);
1026
- const totalPointsAwarded = Object.keys((scores == null ? void 0 : scores.cards) || {}).reduce((acc, cardId) => {
1027
- var _a, _b;
1028
- const cardScores = (_a = scores == null ? void 0 : scores.cards) == null ? void 0 : _a[cardId];
1029
- if ((cardScores == null ? void 0 : cardScores.completed) || (cardScores == null ? void 0 : cardScores.score) || (cardScores == null ? void 0 : cardScores.score) === 0) {
1030
- 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;
1031
- const weight = (weights == null ? void 0 : weights[cardId]) || 1;
1032
- const fraction = (score2 != null ? score2 : 0) / 100;
1033
- if (score2 || score2 === 0) {
1034
- acc += weight * fraction;
1035
- } else {
1036
- acc += weight;
1037
- }
1038
- }
1039
- return acc;
1040
- }, 0);
1041
- const totalCompletedCards = Object.keys((scores == null ? void 0 : scores.cards) || {}).reduce((acc, cardId) => {
1042
- var _a;
1043
- const cardScores = (_a = scores == null ? void 0 : scores.cards) == null ? void 0 : _a[cardId];
1044
- if ((cardScores == null ? void 0 : cardScores.completed) || (cardScores == null ? void 0 : cardScores.score) || (cardScores == null ? void 0 : cardScores.score) === 0) {
1045
- acc += 1;
1046
- }
1047
- return acc;
1048
- }, 0);
1049
- const percent = totalPointsAwarded / totalSetPoints;
1050
- const score = Math.round(percent * 100);
1051
- const progress = Math.round(totalCompletedCards / (cardsList.length || 1) * 100);
1052
- return { score, progress };
1053
- };
1054
- var calculateScoreAndProgress_default = calculateScoreAndProgress;
1055
-
1056
- // src/domains/assignment/services/update-score.service.ts
1057
- async function _updateScore(params) {
1058
- const path = params.isAssignment ? refsAssignmentFiresotre.assignmentScores({
1059
- id: params.activityId,
1060
- userId: params.userId
1061
- }) : refsScoresPractice.practiceScores({
1062
- setId: params.activityId,
1063
- userId: params.userId
1064
- });
1065
- await api.updateDoc(path, {
1066
- ...params.data
1067
- });
1068
- }
1069
- var updateScore = withErrorHandler(_updateScore, "updateScore");
1070
- async function _updateCardScore(params) {
1071
- const path = params.isAssignment ? refsAssignmentFiresotre.assignmentScores({
1072
- id: params.activityId,
1073
- userId: params.userId
1074
- }) : refsScoresPractice.practiceScores({
1075
- setId: params.activityId,
1076
- userId: params.userId
1077
- });
1078
- const updates = Object.keys(params.updates.cardScore).reduce(
1079
- (acc, key) => {
1080
- acc[`cards.${params.cardId}.${key}`] = params.updates.cardScore[key];
1081
- return acc;
1082
- },
1083
- {}
1084
- );
1085
- if (params.updates.progress) {
1086
- updates.progress = params.updates.progress;
1087
- }
1088
- if (params.updates.score) {
1089
- updates.score = params.updates.score;
1090
- }
1091
- await api.updateDoc(path, {
1092
- ...updates
1093
- });
1094
- }
1095
- var updateCardScore = withErrorHandler(_updateCardScore, "updateCardScore");
1096
-
1097
- // src/domains/assignment/services/clear-score.service.ts
1098
- import dayjs3 from "dayjs";
1099
- async function clearScore(params) {
1100
- var _a, _b, _c, _d, _e;
1101
- const update = {
1102
- [`cards.${params.cardId}`]: {
1103
- attempts: (_a = params.cardScores.attempts) != null ? _a : 1,
1104
- correct: (_b = params.cardScores.correct) != null ? _b : 0,
1105
- // save old score history
1106
- history: [
1107
- {
1108
- ...params.cardScores,
1109
- attempts: (_c = params.cardScores.attempts) != null ? _c : 1,
1110
- correct: (_d = params.cardScores.correct) != null ? _d : 0,
1111
- retryTime: dayjs3().format("YYYY-MM-DD HH:mm:ss"),
1112
- history: null
1113
- },
1114
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
1115
- ...(_e = params.cardScores.history) != null ? _e : []
1116
- ]
1117
- }
1118
- };
1119
- const path = params.isAssignment ? refsAssignmentFiresotre.assignmentScores({
1120
- id: params.activityId,
1121
- userId: params.userId
1122
- }) : refsScoresPractice.practiceScores({
1123
- setId: params.activityId,
1124
- userId: params.userId
1125
- });
1126
- await api.updateDoc(path, update);
1127
- return {
1128
- update,
1129
- activityId: params.activityId
1130
- };
1131
- }
1132
-
1133
- // src/domains/assignment/services/submit-assignment-score.service.ts
1134
- import dayjs4 from "dayjs";
1135
- async function _submitAssignmentScore({
1136
- cardIds,
1137
- assignment,
1138
- weights,
1139
- userId,
1140
- status,
1141
- studentName
1142
- }) {
1143
- const { serverTimestamp: serverTimestamp2 } = api.accessHelpers();
1144
- const path = refsAssignmentFiresotre.assignmentScores({ id: assignment.id, userId });
1145
- const fieldsUpdated = {
1146
- submitted: true,
1147
- progress: 100,
1148
- submissionDate: serverTimestamp2(),
1149
- status
1150
- };
1151
- if (assignment.isAssessment) {
1152
- const result = await handleAssessment(
1153
- assignment,
1154
- userId,
1155
- cardIds,
1156
- weights,
1157
- fieldsUpdated,
1158
- studentName
1159
- );
1160
- return result;
1161
- } else if (assignment.courseId) {
1162
- await handleCourseAssignment(assignment, userId);
1163
- }
1164
- await api.updateDoc(path, { ...fieldsUpdated });
1165
- return { success: true, fieldsUpdated };
1166
- }
1167
- var submitAssignmentScore = withErrorHandler(
1168
- _submitAssignmentScore,
1169
- "submitAssignmentScore"
1170
- );
1171
- async function handleAssessment(assignment, userId, cardIds, weights, fieldsUpdated, studentName) {
1172
- var _a, _b, _c;
1173
- const path = refsAssignmentFiresotre.assignmentScores({ id: assignment.id, userId });
1174
- const response = await api.getDoc(path);
1175
- if (!response.data) {
1176
- throw new Error("Score not found");
1177
- }
1178
- const { score: scoreCalculated } = calculateScoreAndProgress_default(response.data, cardIds, weights);
1179
- await api.updateDoc(path, { score: scoreCalculated, status: "PENDING_REVIEW" });
1180
- await ((_c = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "submitAssessment")) == null ? void 0 : _c({
1181
- assignmentId: assignment.id,
1182
- assignmentTitle: assignment.name,
1183
- userId,
1184
- teacherId: assignment.owners[0],
1185
- studentName
1186
- }));
1187
- fieldsUpdated.status = "PENDING_REVIEW";
1188
- return { success: true, fieldsUpdated };
1189
- }
1190
- async function handleCourseAssignment(assignment, userId) {
1191
- var _a, _b, _c;
1192
- await ((_c = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "submitAssignmentV2")) == null ? void 0 : _c({
1193
- assignmentId: assignment.id,
1194
- userId
1195
- }));
1196
- }
1197
- async function submitPracticeScore({
1198
- setId,
1199
- userId,
1200
- scores
1201
- }) {
1202
- const { serverTimestamp: serverTimestamp2 } = api.accessHelpers();
1203
- const date = dayjs4().format("YYYY-MM-DD-HH-mm");
1204
- const ref = refsScoresPractice.practiceScoreHistoryRefDoc({ setId, userId, date });
1205
- const fieldsUpdated = {
1206
- ...scores,
1207
- submitted: true,
1208
- progress: 100,
1209
- submissionDate: serverTimestamp2(),
1210
- status: "SUBMITTED"
1211
- };
1212
- await api.setDoc(ref, { ...fieldsUpdated });
1213
- const refScores = refsScoresPractice.practiceScores({ userId, setId });
1214
- await api.deleteDoc(refScores);
1215
- return { success: true, fieldsUpdated };
1216
- }
1217
-
1218
- // src/domains/assignment/hooks/score-hooks.ts
1219
- var scoreQueryKeys = {
1220
- all: ["scores"],
1221
- byId: (id) => [...scoreQueryKeys.all, id],
1222
- list: () => [...scoreQueryKeys.all, "list"]
1223
- };
1224
- function useScore({
1225
- isAssignment,
1226
- activityId,
1227
- userId = "",
1228
- courseId,
1229
- enabled = true,
1230
- googleClassroomUserId
1231
- }) {
1232
- return useQuery2({
1233
- queryFn: () => getScore({
1234
- userId,
1235
- courseId,
1236
- activityId,
1237
- googleClassroomUserId,
1238
- isAssignment
1239
- }),
1240
- queryKey: scoreQueryKeys.byId(activityId),
1241
- enabled
1242
- });
1243
- }
1244
- var debounceUpdateScore = debounce(updateScore, 1e3);
1245
- function useUpdateScore() {
1246
- const { queryClient } = useSpeakableApi();
1247
- const mutation = useMutation({
1248
- mutationFn: debounceUpdateScore,
1249
- onMutate: (variables) => {
1250
- return handleOptimisticUpdate({
1251
- queryClient,
1252
- queryKey: scoreQueryKeys.byId(variables.activityId),
1253
- newData: variables.data
1254
- });
1255
- },
1256
- onError: (_, variables, context) => {
1257
- if (context == null ? void 0 : context.previousData)
1258
- queryClient.setQueryData(scoreQueryKeys.byId(variables.activityId), context.previousData);
1259
- },
1260
- onSettled: (_, err, variables) => {
1261
- queryClient.invalidateQueries({
1262
- queryKey: scoreQueryKeys.byId(variables.activityId)
1263
- });
1264
- }
1265
- });
1266
- return {
1267
- mutationUpdateScore: mutation
1268
- };
1269
- }
1270
- function useUpdateCardScore({
1271
- isAssignment,
1272
- activityId,
1273
- userId,
1274
- cardIds,
1275
- weights
1276
- }) {
1277
- const { queryClient } = useSpeakableApi();
1278
- const queryKey = scoreQueryKeys.byId(activityId);
1279
- const mutation = useMutation({
1280
- mutationFn: async ({ cardId, cardScore }) => {
1281
- const previousScores = queryClient.getQueryData(queryKey);
1282
- const { progress, score, newScoreUpdated, updatedCardScore } = getScoreUpdated({
1283
- previousScores: previousScores != null ? previousScores : {},
1284
- cardId,
1285
- cardScore,
1286
- cardIds,
1287
- weights
1288
- });
1289
- await updateCardScore({
1290
- userId,
1291
- cardId,
1292
- isAssignment,
1293
- activityId,
1294
- updates: {
1295
- cardScore: updatedCardScore,
1296
- progress,
1297
- score
1298
- }
1299
- });
1300
- return { cardId, scoresUpdated: newScoreUpdated };
1301
- },
1302
- onMutate: ({ cardId, cardScore }) => {
1303
- queryClient.setQueryData(queryKey, (previousScore) => {
1304
- const updates = handleOptimisticScore({
1305
- score: previousScore,
1306
- cardId,
1307
- cardScore,
1308
- cardIds,
1309
- weights
1310
- });
1311
- return {
1312
- ...previousScore,
1313
- ...updates
1314
- };
1315
- });
1316
- },
1317
- // eslint-disable-next-line no-unused-vars
1318
- onError: (error) => {
1319
- console.log(error.message);
1320
- const previousData = queryClient.getQueryData(queryKey);
1321
- if (previousData) {
1322
- queryClient.setQueryData(queryKey, previousData);
1323
- }
1324
- }
1325
- });
1326
- return {
1327
- mutationUpdateCardScore: mutation
1328
- };
1329
- }
1330
- var getScoreUpdated = ({
1331
- cardId,
1332
- cardScore,
1333
- previousScores,
1334
- cardIds,
1335
- weights
1336
- }) => {
1337
- var _a, _b;
1338
- const previousCard = (_a = previousScores.cards) == null ? void 0 : _a[cardId];
1339
- const newCardScore = {
1340
- ...previousCard != null ? previousCard : {},
1341
- ...cardScore
1342
- };
1343
- const newScores = {
1344
- ...previousScores,
1345
- cards: {
1346
- ...(_b = previousScores.cards) != null ? _b : {},
1347
- [cardId]: newCardScore
1348
- }
1349
- };
1350
- const { score, progress } = calculateScoreAndProgress_default(newScores, cardIds, weights);
1351
- return {
1352
- newScoreUpdated: newScores,
1353
- updatedCardScore: cardScore,
1354
- score,
1355
- progress
1356
- };
1357
- };
1358
- var handleOptimisticScore = ({
1359
- score,
1360
- cardId,
1361
- cardScore,
1362
- cardIds,
1363
- weights
1364
- }) => {
1365
- var _a;
1366
- let cards = { ...(_a = score == null ? void 0 : score.cards) != null ? _a : {} };
1367
- cards = {
1368
- ...cards,
1369
- [cardId]: {
1370
- ...cards[cardId],
1371
- ...cardScore
1372
- }
1373
- };
1374
- const { score: scoreValue, progress } = calculateScoreAndProgress_default(
1375
- // @ts-ignore
1376
- {
1377
- ...score != null ? score : {},
1378
- cards
1379
- },
1380
- cardIds,
1381
- weights
1382
- );
1383
- return { cards, score: scoreValue, progress };
1384
- };
1385
- function useClearScore() {
1386
- const { queryClient } = useSpeakableApi();
1387
- const mutation = useMutation({
1388
- mutationFn: clearScore,
1389
- onSettled: (result) => {
1390
- var _a;
1391
- queryClient.invalidateQueries({
1392
- queryKey: scoreQueryKeys.byId((_a = result == null ? void 0 : result.activityId) != null ? _a : "")
1393
- });
1394
- }
1395
- });
1396
- return {
1397
- mutationClearScore: mutation
1398
- };
1399
- }
1400
- function useSubmitAssignmentScore({
1401
- onAssignmentSubmitted,
1402
- studentName
1403
- }) {
1404
- const { queryClient } = useSpeakableApi();
1405
- const { hasGoogleClassroomGradePassback } = usePermissions_default();
1406
- const { submitAssignmentToGoogleClassroom } = useGoogleClassroom();
1407
- const { createNotification: createNotification2 } = useCreateNotification();
1408
- const mutation = useMutation({
1409
- mutationFn: async ({
1410
- assignment,
1411
- userId,
1412
- cardIds,
1413
- weights,
1414
- scores,
1415
- status
1416
- }) => {
1417
- try {
1418
- const scoreUpdated = await submitAssignmentScore({
1419
- assignment,
1420
- userId,
1421
- cardIds,
1422
- weights,
1423
- status,
1424
- studentName
1425
- });
1426
- if (assignment.courseWorkId != null && !assignment.isAssessment && hasGoogleClassroomGradePassback) {
1427
- await submitAssignmentToGoogleClassroom({
1428
- assignment,
1429
- scores
1430
- });
1431
- }
1432
- if (assignment.isAssessment) {
1433
- createNotification2(SpeakableNotificationTypes.ASSESSMENT_SUBMITTED, assignment);
1434
- }
1435
- if (assignment == null ? void 0 : assignment.id) {
1436
- logSubmitAssignment({
1437
- courseId: assignment == null ? void 0 : assignment.courseId
1438
- });
1439
- }
1440
- onAssignmentSubmitted(assignment.id);
1441
- queryClient.setQueryData(scoreQueryKeys.byId(assignment.id), {
1442
- ...scores,
1443
- ...scoreUpdated.fieldsUpdated
1444
- });
1445
- return {
1446
- success: true,
1447
- message: "Score submitted successfully"
1448
- };
1449
- } catch (error) {
1450
- return {
1451
- success: false,
1452
- error
1453
- };
1454
- }
1455
- }
1456
- });
1457
- return {
1458
- submitAssignmentScore: mutation.mutateAsync,
1459
- isLoading: mutation.isPending
1460
- };
1461
- }
1462
- function useSubmitPracticeScore() {
1463
- const { queryClient } = useSpeakableApi();
1464
- const mutation = useMutation({
1465
- mutationFn: async ({
1466
- setId,
1467
- userId,
1468
- scores
1469
- }) => {
1470
- try {
1471
- await submitPracticeScore({
1472
- setId,
1473
- userId,
1474
- scores
1475
- });
1476
- queryClient.invalidateQueries({
1477
- queryKey: scoreQueryKeys.byId(setId)
1478
- });
1479
- return {
1480
- success: true,
1481
- message: "Score submitted successfully"
1482
- };
1483
- } catch (error) {
1484
- return {
1485
- success: false,
1486
- error
1487
- };
1488
- }
1489
- }
1490
- });
1491
- return {
1492
- submitPracticeScore: mutation.mutateAsync,
1493
- isLoading: mutation.isPending
1494
- };
1495
- }
1496
-
1497
- // src/domains/cards/card.hooks.ts
1498
- import { useMutation as useMutation2, useQueries, useQuery as useQuery3 } from "@tanstack/react-query";
1499
- import { useMemo } from "react";
1500
-
1501
- // src/domains/cards/card.constants.ts
1502
- var FeedbackTypesCard = /* @__PURE__ */ ((FeedbackTypesCard2) => {
1503
- FeedbackTypesCard2["SuggestedResponse"] = "suggested_response";
1504
- FeedbackTypesCard2["Wida"] = "wida";
1505
- FeedbackTypesCard2["GrammarInsights"] = "grammar_insights";
1506
- FeedbackTypesCard2["Actfl"] = "actfl";
1507
- FeedbackTypesCard2["ProficiencyLevel"] = "proficiency_level";
1508
- return FeedbackTypesCard2;
1509
- })(FeedbackTypesCard || {});
1510
- var LeniencyCard = /* @__PURE__ */ ((LeniencyCard2) => {
1511
- LeniencyCard2["CONFIDENCE"] = "confidence";
1512
- LeniencyCard2["EASY"] = "easy";
1513
- LeniencyCard2["NORMAL"] = "normal";
1514
- LeniencyCard2["HARD"] = "hard";
1515
- return LeniencyCard2;
1516
- })(LeniencyCard || {});
1517
- var LENIENCY_OPTIONS = [
1518
- {
1519
- label: "Build Confidence - most lenient",
1520
- value: "confidence" /* CONFIDENCE */
1521
- },
1522
- {
1523
- label: "Very Lenient",
1524
- value: "easy" /* EASY */
1525
- },
1526
- {
1527
- label: "Normal",
1528
- value: "normal" /* NORMAL */
1529
- },
1530
- {
1531
- label: "No leniency - most strict",
1532
- value: "hard" /* HARD */
1533
- }
1534
- ];
1535
- var STUDENT_LEVELS_OPTIONS = [
1536
- {
1537
- label: "Beginner",
1538
- description: "Beginner Level: Just starting out. Can say a few basic words and phrases.",
1539
- value: "beginner"
1540
- },
1541
- {
1542
- label: "Elementary",
1543
- description: "Elementary Level: Can understand simple sentences and have very basic conversations.",
1544
- value: "elementary"
1545
- },
1546
- {
1547
- label: "Intermediate",
1548
- description: "Intermediate Level: Can talk about everyday topics and handle common situations.",
1549
- value: "intermediate"
1550
- },
1551
- {
1552
- label: "Advanced",
1553
- description: "Advanced Level: Can speak and understand with ease, and explain ideas clearly.",
1554
- value: "advanced"
1555
- },
1556
- {
1557
- label: "Fluent",
1558
- description: "Fluent Level: Speaks naturally and easily. Can use the language in work or school settings.",
1559
- value: "fluent"
1560
- },
1561
- {
1562
- label: "Native-like",
1563
- description: "Native-like Level: Understands and speaks like a native. Can discuss complex ideas accurately.",
1564
- value: "nativeLike"
1565
- }
1566
- ];
1567
- var BASE_RESPOND_FIELD_VALUES = {
1568
- title: "",
1569
- allowRetries: true,
1570
- respondTime: 180,
1571
- maxCharacters: 1e3
1572
- };
1573
- var BASE_REPEAT_FIELD_VALUES = {
1574
- repeat: 1
1575
- };
1576
- var BASE_MULTIPLE_CHOICE_FIELD_VALUES = {
1577
- MCQType: "single",
1578
- answer: ["A"],
1579
- choices: [
1580
- { option: "A", value: "Option A" },
1581
- { option: "B", value: "Option B" },
1582
- { option: "C", value: "Option C" }
1583
- ]
1584
- };
1585
- var VerificationCardStatus = /* @__PURE__ */ ((VerificationCardStatus2) => {
1586
- VerificationCardStatus2["VERIFIED"] = "VERIFIED";
1587
- VerificationCardStatus2["WARNING"] = "WARNING";
1588
- VerificationCardStatus2["NOT_RECOMMENDED"] = "NOT_RECOMMENDED";
1589
- VerificationCardStatus2["NOT_WORKING"] = "NOT_WORKING";
1590
- VerificationCardStatus2["NOT_CHECKED"] = "NOT_CHECKED";
1591
- return VerificationCardStatus2;
1592
- })(VerificationCardStatus || {});
1593
- var CARDS_COLLECTION = "flashcards";
1594
- var refsCardsFiresotre = {
1595
- allCards: CARDS_COLLECTION,
1596
- card: (id) => `${CARDS_COLLECTION}/${id}`
1597
- };
1598
-
1599
- // src/domains/cards/services/get-card.service.ts
1600
- async function _getCard(params) {
1601
- const ref = refsCardsFiresotre.card(params.cardId);
1602
- const response = await api.getDoc(ref);
1603
- if (!response.data) return null;
1604
- return response.data;
1605
- }
1606
- var getCard = withErrorHandler(_getCard, "getCard");
1607
-
1608
- // src/domains/cards/services/create-card.service.ts
1609
- import { v4 } from "uuid";
1610
-
1611
- // src/domains/cards/card.model.ts
1612
- var ActivityPageType = /* @__PURE__ */ ((ActivityPageType2) => {
1613
- ActivityPageType2["READ_REPEAT"] = "READ_REPEAT";
1614
- ActivityPageType2["VIDEO"] = "VIDEO";
1615
- ActivityPageType2["TEXT"] = "TEXT";
1616
- ActivityPageType2["READ_RESPOND"] = "READ_RESPOND";
1617
- ActivityPageType2["FREE_RESPONSE"] = "FREE_RESPONSE";
1618
- ActivityPageType2["REPEAT"] = "REPEAT";
1619
- ActivityPageType2["RESPOND"] = "RESPOND";
1620
- ActivityPageType2["RESPOND_WRITE"] = "RESPOND_WRITE";
1621
- ActivityPageType2["TEXT_TO_SPEECH"] = "TEXT_TO_SPEECH";
1622
- ActivityPageType2["MULTIPLE_CHOICE"] = "MULTIPLE_CHOICE";
1623
- ActivityPageType2["PODCAST"] = "PODCAST";
1624
- ActivityPageType2["MEDIA_PAGE"] = "MEDIA_PAGE";
1625
- ActivityPageType2["WRITE"] = "WRITE";
1626
- ActivityPageType2["SHORT_ANSWER"] = "SHORT_ANSWER";
1627
- ActivityPageType2["SHORT_STORY"] = "SHORT_STORY";
1628
- ActivityPageType2["SPEAK"] = "SPEAK";
1629
- ActivityPageType2["CONVERSATION"] = "CONVERSATION";
1630
- ActivityPageType2["CONVERSATION_WRITE"] = "CONVERSATION_WRITE";
1631
- ActivityPageType2["DIALOGUE"] = "DIALOGUE";
1632
- ActivityPageType2["INSTRUCTION"] = "INSTRUCTION";
1633
- ActivityPageType2["LISTEN"] = "LISTEN";
1634
- ActivityPageType2["READ"] = "READ";
1635
- ActivityPageType2["ANSWER"] = "ANSWER";
1636
- return ActivityPageType2;
1637
- })(ActivityPageType || {});
1638
- var RESPOND_PAGE_ACTIVITY_TYPES = [
1639
- "READ_RESPOND" /* READ_RESPOND */,
1640
- "RESPOND" /* RESPOND */,
1641
- "RESPOND_WRITE" /* RESPOND_WRITE */,
1642
- "FREE_RESPONSE" /* FREE_RESPONSE */
1643
- ];
1644
- var MULTIPLE_CHOICE_PAGE_ACTIVITY_TYPES = ["MULTIPLE_CHOICE" /* MULTIPLE_CHOICE */];
1645
- var REPEAT_PAGE_ACTIVITY_TYPES = ["READ_REPEAT" /* READ_REPEAT */, "REPEAT" /* REPEAT */];
1646
- var RESPOND_WRITE_PAGE_ACTIVITY_TYPES = [
1647
- "RESPOND_WRITE" /* RESPOND_WRITE */,
1648
- "FREE_RESPONSE" /* FREE_RESPONSE */
1649
- ];
1650
- var RESPOND_AUDIO_PAGE_ACTIVITY_TYPES = [
1651
- "RESPOND" /* RESPOND */,
1652
- "READ_RESPOND" /* READ_RESPOND */
1653
- ];
1654
-
1655
- // src/utils/text-utils.ts
1656
- import sha1 from "js-sha1";
1657
- var purify = (word) => {
1658
- 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();
1659
- };
1660
- var cleanString = (words) => {
1661
- const splitWords = words == null ? void 0 : words.split("+");
1662
- if (splitWords && splitWords.length === 1) {
1663
- const newWord = purify(words);
1664
- return newWord;
1665
- } else if (splitWords && splitWords.length > 1) {
1666
- const split = splitWords.map((w) => purify(w));
1667
- return split;
1668
- } else {
1669
- return "";
1670
- }
1671
- };
1672
- var getWordHash = (word, language) => {
1673
- const cleanedWord = cleanString(word);
1674
- const wordHash = sha1(`${language}-${cleanedWord}`);
1675
- console.log("wordHash core library", wordHash);
1676
- return wordHash;
1677
- };
1678
- function getPhraseLength(phrase, input) {
1679
- if (Array.isArray(phrase) && phrase.includes(input)) {
1680
- return phrase[phrase.indexOf(input)].split(" ").length;
1681
- } else {
1682
- return phrase ? phrase.split(" ").length : 0;
1683
- }
1684
- }
1685
-
1686
- // src/domains/cards/services/get-card-verification-status.service.ts
1687
- var charactarLanguages = ["zh", "ja", "ko"];
1688
- var getVerificationStatus = async (target_text, language) => {
1689
- if ((target_text == null ? void 0 : target_text.length) < 3 && !charactarLanguages.includes(language)) {
1690
- return "NOT_RECOMMENDED" /* NOT_RECOMMENDED */;
1691
- }
1692
- const hash = getWordHash(target_text, language);
1693
- const response = await api.getDoc(`checked-pronunciations/${hash}`);
1694
- try {
1695
- if (response.data) {
1696
- return processRecord(response.data);
1697
- } else {
1698
- return "NOT_CHECKED" /* NOT_CHECKED */;
1699
- }
1700
- } catch (e) {
1701
- return "NOT_CHECKED" /* NOT_CHECKED */;
1702
- }
1703
- };
1704
- var processRecord = (data) => {
1705
- const { pronunciations = 0, fails = 0 } = data;
1706
- const attempts = pronunciations + fails;
1707
- const successRate = attempts > 0 ? pronunciations / attempts * 100 : 0;
1708
- let newStatus = null;
1709
- if (attempts < 6) {
1710
- return "NOT_CHECKED" /* NOT_CHECKED */;
1711
- }
1712
- if (successRate > 25) {
1713
- newStatus = "VERIFIED" /* VERIFIED */;
1714
- } else if (successRate > 10) {
1715
- newStatus = "WARNING" /* WARNING */;
1716
- } else if (fails > 20 && successRate < 10 && pronunciations > 1) {
1717
- newStatus = "NOT_RECOMMENDED" /* NOT_RECOMMENDED */;
1718
- } else if (pronunciations === 0 && fails > 20) {
1719
- newStatus = "NOT_WORKING" /* NOT_WORKING */;
1720
- } else {
1721
- newStatus = "NOT_CHECKED" /* NOT_CHECKED */;
1722
- }
1723
- return newStatus;
1724
- };
1725
-
1726
- // src/domains/cards/services/create-card.service.ts
1727
- async function _createCard({ data }) {
1728
- const response = await api.addDoc(refsCardsFiresotre.allCards, data);
1729
- return response;
1730
- }
1731
- var createCard = withErrorHandler(_createCard, "createCard");
1732
- async function _createCards({ cards }) {
1733
- const { writeBatch: writeBatch2, doc: doc2 } = api.accessHelpers();
1734
- const batch = writeBatch2();
1735
- const cardsWithId = [];
1736
- for (const card of cards) {
1737
- const cardId = v4();
1738
- const ref = doc2(refsCardsFiresotre.card(cardId));
1739
- const newCardObject = {
1740
- ...card,
1741
- id: cardId
1742
- };
1743
- if (card.type === "READ_REPEAT" /* READ_REPEAT */ && card.target_text && card.language) {
1744
- const verificationStatus = await getVerificationStatus(card.target_text, card.language);
1745
- newCardObject.verificationStatus = verificationStatus || null;
1746
- }
1747
- cardsWithId.push(newCardObject);
1748
- batch.set(ref, newCardObject);
1749
- }
1750
- await batch.commit();
1751
- return cardsWithId;
1752
- }
1753
- var createCards = withErrorHandler(_createCards, "createCards");
1754
-
1755
- // src/domains/cards/card.hooks.ts
1756
- var cardsQueryKeys = {
1757
- all: ["cards"],
1758
- one: (params) => [...cardsQueryKeys.all, params.cardId]
1759
- };
1760
- function useCards({
1761
- cardIds,
1762
- enabled = true,
1763
- asObject
1764
- }) {
1765
- const queries = useQueries({
1766
- queries: cardIds.map((cardId) => ({
1767
- enabled: enabled && cardIds.length > 0,
1768
- queryKey: cardsQueryKeys.one({
1769
- cardId
1770
- }),
1771
- queryFn: () => getCard({ cardId })
1772
- }))
1773
- });
1774
- const cards = queries.map((query2) => query2.data).filter(Boolean);
1775
- const cardsObject = useMemo(() => {
1776
- if (!asObject) return null;
1777
- return cards.reduce((acc, card) => {
1778
- acc[card.id] = card;
1779
- return acc;
1780
- }, {});
1781
- }, [asObject, cards]);
1782
- return {
1783
- cards,
1784
- cardsObject,
1785
- cardsQueries: queries
1786
- };
1787
- }
1788
- function useCreateCard() {
1789
- const { queryClient } = useSpeakableApi();
1790
- const mutationCreateCard = useMutation2({
1791
- mutationFn: createCard,
1792
- onSuccess: (cardCreated) => {
1793
- queryClient.invalidateQueries({ queryKey: cardsQueryKeys.one({ cardId: cardCreated.id }) });
1794
- }
1795
- });
1796
- return {
1797
- mutationCreateCard
1798
- };
1799
- }
1800
- function useCreateCards() {
1801
- const mutationCreateCards = useMutation2({
1802
- mutationFn: createCards
1803
- });
1804
- return {
1805
- mutationCreateCards
1806
- };
1807
- }
1808
- function getCardFromCache({
1809
- cardId,
1810
- queryClient
1811
- }) {
1812
- return queryClient.getQueryData(cardsQueryKeys.one({ cardId }));
1813
- }
1814
- function updateCardInCache({
1815
- cardId,
1816
- card,
1817
- queryClient
1818
- }) {
1819
- queryClient.setQueryData(cardsQueryKeys.one({ cardId }), card);
1820
- }
1821
- function useGetCard({ cardId, enabled = true }) {
1822
- const query2 = useQuery3({
1823
- queryKey: cardsQueryKeys.one({ cardId }),
1824
- queryFn: () => getCard({ cardId }),
1825
- enabled: enabled && !!cardId
1826
- });
1827
- return query2;
1828
- }
1829
-
1830
- // src/domains/cards/card.repo.ts
1831
- var createCardRepo = () => {
1832
- return {
1833
- createCard,
1834
- createCards,
1835
- getCard
1836
- };
1837
- };
1838
-
1839
- // src/domains/cards/utils/check-page-type.ts
1840
- function checkIsRepeatPage(cardType) {
1841
- if (cardType === void 0) return false;
1842
- return REPEAT_PAGE_ACTIVITY_TYPES.includes(cardType);
1843
- }
1844
- function checkIsMCPage(cardType) {
1845
- if (cardType === void 0) return false;
1846
- return MULTIPLE_CHOICE_PAGE_ACTIVITY_TYPES.includes(cardType);
1847
- }
1848
- function checkIsRespondPage(cardType) {
1849
- if (cardType === void 0) return false;
1850
- return RESPOND_PAGE_ACTIVITY_TYPES.includes(cardType);
1851
- }
1852
- function checkIsRespondWrittenPage(cardType) {
1853
- if (cardType === void 0) return false;
1854
- return RESPOND_WRITE_PAGE_ACTIVITY_TYPES.includes(cardType);
1855
- }
1856
- function checkIsRespondAudioPage(cardType) {
1857
- if (cardType === void 0) return false;
1858
- return RESPOND_AUDIO_PAGE_ACTIVITY_TYPES.includes(cardType);
1859
- }
1860
- var checkIsMediaPage = (cardType) => {
1861
- if (cardType === void 0) return false;
1862
- return cardType === "MEDIA_PAGE" /* MEDIA_PAGE */;
1863
- };
1864
- var checkIsShortAnswerPage = (cardType) => {
1865
- if (cardType === void 0) return false;
1866
- return cardType === "SHORT_ANSWER" /* SHORT_ANSWER */;
1867
- };
1868
- var checkTypePageActivity = (cardType) => {
1869
- const isRespondAudio = checkIsRespondAudioPage(cardType);
1870
- const isRespondWritten = checkIsRespondWrittenPage(cardType);
1871
- const isRespond = checkIsRespondPage(cardType);
1872
- const isMC = checkIsMCPage(cardType);
1873
- const isRepeat = checkIsRepeatPage(cardType);
1874
- const isMediaPage = checkIsMediaPage(cardType);
1875
- const isShortAnswer = checkIsShortAnswerPage(cardType);
1876
- return {
1877
- isRespondAudio,
1878
- isRespondWritten,
1879
- isRespond,
1880
- isMC,
1881
- isRepeat,
1882
- isMediaPage,
1883
- isShortAnswer
1884
- };
1885
- };
1886
-
1887
- // src/domains/cards/utils/get-page-prompt.ts
1888
- function getPagePrompt(card) {
1889
- if (!card) return { has: false, text: "" };
1890
- const { isMC, isRepeat, isRespond, isShortAnswer } = checkTypePageActivity(card == null ? void 0 : card.type);
1891
- const hidePrompt = (card == null ? void 0 : card.hidePrompt) === true;
1892
- if (isRepeat) {
1893
- return {
1894
- has: true,
1895
- text: card == null ? void 0 : card.target_text
1896
- };
1897
- }
1898
- if (isRespond && !hidePrompt) {
1899
- return {
1900
- has: true,
1901
- text: card == null ? void 0 : card.prompt
1902
- };
1903
- }
1904
- if (isMC) {
1905
- return {
1906
- has: true,
1907
- text: card == null ? void 0 : card.question
1908
- };
1909
- }
1910
- if (isShortAnswer && !hidePrompt) {
1911
- return {
1912
- has: true,
1913
- text: card == null ? void 0 : card.prompt
1914
- };
1915
- }
1916
- return {
1917
- has: false,
1918
- text: ""
1919
- };
1920
- }
1921
-
1922
- // src/domains/sets/set.hooks.ts
1923
- import { useQuery as useQuery4 } from "@tanstack/react-query";
1924
-
1925
- // src/domains/sets/set.constants.ts
1926
- var SETS_COLLECTION = "sets";
1927
- var refsSetsFirestore = {
1928
- allSets: SETS_COLLECTION,
1929
- set: (id) => `${SETS_COLLECTION}/${id}`
1930
- };
1931
-
1932
- // src/domains/sets/services/get-set.service.ts
1933
- async function _getSet({ setId }) {
1934
- const response = await api.getDoc(refsSetsFirestore.set(setId));
1935
- return response.data;
1936
- }
1937
- var getSet = withErrorHandler(_getSet, "getSet");
1938
-
1939
- // src/domains/sets/set.hooks.ts
1940
- var setsQueryKeys = {
1941
- all: ["sets"],
1942
- one: (params) => [...setsQueryKeys.all, params.setId]
1943
- };
1944
- var useSet = ({ setId, enabled }) => {
1945
- return useQuery4({
1946
- queryKey: setsQueryKeys.one({ setId }),
1947
- queryFn: () => getSet({ setId }),
1948
- enabled: setId !== void 0 && setId !== "" && enabled
1949
- });
1950
- };
1951
- function getSetFromCache({
1952
- setId,
1953
- queryClient
1954
- }) {
1955
- if (!setId) return null;
1956
- return queryClient.getQueryData(setsQueryKeys.one({ setId }));
1957
- }
1958
- function updateSetInCache({
1959
- set,
1960
- queryClient
1961
- }) {
1962
- const { id, ...setData } = set;
1963
- queryClient.setQueryData(setsQueryKeys.one({ setId: id }), setData);
1964
- }
1965
-
1966
- // src/domains/sets/set.repo.ts
1967
- var createSetRepo = () => {
1968
- return {
1969
- getSet
1970
- };
1971
- };
1972
-
1973
- // src/constants/all-langs.json
1974
- var all_langs_default = {
1975
- af: "Afrikaans",
1976
- sq: "Albanian",
1977
- am: "Amharic",
1978
- ar: "Arabic",
1979
- hy: "Armenian",
1980
- az: "Azerbaijani",
1981
- eu: "Basque",
1982
- be: "Belarusian",
1983
- bn: "Bengali",
1984
- bs: "Bosnian",
1985
- bg: "Bulgarian",
1986
- ca: "Catalan",
1987
- ceb: "Cebuano",
1988
- zh: "Chinese",
1989
- co: "Corsican",
1990
- hr: "Croatian",
1991
- cs: "Czech",
1992
- da: "Danish",
1993
- nl: "Dutch",
1994
- en: "English",
1995
- eo: "Esperanto",
1996
- et: "Estonian",
1997
- fi: "Finnish",
1998
- fr: "French",
1999
- fy: "Frisian",
2000
- gl: "Galician",
2001
- ka: "Georgian",
2002
- de: "German",
2003
- el: "Greek",
2004
- gu: "Gujarati",
2005
- ht: "Haitian Creole",
2006
- ha: "Hausa",
2007
- haw: "Hawaiian",
2008
- he: "Hebrew",
2009
- hi: "Hindi",
2010
- hmn: "Hmong",
2011
- hu: "Hungarian",
2012
- is: "Icelandic",
2013
- ig: "Igbo",
2014
- id: "Indonesian",
2015
- ga: "Irish",
2016
- it: "Italian",
2017
- ja: "Japanese",
2018
- jv: "Javanese",
2019
- kn: "Kannada",
2020
- kk: "Kazakh",
2021
- km: "Khmer",
2022
- ko: "Korean",
2023
- ku: "Kurdish",
2024
- ky: "Kyrgyz",
2025
- lo: "Lao",
2026
- la: "Latin",
2027
- lv: "Latvian",
2028
- lt: "Lithuanian",
2029
- lb: "Luxembourgish",
2030
- mk: "Macedonian",
2031
- mg: "Malagasy",
2032
- ms: "Malay",
2033
- ml: "Malayalam",
2034
- mt: "Maltese",
2035
- mi: "Maori",
2036
- mr: "Marathi",
2037
- mn: "Mongolian",
2038
- my: "Myanmar (Burmese)",
2039
- ne: "Nepali",
2040
- no: "Norwegian",
2041
- ny: "Nyanja (Chichewa)",
2042
- ps: "Pashto",
2043
- fa: "Persian",
2044
- pl: "Polish",
2045
- pt: "Portuguese",
2046
- pa: "Punjabi",
2047
- ro: "Romanian",
2048
- ru: "Russian",
2049
- sm: "Samoan",
2050
- gd: "Scots Gaelic",
2051
- sr: "Serbian",
2052
- st: "Sesotho",
2053
- sn: "Shona",
2054
- sd: "Sindhi",
2055
- si: "Sinhala (Sinhalese)",
2056
- sk: "Slovak",
2057
- sl: "Slovenian",
2058
- so: "Somali",
2059
- es: "Spanish",
2060
- su: "Sundanese",
2061
- sw: "Swahili",
2062
- sv: "Swedish",
2063
- tl: "Tagalog (Filipino)",
2064
- tg: "Tajik",
2065
- ta: "Tamil",
2066
- te: "Telugu",
2067
- th: "Thai",
2068
- tr: "Turkish",
2069
- uk: "Ukrainian",
2070
- ur: "Urdu",
2071
- uz: "Uzbek",
2072
- vi: "Vietnamese",
2073
- cy: "Welsh",
2074
- xh: "Xhosa",
2075
- yi: "Yiddish",
2076
- yo: "Yoruba",
2077
- zu: "Zulu"
2078
- };
2079
-
2080
- // src/utils/ai/get-respond-card-tool.ts
2081
- var getRespondCardTool = ({
2082
- language,
2083
- standard = "actfl"
2084
- }) => {
2085
- const lang = all_langs_default[language] || "English";
2086
- const tool = {
2087
- tool_choice: {
2088
- type: "function",
2089
- function: { name: "get_feedback" }
2090
- },
2091
- tools: [
2092
- {
2093
- type: "function",
2094
- function: {
2095
- name: "get_feedback",
2096
- description: "Get feedback on a student's response",
2097
- parameters: {
2098
- type: "object",
2099
- required: [
2100
- "success",
2101
- "score",
2102
- "score_justification",
2103
- "errors",
2104
- "improvedResponse",
2105
- "compliments"
2106
- ],
2107
- properties: {
2108
- success: {
2109
- type: "boolean",
2110
- 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."
2111
- },
2112
- errors: {
2113
- type: "array",
2114
- items: {
2115
- type: "object",
2116
- required: ["error", "grammar_error_type", "correction", "justification"],
2117
- properties: {
2118
- error: {
2119
- type: "string",
2120
- description: "The grammatical error in the student's response."
2121
- },
2122
- correction: {
2123
- type: "string",
2124
- description: "The suggested correction to the error"
2125
- },
2126
- justification: {
2127
- type: "string",
2128
- description: `An explanation of the rationale behind the suggested correction. WRITE THIS IN ${lang}!`
2129
- },
2130
- grammar_error_type: {
2131
- type: "string",
2132
- enum: [
2133
- "subjVerbAgree",
2134
- "tenseErrors",
2135
- "articleMisuse",
2136
- "prepositionErrors",
2137
- "adjNounAgree",
2138
- "pronounErrors",
2139
- "wordOrder",
2140
- "verbConjugation",
2141
- "pluralization",
2142
- "negationErrors",
2143
- "modalVerbMisuse",
2144
- "relativeClause",
2145
- "auxiliaryVerb",
2146
- "complexSentenceAgreement",
2147
- "idiomaticExpression",
2148
- "registerInconsistency",
2149
- "voiceMisuse"
2150
- ],
2151
- 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"
2152
- }
2153
- }
2154
- },
2155
- 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."
2156
- },
2157
- compliments: {
2158
- type: "array",
2159
- items: {
2160
- type: "string"
2161
- },
2162
- description: `An array of strings, each representing something the student did well. Each string should be WRITTEN IN ${lang}!`
2163
- },
2164
- improvedResponse: {
2165
- type: "string",
2166
- description: "An improved response with proper grammar and more detail, if applicable."
2167
- },
2168
- score: {
2169
- type: "number",
2170
- description: "A score between 0 and 100, reflecting the overall quality of the response"
2171
- },
2172
- score_justification: {
2173
- type: "string",
2174
- description: "An explanation of the rationale behind the assigned score, considering both accuracy and fluency"
2175
- }
2176
- }
2177
- }
2178
- }
2179
- }
2180
- ]
2181
- };
2182
- if (standard === "wida") {
2183
- const wida_level = {
2184
- type: "number",
2185
- enum: [1, 2, 3, 4, 5, 6],
2186
- 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
2187
-
2188
- 1 - Entering
2189
- 2 - Emerging
2190
- 3 - Developing
2191
- 4 - Expanding
2192
- 5 - Bridging
2193
- 6 - Reaching
2194
-
2195
- 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.
2196
- `
2197
- };
2198
- const wida_justification = {
2199
- type: "string",
2200
- description: `An explanation of the rationale behind the assigned WIDA level of the response, considering both accuracy and fluency. WRITE THIS IN ENGLISH!`
2201
- };
2202
- tool.tools[0].function.parameters.required.push("wida_level");
2203
- tool.tools[0].function.parameters.required.push("wida_justification");
2204
- tool.tools[0].function.parameters.properties.wida_level = wida_level;
2205
- tool.tools[0].function.parameters.properties.wida_justification = wida_justification;
2206
- } else {
2207
- const actfl_level = {
2208
- type: "string",
2209
- enum: ["NL", "NM", "NH", "IL", "IM", "IH", "AL", "AM", "AH", "S", "D"],
2210
- 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"
2211
- };
2212
- const actfl_justification = {
2213
- type: "string",
2214
- description: "An explanation of the rationale behind the assigned ACTFL level, considering both accuracy and fluency"
2215
- };
2216
- tool.tools[0].function.parameters.required.push("actfl_level");
2217
- tool.tools[0].function.parameters.required.push("actfl_justification");
2218
- tool.tools[0].function.parameters.properties.actfl_level = actfl_level;
2219
- tool.tools[0].function.parameters.properties.actfl_justification = actfl_justification;
2220
- }
2221
- return tool;
2222
- };
2223
-
2224
- // src/hooks/useActivity.ts
2225
- import { useEffect as useEffect2 } from "react";
2226
-
2227
- // src/services/add-grading-standard.ts
2228
- var addGradingStandardLog = async (gradingStandard, userId) => {
2229
- logGradingStandardLog(gradingStandard);
2230
- const path = `users/${userId}/grading_standard_logs`;
2231
- await api.addDoc(path, gradingStandard);
2232
- };
2233
-
2234
- // src/hooks/useActivityTracker.ts
2235
- import { v4 as v42 } from "uuid";
2236
- function useActivityTracker({ userId }) {
2237
- const trackActivity = async ({
2238
- activityName,
2239
- activityType,
2240
- id = v42(),
2241
- language = ""
2242
- }) => {
2243
- if (userId) {
2244
- const { doc: doc2, serverTimestamp: serverTimestamp2, setDoc: setDoc2 } = api.accessHelpers();
2245
- const activityRef = doc2(`users/${userId}/activity/${id}`);
2246
- const timestamp = serverTimestamp2();
2247
- await setDoc2(activityRef, {
2248
- name: activityName,
2249
- type: activityType,
2250
- lastSeen: timestamp,
2251
- id,
2252
- language
2253
- });
2254
- }
2255
- };
2256
- return {
2257
- trackActivity
2258
- };
2259
- }
2260
-
2261
- // src/hooks/useActivity.ts
2262
- function useActivity({
2263
- id,
2264
- isAssignment,
2265
- onAssignmentSubmitted,
2266
- ltiData
2267
- }) {
2268
- var _a, _b;
2269
- const { queryClient, user } = useSpeakableApi();
2270
- const userId = user.auth.uid;
2271
- const assignmentQuery = useAssignment({
2272
- assignmentId: id,
2273
- userId,
2274
- enabled: isAssignment
2275
- });
2276
- const activeAssignment = assignmentQuery.data;
2277
- const setId = isAssignment ? (_a = activeAssignment == null ? void 0 : activeAssignment.setId) != null ? _a : "" : id;
2278
- const querySet = useSet({ setId });
2279
- const setData = querySet.data;
2280
- const assignmentContent = activeAssignment == null ? void 0 : activeAssignment.content;
2281
- const assignmentWeights = activeAssignment == null ? void 0 : activeAssignment.weights;
2282
- const setContent = setData == null ? void 0 : setData.content;
2283
- const setWeights = setData == null ? void 0 : setData.weights;
2284
- const contentCardsToUse = isAssignment ? assignmentContent != null ? assignmentContent : setContent : setContent;
2285
- const weightsToUse = isAssignment ? assignmentWeights != null ? assignmentWeights : setWeights : setWeights;
2286
- const activityId = isAssignment ? (_b = activeAssignment == null ? void 0 : activeAssignment.id) != null ? _b : "" : setId;
2287
- const { cardsObject, cardsQueries, cards } = useCards({
2288
- cardIds: contentCardsToUse != null ? contentCardsToUse : [],
2289
- enabled: querySet.isSuccess,
2290
- asObject: true
2291
- });
2292
- const scoreQuery = useScore({
2293
- isAssignment,
2294
- activityId: id,
2295
- userId,
2296
- courseId: activeAssignment == null ? void 0 : activeAssignment.courseId,
2297
- googleClassroomUserId: user.profile.googleClassroomUserId,
2298
- enabled: isAssignment ? assignmentQuery.isSuccess : querySet.isSuccess
2299
- });
2300
- const { mutationUpdateScore } = useUpdateScore();
2301
- const { mutationUpdateCardScore } = useUpdateCardScore({
2302
- activityId,
2303
- isAssignment,
2304
- userId,
2305
- cardIds: contentCardsToUse != null ? contentCardsToUse : [],
2306
- weights: weightsToUse != null ? weightsToUse : {}
2307
- });
2308
- const { mutationClearScore } = useClearScore();
2309
- const { submitAssignmentScore: submitAssignmentScore2 } = useSubmitAssignmentScore({
2310
- onAssignmentSubmitted,
2311
- studentName: user.profile.displayName
2312
- });
2313
- const { submitPracticeScore: submitPracticeScore2 } = useSubmitPracticeScore();
2314
- const handleUpdateScore = (data) => {
2315
- mutationUpdateScore.mutate({
2316
- data,
2317
- isAssignment,
2318
- activityId,
2319
- userId
2320
- });
2321
- };
2322
- const handleUpdateCardScore = (cardId, cardScore) => {
2323
- mutationUpdateCardScore.mutate({ cardId, cardScore });
2324
- if (cardScore.proficiency_level) {
2325
- logGradingStandardEntry({
2326
- type: cardScore.proficiency_level.standardId,
2327
- cardId,
2328
- gradingStandard: cardScore.proficiency_level
2329
- });
2330
- } else if (cardScore.wida || cardScore.actfl) {
2331
- logGradingStandardEntry({
2332
- type: cardScore.wida ? "wida" : "actfl",
2333
- cardId,
2334
- gradingStandard: cardScore.wida || cardScore.actfl || { level: "", justification: "" }
2335
- });
2336
- }
2337
- };
2338
- const onClearScore = ({
2339
- cardId,
2340
- wasCompleted = true
2341
- }) => {
2342
- var _a2, _b2;
2343
- const currentCard = cardsObject == null ? void 0 : cardsObject[cardId];
2344
- if ((currentCard == null ? void 0 : currentCard.type) === "MULTIPLE_CHOICE" /* MULTIPLE_CHOICE */ || (currentCard == null ? void 0 : currentCard.type) === "READ_REPEAT" /* READ_REPEAT */) {
2345
- return;
2346
- }
2347
- const queryKeys = scoreQueryKeys.byId(activityId);
2348
- const activeCardScores = (_b2 = (_a2 = queryClient.getQueryData(queryKeys)) == null ? void 0 : _a2.cards) == null ? void 0 : _b2[cardId];
2349
- if (activeCardScores === void 0) return;
2350
- mutationClearScore.mutate({
2351
- isAssignment,
2352
- activityId,
2353
- cardScores: activeCardScores,
2354
- cardId,
2355
- userId
2356
- });
2357
- };
2358
- const onSubmitScore = async () => {
2359
- var _a2, _b2, _c, _d, _e, _f, _g, _h, _i, _j;
2360
- try {
2361
- let results;
2362
- if (isAssignment) {
2363
- const cardScores = ((_a2 = scoreQuery.data) == null ? void 0 : _a2.cards) || {};
2364
- const hasPendingReview = Object.values(cardScores).some(
2365
- (cardScore) => cardScore.status === "pending_review"
2366
- );
2367
- results = await submitAssignmentScore2({
2368
- assignment: assignmentQuery.data,
2369
- userId,
2370
- cardIds: contentCardsToUse != null ? contentCardsToUse : [],
2371
- scores: scoreQuery.data,
2372
- weights: weightsToUse != null ? weightsToUse : {},
2373
- status: hasPendingReview ? "PENDING_REVIEW" : "FINALIZED"
2374
- });
2375
- if ((_b2 = assignmentQuery.data) == null ? void 0 : _b2.ltiDeeplink) {
2376
- submitLTIScore({
2377
- maxPoints: (_c = assignmentQuery.data) == null ? void 0 : _c.maxPoints,
2378
- score: (_e = (_d = scoreQuery.data) == null ? void 0 : _d.score) != null ? _e : 0,
2379
- SERVICE_KEY: (_f = ltiData == null ? void 0 : ltiData.serviceKey) != null ? _f : "",
2380
- lineItemId: (_g = ltiData == null ? void 0 : ltiData.lineItemId) != null ? _g : "",
2381
- lti_id: (_h = ltiData == null ? void 0 : ltiData.lti_id) != null ? _h : ""
2382
- });
2383
- }
2384
- } else {
2385
- results = await submitPracticeScore2({
2386
- setId: (_j = (_i = querySet.data) == null ? void 0 : _i.id) != null ? _j : "",
2387
- userId,
2388
- scores: scoreQuery.data
2389
- });
2390
- }
2391
- return results;
2392
- } catch (error) {
2393
- return {
2394
- success: false,
2395
- error
2396
- };
2397
- }
2398
- };
2399
- const logGradingStandardEntry = ({
2400
- cardId,
2401
- gradingStandard,
2402
- type
2403
- }) => {
2404
- var _a2, _b2, _c, _d, _e, _f, _g, _h, _i;
2405
- const card = cardsObject == null ? void 0 : cardsObject[cardId];
2406
- const scoresObject = queryClient.getQueryData(scoreQueryKeys.byId(activityId));
2407
- const cardScore = (_a2 = scoresObject == null ? void 0 : scoresObject.cards) == null ? void 0 : _a2[cardId];
2408
- const serverTimestamp2 = api.helpers.serverTimestamp;
2409
- addGradingStandardLog(
2410
- {
2411
- assignmentId: (_b2 = activeAssignment == null ? void 0 : activeAssignment.id) != null ? _b2 : "",
2412
- courseId: (_c = activeAssignment == null ? void 0 : activeAssignment.courseId) != null ? _c : "",
2413
- teacherId: (_d = activeAssignment == null ? void 0 : activeAssignment.owners[0]) != null ? _d : "",
2414
- setId: (_e = setData == null ? void 0 : setData.id) != null ? _e : "",
2415
- cardId,
2416
- level: gradingStandard.level,
2417
- justification: gradingStandard.justification,
2418
- transcript: (_f = cardScore == null ? void 0 : cardScore.transcript) != null ? _f : "",
2419
- audioUrl: (_g = cardScore == null ? void 0 : cardScore.audio) != null ? _g : "",
2420
- prompt: (_h = card == null ? void 0 : card.prompt) != null ? _h : "",
2421
- responseType: (card == null ? void 0 : card.type) === "RESPOND_WRITE" /* RESPOND_WRITE */ ? "written" : "spoken",
2422
- type,
2423
- dateMade: serverTimestamp2(),
2424
- language: (_i = card == null ? void 0 : card.language) != null ? _i : ""
2425
- },
2426
- userId
2427
- );
2428
- };
2429
- useEffect2(() => {
2430
- if (isAssignment) {
2431
- logOpenAssignment({ assignmentId: id });
2432
- } else {
2433
- logOpenActivityPreview({ setId: id });
2434
- }
2435
- }, []);
2436
- useInitActivity({
2437
- assignment: activeAssignment != null ? activeAssignment : void 0,
2438
- set: setData != null ? setData : void 0,
2439
- enabled: !!setData,
2440
- userId
2441
- });
2442
- return {
2443
- set: {
2444
- data: setData,
2445
- query: querySet
2446
- },
2447
- cards: {
2448
- data: cardsObject,
2449
- query: cardsQueries,
2450
- cardsArray: cards
2451
- },
2452
- assignment: {
2453
- data: isAssignment ? activeAssignment : void 0,
2454
- query: assignmentQuery
2455
- },
2456
- scores: {
2457
- data: scoreQuery.data,
2458
- query: scoreQuery,
2459
- actions: {
2460
- update: handleUpdateScore,
2461
- clear: onClearScore,
2462
- submit: onSubmitScore,
2463
- updateCard: handleUpdateCardScore,
2464
- logGradingStandardEntry
2465
- }
2466
- }
2467
- };
2468
- }
2469
- var useInitActivity = ({
2470
- assignment,
2471
- set,
2472
- enabled,
2473
- userId
2474
- }) => {
2475
- const { trackActivity } = useActivityTracker({ userId });
2476
- const init = () => {
2477
- var _a, _b, _c, _d, _e, _f, _g;
2478
- if (!enabled) return;
2479
- if (!assignment) {
2480
- trackActivity({
2481
- activityName: (_a = set == null ? void 0 : set.name) != null ? _a : "",
2482
- activityType: "set",
2483
- id: set == null ? void 0 : set.id,
2484
- language: set == null ? void 0 : set.language
2485
- });
2486
- } else if (assignment.name) {
2487
- trackActivity({
2488
- activityName: assignment.name,
2489
- activityType: assignment.isAssessment ? "assessment" : "assignment",
2490
- id: assignment.id,
2491
- language: set == null ? void 0 : set.language
2492
- });
2493
- }
2494
- if (set == null ? void 0 : set.public) {
2495
- (_d = (_c = (_b = api).httpsCallable) == null ? void 0 : _c.call(_b, "onSetOpened")) == null ? void 0 : _d({
2496
- setId: set.id,
2497
- language: set.language
2498
- });
2499
- }
2500
- (_g = (_f = (_e = api).httpsCallable) == null ? void 0 : _f.call(_e, "updateAlgoliaIndex")) == null ? void 0 : _g({
2501
- updatePlays: true,
2502
- objectID: set == null ? void 0 : set.id
2503
- });
2504
- };
2505
- useEffect2(() => {
2506
- init();
2507
- }, [set]);
2508
- };
2509
- var submitLTIScore = async ({
2510
- maxPoints,
2511
- score,
2512
- SERVICE_KEY,
2513
- lineItemId,
2514
- lti_id
2515
- }) => {
2516
- var _a, _b, _c;
2517
- try {
2518
- if (!SERVICE_KEY || !lineItemId || !lti_id) {
2519
- throw new Error("Missing required LTI credentials");
2520
- }
2521
- const earnedPoints = score ? score / 100 * maxPoints : 0;
2522
- const { data } = await ((_c = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "submitLTIAssignmentScore")) == null ? void 0 : _c({
2523
- SERVICE_KEY,
2524
- scoreData: {
2525
- lineItemId,
2526
- userId: lti_id,
2527
- maxPoints,
2528
- earnedPoints
2529
- }
2530
- }));
2531
- return { success: true, data };
2532
- } catch (error) {
2533
- console.error("Failed to submit LTI score:", error);
2534
- return {
2535
- success: false,
2536
- error: error instanceof Error ? error : new Error("Unknown error occurred")
2537
- };
2538
- }
2539
- };
2540
-
2541
- // src/hooks/useCredits.ts
2542
- import { useQuery as useQuery5 } from "@tanstack/react-query";
2543
- var creditQueryKeys = {
2544
- userCredits: (uid) => ["userCredits", uid]
2545
- };
2546
- var useUserCredits = () => {
2547
- const { user } = useSpeakableApi();
2548
- const email = user.auth.email;
2549
- const uid = user.auth.uid;
2550
- const query2 = useQuery5({
2551
- queryKey: creditQueryKeys.userCredits(uid),
2552
- queryFn: () => fetchUserCredits({ uid, email }),
2553
- enabled: !!uid,
2554
- refetchInterval: 1e3 * 60 * 5
2555
- });
2556
- return {
2557
- ...query2
2558
- };
2559
- };
2560
- var fetchUserCredits = async ({ uid, email }) => {
2561
- if (!uid) {
2562
- throw new Error("User ID is required");
2563
- }
2564
- const contractSnap = await api.getDoc(`creditContracts/${uid}`);
2565
- if (contractSnap.data == null) {
2566
- return {
2567
- id: uid,
2568
- userId: uid,
2569
- email,
2570
- effectivePlanId: "free_tier",
2571
- status: "inactive",
2572
- isUnlimited: false,
2573
- creditsAvailable: 100,
2574
- creditsAllocatedThisPeriod: 100,
2575
- topOffCreditsAvailable: 0,
2576
- topOffCreditsTotal: 0,
2577
- allocationSource: "free_tier",
2578
- sourceDetails: {},
2579
- periodStart: null,
2580
- periodEnd: null,
2581
- planTermEndTimestamp: null,
2582
- ownerType: "individual",
2583
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
2584
- lastUpdatedAt: (/* @__PURE__ */ new Date()).toISOString()
2585
- };
2586
- }
2587
- const contractData = contractSnap.data;
2588
- const monthlyCredits = (contractData == null ? void 0 : contractData.creditsAvailable) || 0;
2589
- const topOffCredits = (contractData == null ? void 0 : contractData.topOffCreditsAvailable) || 0;
2590
- const totalCredits = monthlyCredits + topOffCredits;
2591
- return {
2592
- id: contractSnap.id,
2593
- ...contractData,
2594
- // Add computed total for convenience
2595
- totalCreditsAvailable: totalCredits
2596
- };
2597
- };
2598
-
2599
- // src/hooks/useOrganizationAccess.ts
2600
- import { useQuery as useQuery6 } from "@tanstack/react-query";
2601
- var useOrganizationAccess = () => {
2602
- const { user } = useSpeakableApi();
2603
- const email = user.auth.email;
2604
- const query2 = useQuery6({
2605
- queryKey: ["organizationAccess", email],
2606
- queryFn: async () => {
2607
- if (!email) {
2608
- return {
2609
- hasUnlimitedAccess: false,
2610
- subscriptionId: null,
2611
- organizationId: null,
2612
- organizationName: null,
2613
- subscriptionEndDate: null,
2614
- accessType: "individual"
2615
- };
2616
- }
2617
- return getOrganizationAccess(email);
2618
- },
2619
- enabled: !!email,
2620
- // Only run query if we have a user email
2621
- staleTime: 5 * 60 * 1e3,
2622
- // Consider data fresh for 5 minutes
2623
- gcTime: 10 * 60 * 1e3,
2624
- // Keep in cache for 10 minutes
2625
- retry: 2
2626
- // Retry failed requests twice
2627
- });
2628
- return {
2629
- ...query2
2630
- };
2631
- };
2632
- var getOrganizationAccess = async (email) => {
2633
- const { limit: limit2, where: where2 } = api.accessQueryConstraints();
2634
- try {
2635
- const organizationSnapshot = await api.getDocs(
2636
- "organizations",
2637
- where2("members", "array-contains", email),
2638
- where2("masterSubscriptionStatus", "==", "active"),
2639
- limit2(1)
2640
- );
2641
- if (!organizationSnapshot.empty) {
2642
- const orgData = organizationSnapshot.data[0];
2643
- return {
2644
- hasUnlimitedAccess: true,
2645
- subscriptionId: orgData == null ? void 0 : orgData.masterSubscriptionId,
2646
- organizationId: orgData.id,
2647
- organizationName: orgData.name || "Unknown Organization",
2648
- subscriptionEndDate: orgData.masterSubscriptionEndDate || null,
2649
- accessType: "organization"
2650
- };
2651
- }
2652
- const institutionSnapshot = await api.getDocs(
2653
- "institution_subscriptions",
2654
- where2("users", "array-contains", email),
2655
- where2("active", "==", true),
2656
- limit2(1)
2657
- );
2658
- if (!institutionSnapshot.empty) {
2659
- const institutionData = institutionSnapshot.data[0];
2660
- const isUnlimited = (institutionData == null ? void 0 : institutionData.plan) === "organization" || (institutionData == null ? void 0 : institutionData.plan) === "school_starter";
2661
- return {
2662
- hasUnlimitedAccess: isUnlimited,
2663
- subscriptionId: institutionData.id,
2664
- organizationId: institutionData == null ? void 0 : institutionData.institutionId,
2665
- organizationName: institutionData.name || institutionData.institutionId || "Legacy Institution",
2666
- subscriptionEndDate: institutionData.endDate || null,
2667
- accessType: "institution_subscriptions"
2668
- };
2669
- }
2670
- return {
2671
- hasUnlimitedAccess: false,
2672
- subscriptionId: null,
2673
- organizationId: null,
2674
- organizationName: null,
2675
- subscriptionEndDate: null,
2676
- accessType: "individual"
2677
- };
2678
- } catch (error) {
2679
- console.error("Error checking organization access:", error);
2680
- return {
2681
- hasUnlimitedAccess: false,
2682
- subscriptionId: null,
2683
- organizationId: null,
2684
- organizationName: null,
2685
- subscriptionEndDate: null,
2686
- accessType: "individual"
2687
- };
2688
- }
2689
- };
2690
-
2691
- // src/hooks/useUpdateStudentVoc.ts
2692
- var useUpdateStudentVocab = (page) => {
2693
- const { user } = useSpeakableApi();
2694
- const currentUserId = user == null ? void 0 : user.auth.uid;
2695
- if (!page || !currentUserId || !page.target_text || !page.language) {
2696
- return {
2697
- studentVocabMarkVoiceSuccess: void 0,
2698
- studentVocabMarkVoiceFail: void 0
2699
- };
2700
- }
2701
- const getDataObject = () => {
2702
- var _a, _b;
2703
- const { serverTimestamp: serverTimestamp2 } = api.accessHelpers();
2704
- const language = (_a = page.language) != null ? _a : "en";
2705
- const word = (_b = page.target_text) != null ? _b : "";
2706
- const phrase_length = getPhraseLength(word);
2707
- const wordHash = getWordHash(word, language);
2708
- const docPath = `users/${currentUserId}/vocab/${wordHash}`;
2709
- const communityPath = `checked-pronunciations/${wordHash}`;
2710
- const id = `${language}-${cleanString(word)}`;
2711
- const data = {
2712
- id,
2713
- word,
2714
- words: (word == null ? void 0 : word.split(" ")) || [],
2715
- wordHash,
2716
- language,
2717
- lastSeen: serverTimestamp2(),
2718
- phrase_length
2719
- };
2720
- return {
2721
- docPath,
2722
- communityPath,
2723
- data
2724
- };
2725
- };
2726
- const markVoiceSuccess = async () => {
2727
- const { docPath, communityPath, data } = getDataObject();
2728
- const { increment: increment2 } = api.accessQueryConstraints();
2729
- const { serverTimestamp: serverTimestamp2 } = api.accessHelpers();
2730
- data.voiceSuccess = increment2(1);
2731
- try {
2732
- await api.updateDoc(docPath, data);
2733
- } catch (error) {
2734
- if (error instanceof Error && error.message === "not-found") {
2735
- data.firstSeen = serverTimestamp2();
2736
- await api.setDoc(docPath, data);
2737
- } else {
2738
- console.log(error);
2739
- }
2740
- }
2741
- try {
2742
- data.pronunciations = increment2(1);
2743
- await api.setDoc(communityPath, data, { merge: true });
2744
- } catch (error) {
2745
- console.log(error);
2746
- }
2747
- };
2748
- const markVoiceFail = async () => {
2749
- const { docPath, communityPath, data } = getDataObject();
2750
- const { increment: increment2 } = api.accessQueryConstraints();
2751
- const { serverTimestamp: serverTimestamp2 } = api.accessHelpers();
2752
- data.voiceFail = increment2(1);
2753
- try {
2754
- await api.updateDoc(docPath, data);
2755
- } catch (error) {
2756
- if (error instanceof Error && error.message === "not-found") {
2757
- data.firstSeen = serverTimestamp2();
2758
- await api.setDoc(docPath, data);
2759
- } else {
2760
- console.log(error);
2761
- }
2762
- }
2763
- try {
2764
- data.fails = increment2(1);
2765
- await api.setDoc(communityPath, data, { merge: true });
2766
- } catch (error) {
2767
- console.log(error);
2768
- }
2769
- };
2770
- return {
2771
- studentVocabMarkVoiceSuccess: markVoiceSuccess,
2772
- studentVocabMarkVoiceFail: markVoiceFail
2773
- };
2774
- };
2775
-
2776
- // src/hooks/useActivityFeedbackAccess.ts
2777
- import { useQuery as useQuery7 } from "@tanstack/react-query";
2778
- var activityFeedbackAccessQueryKeys = {
2779
- activityFeedbackAccess: (args) => ["activityFeedbackAccess", ...Object.values(args)]
2780
- };
2781
- var useActivityFeedbackAccess = ({
2782
- aiEnabled = false,
2783
- isActivityRoute = false
2784
- }) => {
2785
- var _a, _b, _c;
2786
- const { user } = useSpeakableApi();
2787
- const uid = user.auth.uid;
2788
- const isTeacher = (_a = user.profile) == null ? void 0 : _a.isTeacher;
2789
- const isStudent = (_b = user.profile) == null ? void 0 : _b.isStudent;
2790
- const userRoles = ((_c = user.profile) == null ? void 0 : _c.roles) || [];
2791
- const query2 = useQuery7({
2792
- queryKey: activityFeedbackAccessQueryKeys.activityFeedbackAccess({
2793
- aiEnabled,
2794
- isActivityRoute
2795
- }),
2796
- queryFn: async () => {
2797
- var _a2, _b2, _c2;
2798
- if (!uid) {
2799
- return {
2800
- canAccessFeedback: false,
2801
- reason: "Missing user ID",
2802
- isUnlimited: false,
2803
- accessType: "none"
2804
- };
2805
- }
2806
- try {
2807
- if (aiEnabled) {
2808
- return {
2809
- canAccessFeedback: true,
2810
- reason: "AI feedback enabled",
2811
- isUnlimited: true,
2812
- accessType: "ai_enabled"
2813
- };
2814
- }
2815
- if (isTeacher || userRoles.includes("ADMIN")) {
2816
- return {
2817
- canAccessFeedback: true,
2818
- reason: "Teacher preview access",
2819
- isUnlimited: true,
2820
- accessType: "teacher_preview"
2821
- };
2822
- }
2823
- if (isStudent && isActivityRoute) {
2824
- try {
2825
- const result = await ((_c2 = (_b2 = (_a2 = api).httpsCallable) == null ? void 0 : _b2.call(_a2, "checkStudentTeacherPlan")) == null ? void 0 : _c2({
2826
- studentId: uid
2827
- }));
2828
- const planCheckResult = result.data;
2829
- if (planCheckResult.canAccessFeedback) {
2830
- return {
2831
- canAccessFeedback: true,
2832
- reason: planCheckResult.reason || "Student access via teacher with active plan",
2833
- isUnlimited: planCheckResult.hasTeacherWithUnlimitedAccess,
2834
- accessType: "student_with_teacher_plan"
2835
- };
2836
- } else {
2837
- return {
2838
- canAccessFeedback: false,
2839
- reason: planCheckResult.reason || "No teacher with active plan found",
2840
- isUnlimited: false,
2841
- accessType: "none"
2842
- };
2843
- }
2844
- } catch (error) {
2845
- console.error("Error checking student teacher plan:", error);
2846
- return {
2847
- canAccessFeedback: false,
2848
- reason: "Error checking teacher plans",
2849
- isUnlimited: false,
2850
- accessType: "none"
2851
- };
2852
- }
2853
- }
2854
- return {
2855
- canAccessFeedback: false,
2856
- reason: "No access permissions found for current context",
2857
- isUnlimited: false,
2858
- accessType: "none"
2859
- };
2860
- } catch (error) {
2861
- console.error("Error checking activity feedback access:", error);
2862
- return {
2863
- canAccessFeedback: false,
2864
- reason: "Error checking access permissions",
2865
- isUnlimited: false,
2866
- accessType: "none"
2867
- };
2868
- }
2869
- },
2870
- enabled: !!uid,
2871
- staleTime: 5 * 60 * 1e3,
2872
- // 5 minutes
2873
- gcTime: 10 * 60 * 1e3
2874
- // 10 minutes
2875
- });
2876
- return {
2877
- ...query2
2878
- };
2879
- };
2880
-
2881
- // src/hooks/useOpenAI.ts
2882
- var useBaseOpenAI = ({
2883
- onTranscriptSuccess,
2884
- onTranscriptError,
2885
- onCompletionSuccess,
2886
- onCompletionError,
2887
- aiEnabled,
2888
- submitAudioResponse,
2889
- uploadAudioAndGetTranscript
2890
- }) => {
2891
- const { user, queryClient } = useSpeakableApi();
2892
- const currentUserId = user.auth.uid;
2893
- const { data: feedbackAccess } = useActivityFeedbackAccess({
2894
- aiEnabled
2895
- });
2896
- const getTranscript = async (audioUrl, language) => {
2897
- var _a, _b;
2898
- try {
2899
- const getAssemblyAITranscript = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "transcribeAssemblyAIAudio");
2900
- const response = await (getAssemblyAITranscript == null ? void 0 : getAssemblyAITranscript({
2901
- audioUrl,
2902
- language
2903
- }));
2904
- console.log("response (getTranscript) from getAssemblyAITranscript", {
2905
- response,
2906
- audioUrl,
2907
- language,
2908
- getAssemblyAITranscript
2909
- });
2910
- const transcript = response == null ? void 0 : response.data;
2911
- onTranscriptSuccess(transcript);
2912
- return transcript;
2913
- } catch (error) {
2914
- console.log("error", error);
2915
- onTranscriptError({
2916
- type: "TRANSCRIPT",
2917
- message: (error == null ? void 0 : error.message) || "Error getting transcript"
2918
- });
2919
- throw new Error(error);
2920
- }
2921
- };
2922
- const getFreeResponseCompletion = async (messages, isFreeResponse, feedbackLanguage, gradingStandard = "actfl") => {
2923
- var _a, _b, _c, _d, _e;
2924
- const responseTool = getRespondCardTool({
2925
- language: feedbackLanguage,
2926
- standard: gradingStandard
2927
- });
2928
- try {
2929
- const createChatCompletion = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "createChatCompletion");
2930
- const {
2931
- data: {
2932
- response,
2933
- prompt_tokens = 0,
2934
- completion_tokens = 0,
2935
- success: aiSuccess = false
2936
- // the AI was able to generate a response
2937
- }
2938
- } = await (createChatCompletion == null ? void 0 : createChatCompletion({
2939
- chat: {
2940
- model: isFreeResponse ? "gpt-4-1106-preview" : "gpt-3.5-turbo-1106",
2941
- messages,
2942
- temperature: 0.7,
2943
- ...responseTool
2944
- },
2945
- type: isFreeResponse ? "LONG_RESPONSE" : "SHORT_RESPONSE"
2946
- }));
2947
- 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) || "{}");
2948
- const result = {
2949
- ...functionArguments,
2950
- prompt_tokens,
2951
- completion_tokens,
2952
- aiSuccess
2953
- };
2954
- onCompletionSuccess(result);
2955
- return result;
2956
- } catch (error) {
2957
- onCompletionError({
2958
- type: "COMPLETION",
2959
- message: (error == null ? void 0 : error.message) || "Error getting completion"
2960
- });
2961
- throw new Error(error);
2962
- }
2963
- };
2964
- const getFeedback = async ({
2965
- cardId,
2966
- language = "en",
2967
- // required
2968
- writtenResponse = null,
2969
- // if the type = RESPOND_WRITE
2970
- audio = null,
2971
- autoGrade = true,
2972
- file = null
2973
- }) => {
2974
- try {
2975
- if (!(feedbackAccess == null ? void 0 : feedbackAccess.canAccessFeedback)) {
2976
- const result = {
2977
- noFeedbackAvailable: true,
2978
- success: true,
2979
- reason: (feedbackAccess == null ? void 0 : feedbackAccess.reason) || "No feedback access",
2980
- accessType: (feedbackAccess == null ? void 0 : feedbackAccess.accessType) || "none"
2981
- };
2982
- onCompletionSuccess(result);
2983
- return result;
2984
- }
2985
- let transcript;
2986
- if (writtenResponse) {
2987
- transcript = writtenResponse;
2988
- onTranscriptSuccess(writtenResponse);
2989
- } else if (typeof audio === "string" && file) {
2990
- if (feedbackAccess == null ? void 0 : feedbackAccess.canAccessFeedback) {
2991
- transcript = await getTranscript(audio, language);
2992
- onTranscriptSuccess(transcript);
2993
- } else {
2994
- console.info(
2995
- `Transcript not available: ${(feedbackAccess == null ? void 0 : feedbackAccess.reason) || "No feedback access"}`
2996
- );
2997
- }
2998
- } else {
2999
- transcript = await uploadAudioAndGetTranscript(audio || "", language);
3000
- }
3001
- if (feedbackAccess == null ? void 0 : feedbackAccess.canAccessFeedback) {
3002
- const results = await getAIResponse({
3003
- cardId,
3004
- transcript: transcript || ""
3005
- });
3006
- let output = results;
3007
- if (!autoGrade) {
3008
- output = {
3009
- ...output,
3010
- noFeedbackAvailable: true,
3011
- success: true
3012
- };
3013
- }
3014
- onCompletionSuccess(output);
3015
- return output;
3016
- } else {
3017
- const result = {
3018
- noFeedbackAvailable: true,
3019
- success: true,
3020
- reason: (feedbackAccess == null ? void 0 : feedbackAccess.reason) || "No feedback access",
3021
- accessType: (feedbackAccess == null ? void 0 : feedbackAccess.accessType) || "none"
3022
- };
3023
- onCompletionSuccess(result);
3024
- return result;
3025
- }
3026
- } catch (error) {
3027
- console.error("Error getting feedback:", error);
3028
- throw new Error(error);
3029
- }
3030
- };
3031
- const getAIResponse = async ({ cardId, transcript }) => {
3032
- var _a, _b, _c, _d, _e;
3033
- try {
3034
- const getGeminiFeedback = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "callGetFeedback");
3035
- const getProficiencyEstimate = (_d = (_c = api).httpsCallable) == null ? void 0 : _d.call(_c, "getProficiencyEstimate");
3036
- const card = getCardFromCache({
3037
- cardId,
3038
- queryClient
3039
- });
3040
- let feedbackData;
3041
- let proficiencyData = {};
3042
- if (card && card.grading_method === "manual") {
3043
- } else if (card && card.grading_method !== "standards_based") {
3044
- const [geminiResult, proficiencyResult] = await Promise.all([
3045
- getGeminiFeedback == null ? void 0 : getGeminiFeedback({
3046
- cardId,
3047
- studentId: currentUserId,
3048
- studentResponse: transcript
3049
- }),
3050
- getProficiencyEstimate == null ? void 0 : getProficiencyEstimate({
3051
- cardId,
3052
- studentId: currentUserId,
3053
- studentResponse: transcript
3054
- })
3055
- ]);
3056
- proficiencyData = (proficiencyResult == null ? void 0 : proficiencyResult.data) || {};
3057
- feedbackData = {
3058
- ...(_e = geminiResult == null ? void 0 : geminiResult.data) != null ? _e : {},
3059
- // @ts-ignore
3060
- proficiency_level: (proficiencyData == null ? void 0 : proficiencyData.proficiency_level) || null
3061
- };
3062
- } else {
3063
- const geminiResult = await (getGeminiFeedback == null ? void 0 : getGeminiFeedback({
3064
- cardId,
3065
- studentId: currentUserId,
3066
- studentResponse: transcript
3067
- }));
3068
- feedbackData = geminiResult == null ? void 0 : geminiResult.data;
3069
- }
3070
- const results = {
3071
- ...feedbackData,
3072
- // ...proficiencyData,
3073
- aiSuccess: true,
3074
- promptSuccess: (feedbackData == null ? void 0 : feedbackData.success) || false,
3075
- transcript
3076
- };
3077
- return results;
3078
- } catch (error) {
3079
- onCompletionError({
3080
- type: "AI_FEEDBACK",
3081
- message: (error == null ? void 0 : error.message) || "Error getting ai feedback"
3082
- });
3083
- throw new Error(error);
3084
- }
3085
- };
3086
- return {
3087
- submitAudioResponse,
3088
- uploadAudioAndGetTranscript,
3089
- getTranscript,
3090
- getFreeResponseCompletion,
3091
- getFeedback
3092
- };
3093
- };
3094
-
3095
- // src/lib/create-firebase-client-web.ts
3096
- import {
3097
- getDoc,
3098
- getDocs,
3099
- addDoc,
3100
- setDoc,
3101
- updateDoc,
3102
- deleteDoc,
3103
- runTransaction,
3104
- writeBatch,
3105
- doc,
3106
- collection,
3107
- query,
3108
- serverTimestamp,
3109
- orderBy,
3110
- limit,
3111
- startAt,
3112
- startAfter,
3113
- endAt,
3114
- endBefore,
3115
- where,
3116
- increment
3117
- } from "firebase/firestore";
3118
-
3119
- // src/lib/create-firebase-client.ts
3120
- function createFsClientBase({
3121
- db,
3122
- helpers,
3123
- httpsCallable,
3124
- logEvent
3125
- }) {
3126
- const dbAsFirestore = db;
3127
- api.initialize({
3128
- db: dbAsFirestore,
3129
- helpers,
3130
- httpsCallable,
3131
- logEvent
3132
- });
3133
- return {
3134
- assignmentRepo: createAssignmentRepo(),
3135
- cardRepo: createCardRepo()
3136
- };
3137
- }
3138
-
3139
- // src/lib/create-firebase-client-web.ts
3140
- var createFsClientWeb = ({ db, httpsCallable, logEvent }) => {
3141
- return createFsClientBase({
3142
- db,
3143
- httpsCallable,
3144
- logEvent,
3145
- helpers: {
3146
- getDoc,
3147
- getDocs,
3148
- addDoc,
3149
- setDoc,
3150
- updateDoc,
3151
- deleteDoc,
3152
- runTransaction,
3153
- writeBatch,
3154
- doc,
3155
- collection,
3156
- query,
3157
- serverTimestamp,
3158
- orderBy,
3159
- limit,
3160
- startAt,
3161
- startAfter,
3162
- endAt,
3163
- endBefore,
3164
- where,
3165
- increment
3166
- }
3167
- });
3168
- };
3169
- export {
3170
- ActivityPageType,
3171
- BASE_MULTIPLE_CHOICE_FIELD_VALUES,
3172
- BASE_REPEAT_FIELD_VALUES,
3173
- BASE_RESPOND_FIELD_VALUES,
3174
- FeedbackTypesCard,
3175
- FsCtx,
3176
- LENIENCY_OPTIONS,
3177
- LeniencyCard,
3178
- MULTIPLE_CHOICE_PAGE_ACTIVITY_TYPES,
3179
- REPEAT_PAGE_ACTIVITY_TYPES,
3180
- RESPOND_AUDIO_PAGE_ACTIVITY_TYPES,
3181
- RESPOND_PAGE_ACTIVITY_TYPES,
3182
- RESPOND_WRITE_PAGE_ACTIVITY_TYPES,
3183
- SPEAKABLE_NOTIFICATIONS,
3184
- STUDENT_LEVELS_OPTIONS,
3185
- SpeakableNotificationTypes,
3186
- SpeakableProvider,
3187
- VerificationCardStatus,
3188
- assignmentQueryKeys,
3189
- cardsQueryKeys,
3190
- checkIsMCPage,
3191
- checkIsMediaPage,
3192
- checkIsRepeatPage,
3193
- checkIsRespondAudioPage,
3194
- checkIsRespondPage,
3195
- checkIsRespondWrittenPage,
3196
- checkIsShortAnswerPage,
3197
- checkTypePageActivity,
3198
- cleanString,
3199
- createAssignmentRepo,
3200
- createCardRepo,
3201
- createFsClientWeb as createFsClient,
3202
- createSetRepo,
3203
- creditQueryKeys,
3204
- debounce,
3205
- getCardFromCache,
3206
- getPagePrompt,
3207
- getPhraseLength,
3208
- getRespondCardTool,
3209
- getSetFromCache,
3210
- getWordHash,
3211
- purify,
3212
- refsCardsFiresotre,
3213
- refsSetsFirestore,
3214
- scoreQueryKeys,
3215
- setsQueryKeys,
3216
- updateCardInCache,
3217
- updateSetInCache,
3218
- useActivity,
3219
- useActivityFeedbackAccess,
3220
- useAssignment,
3221
- useBaseOpenAI,
3222
- useCards,
3223
- useClearScore,
3224
- useCreateCard,
3225
- useCreateCards,
3226
- useCreateNotification,
3227
- useGetCard,
3228
- useOrganizationAccess,
3229
- useScore,
3230
- useSet,
3231
- useSpeakableApi,
3232
- useSubmitAssignmentScore,
3233
- useSubmitPracticeScore,
3234
- useUpdateCardScore,
3235
- useUpdateScore,
3236
- useUpdateStudentVocab,
3237
- useUserCredits
3238
- };
3239
- //# sourceMappingURL=index.web.mjs.map