@speakableio/core 1.0.18 → 1.0.20

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.
@@ -30,114 +30,12 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/entry-points/index.native.ts
31
31
  var index_native_exports = {};
32
32
  __export(index_native_exports, {
33
- ActivityPageType: () => ActivityPageType,
34
- BASE_MULTIPLE_CHOICE_FIELD_VALUES: () => BASE_MULTIPLE_CHOICE_FIELD_VALUES,
35
- BASE_REPEAT_FIELD_VALUES: () => BASE_REPEAT_FIELD_VALUES,
36
- BASE_RESPOND_FIELD_VALUES: () => BASE_RESPOND_FIELD_VALUES,
37
- FeedbackTypesCard: () => FeedbackTypesCard,
38
- FsCtx: () => FsCtx,
39
- LENIENCY_OPTIONS: () => LENIENCY_OPTIONS,
40
- LeniencyCard: () => LeniencyCard,
41
- MULTIPLE_CHOICE_PAGE_ACTIVITY_TYPES: () => MULTIPLE_CHOICE_PAGE_ACTIVITY_TYPES,
42
- REPEAT_PAGE_ACTIVITY_TYPES: () => REPEAT_PAGE_ACTIVITY_TYPES,
43
- RESPOND_AUDIO_PAGE_ACTIVITY_TYPES: () => RESPOND_AUDIO_PAGE_ACTIVITY_TYPES,
44
- RESPOND_PAGE_ACTIVITY_TYPES: () => RESPOND_PAGE_ACTIVITY_TYPES,
45
- RESPOND_WRITE_PAGE_ACTIVITY_TYPES: () => RESPOND_WRITE_PAGE_ACTIVITY_TYPES,
46
- SPEAKABLE_NOTIFICATIONS: () => SPEAKABLE_NOTIFICATIONS,
47
- STUDENT_LEVELS_OPTIONS: () => STUDENT_LEVELS_OPTIONS,
48
- SpeakableNotificationTypes: () => SpeakableNotificationTypes,
49
- SpeakableProvider: () => SpeakableProvider,
50
- VerificationCardStatus: () => VerificationCardStatus,
51
- assignmentQueryKeys: () => assignmentQueryKeys,
52
- cardsQueryKeys: () => cardsQueryKeys,
53
- checkIsMCPage: () => checkIsMCPage,
54
- checkIsMediaPage: () => checkIsMediaPage,
55
- checkIsRepeatPage: () => checkIsRepeatPage,
56
- checkIsRespondAudioPage: () => checkIsRespondAudioPage,
57
- checkIsRespondPage: () => checkIsRespondPage,
58
- checkIsRespondWrittenPage: () => checkIsRespondWrittenPage,
59
- checkIsShortAnswerPage: () => checkIsShortAnswerPage,
60
- checkTypePageActivity: () => checkTypePageActivity,
61
- cleanString: () => cleanString,
62
- createAssignmentRepo: () => createAssignmentRepo,
63
- createCardRepo: () => createCardRepo,
64
- createFsClient: () => createFsClientNative,
65
- createSetRepo: () => createSetRepo,
66
- creditQueryKeys: () => creditQueryKeys,
67
- debounce: () => debounce,
68
- getCardFromCache: () => getCardFromCache,
69
- getLabelPage: () => getLabelPage,
70
- getPagePrompt: () => getPagePrompt,
71
- getPhraseLength: () => getPhraseLength,
72
- getRespondCardTool: () => getRespondCardTool,
73
- getSetFromCache: () => getSetFromCache,
74
- getTotalCompletedCards: () => getTotalCompletedCards,
75
- getWordHash: () => getWordHash,
76
- purify: () => purify,
77
- refsCardsFiresotre: () => refsCardsFiresotre,
78
- refsSetsFirestore: () => refsSetsFirestore,
79
- scoreQueryKeys: () => scoreQueryKeys,
80
- setsQueryKeys: () => setsQueryKeys,
81
- updateCardInCache: () => updateCardInCache,
82
- updateSetInCache: () => updateSetInCache,
83
- useActivity: () => useActivity,
84
- useActivityFeedbackAccess: () => useActivityFeedbackAccess,
85
- useAssignment: () => useAssignment,
86
- useBaseOpenAI: () => useBaseOpenAI,
87
- useCards: () => useCards,
88
- useClearScore: () => useClearScore,
89
- useClearScoreV2: () => useClearScoreV2,
90
- useCreateCard: () => useCreateCard,
91
- useCreateCards: () => useCreateCards,
92
- useCreateNotification: () => useCreateNotification,
93
- useGetCard: () => useGetCard,
94
- useOrganizationAccess: () => useOrganizationAccess,
95
- useScore: () => useScore,
96
- useSet: () => useSet,
97
- useSpeakableApi: () => useSpeakableApi,
98
- useSubmitAssignmentScore: () => useSubmitAssignmentScore,
99
- useSubmitPracticeScore: () => useSubmitPracticeScore,
100
- useUpdateCardScore: () => useUpdateCardScore,
101
- useUpdateScore: () => useUpdateScore,
102
- useUpdateStudentVocab: () => useUpdateStudentVocab,
103
- useUserCredits: () => useUserCredits
33
+ createFsClient: () => createFsClientNative
104
34
  });
105
35
  module.exports = __toCommonJS(index_native_exports);
106
36
 
107
- // src/providers/SpeakableProvider.tsx
108
- var import_react = require("react");
109
- var import_jsx_runtime = require("react/jsx-runtime");
110
- var FsCtx = (0, import_react.createContext)(null);
111
- function SpeakableProvider({
112
- user,
113
- children,
114
- queryClient,
115
- permissions,
116
- fsClient
117
- }) {
118
- const [speakableApi, setSpeakableApi] = (0, import_react.useState)(null);
119
- (0, import_react.useEffect)(() => {
120
- setSpeakableApi(fsClient);
121
- }, [fsClient]);
122
- if (!speakableApi) return null;
123
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
124
- FsCtx.Provider,
125
- {
126
- value: {
127
- speakableApi,
128
- queryClient,
129
- user,
130
- permissions
131
- },
132
- children
133
- }
134
- );
135
- }
136
- function useSpeakableApi() {
137
- const ctx = (0, import_react.useContext)(FsCtx);
138
- if (!ctx) throw new Error("useSpeakableApi must be used within a SpeakableProvider");
139
- return ctx;
140
- }
37
+ // src/lib/create-firebase-client-native.ts
38
+ var import_firestore = require("@react-native-firebase/firestore");
141
39
 
142
40
  // src/utils/error-handler.ts
143
41
  var ServiceError = class extends Error {
@@ -447,30 +345,13 @@ var createAssignmentRepo = () => {
447
345
  };
448
346
  };
449
347
 
348
+ // src/providers/SpeakableProvider.tsx
349
+ var import_react = require("react");
350
+ var import_jsx_runtime = require("react/jsx-runtime");
351
+ var FsCtx = (0, import_react.createContext)(null);
352
+
450
353
  // src/domains/assignment/hooks/assignment.hooks.ts
451
354
  var import_react_query = require("@tanstack/react-query");
452
- var assignmentQueryKeys = {
453
- all: ["assignments"],
454
- byId: (id) => [...assignmentQueryKeys.all, id],
455
- list: () => [...assignmentQueryKeys.all, "list"]
456
- };
457
- function useAssignment({
458
- assignmentId,
459
- enabled = true,
460
- analyticType,
461
- userId
462
- }) {
463
- const { speakableApi } = useSpeakableApi();
464
- return (0, import_react_query.useQuery)({
465
- queryKey: assignmentQueryKeys.byId(assignmentId),
466
- queryFn: () => speakableApi.assignmentRepo.getAssignment({
467
- assignmentId,
468
- analyticType,
469
- currentUserId: userId
470
- }),
471
- enabled
472
- });
473
- }
474
355
 
475
356
  // src/domains/assignment/hooks/score-hooks.ts
476
357
  var import_react_query2 = require("@tanstack/react-query");
@@ -493,24 +374,6 @@ function debounce(func, waitFor) {
493
374
  });
494
375
  }
495
376
 
496
- // src/lib/tanstack/handle-optimistic-update-query.ts
497
- var handleOptimisticUpdate = async ({
498
- queryClient,
499
- queryKey,
500
- newData
501
- }) => {
502
- await queryClient.cancelQueries({
503
- queryKey
504
- });
505
- const previousData = queryClient.getQueryData(queryKey);
506
- if (previousData === void 0) {
507
- queryClient.setQueryData(queryKey, newData);
508
- } else {
509
- queryClient.setQueryData(queryKey, { ...previousData, ...newData });
510
- }
511
- return { previousData };
512
- };
513
-
514
377
  // src/constants/speakable-plans.ts
515
378
  var FEEDBACK_PLANS = {
516
379
  FEEDBACK_TRANSCRIPT: "FEEDBACK_TRANSCRIPT",
@@ -667,64 +530,9 @@ var SpeakablePlanHierarchy = [
667
530
  SpeakablePlanTypes.organization
668
531
  ];
669
532
 
670
- // src/hooks/usePermissions.ts
671
- var usePermissions = () => {
672
- const { permissions } = useSpeakableApi();
673
- const has = (permission) => {
674
- var _a;
675
- return (_a = permissions.permissions) == null ? void 0 : _a.includes(permission);
676
- };
677
- return {
678
- plan: permissions.plan,
679
- permissionsLoaded: permissions.loaded,
680
- isStripePlan: permissions.isStripePlan,
681
- refreshDate: permissions.refreshDate,
682
- isInstitutionPlan: permissions.isInstitutionPlan,
683
- subscriptionId: permissions.subscriptionId,
684
- contact: permissions.contact,
685
- hasGradebook: has(ANALYTICS_PLANS.ANALYTICS_GRADEBOOK),
686
- hasGoogleClassroomGradePassback: has(ASSIGNMENT_SETTINGS_PLANS.GOOGLE_CLASSROOM_GRADE_PASSBACK),
687
- hasAssessments: has(ASSIGNMENT_SETTINGS_PLANS.ASSESSMENTS),
688
- hasSectionAnalytics: has(ANALYTICS_PLANS.ANALYTICS_CLASSROOM_ANALYTICS),
689
- hasStudentReports: has(ANALYTICS_PLANS.ANALYTICS_STUDENT_PROGRESS_REPORTS),
690
- permissions: permissions || [],
691
- hasStudentPortfolios: permissions.hasStudentPortfolios,
692
- isFreeOrgTrial: permissions.type === "free_org_trial",
693
- freeOrgTrialExpired: permissions.freeOrgTrialExpired
694
- };
695
- };
696
- var usePermissions_default = usePermissions;
697
-
698
- // src/domains/notification/notification.constants.ts
699
- var SPEAKABLE_NOTIFICATIONS = {
700
- NEW_ASSIGNMENT: "new_assignment",
701
- ASSESSMENT_SUBMITTED: "assessment_submitted",
702
- ASSESSMENT_SCORED: "assessment_scored",
703
- NEW_COMMENT: "NEW_COMMENT"
704
- };
705
- var SpeakableNotificationTypes = {
706
- NEW_ASSIGNMENT: "NEW_ASSIGNMENT",
707
- FEEDBACK_FROM_TEACHER: "FEEDBACK_FROM_TEACHER",
708
- MESSAGE_FROM_STUDENT: "MESSAGE_FROM_STUDENT",
709
- PHRASE_MARKED_CORRECT: "PHRASE_MARKED_CORRECT",
710
- STUDENT_PROGRESS: "STUDENT_PROGRESS",
711
- PLAYLIST_FOLLOWERS: "PLAYLIST_FOLLOWERS",
712
- PLAYLIST_PLAYS: "PLAYLIST_PLAYS",
713
- // New notifications
714
- ASSESSMENT_SUBMITTED: "ASSESSMENT_SUBMITTED",
715
- // Notification FOR TEACHER when student submits assessment
716
- ASSESSMENT_SCORED: "ASSESSMENT_SCORED",
717
- // Notification FOR STUDENT when teacher scores assessment
718
- // Comment
719
- NEW_COMMENT: "NEW_COMMENT"
720
- };
721
-
722
533
  // src/domains/notification/services/create-notification.service.ts
723
534
  var import_dayjs2 = __toESM(require("dayjs"));
724
535
 
725
- // src/constants/web.constants.ts
726
- var WEB_BASE_URL = "https://app.speakable.io";
727
-
728
536
  // src/domains/notification/services/send-notification.service.ts
729
537
  var _sendNotification = async (sendTo, notification) => {
730
538
  var _a, _b, _c;
@@ -737,202 +545,6 @@ var _sendNotification = async (sendTo, notification) => {
737
545
  };
738
546
  var sendNotification = withErrorHandler(_sendNotification, "sendNotification");
739
547
 
740
- // src/domains/notification/services/create-notification.service.ts
741
- var createNotification = async ({
742
- data,
743
- type,
744
- userId,
745
- profile
746
- }) => {
747
- let result;
748
- switch (type) {
749
- case SPEAKABLE_NOTIFICATIONS.NEW_ASSIGNMENT:
750
- result = await handleAssignNotifPromise({ data, profile });
751
- break;
752
- case SPEAKABLE_NOTIFICATIONS.ASSESSMENT_SUBMITTED:
753
- result = await createAssessmentSubmissionNotification({
754
- data,
755
- profile,
756
- userId
757
- });
758
- break;
759
- case SPEAKABLE_NOTIFICATIONS.ASSESSMENT_SCORED:
760
- result = await createAssessmentScoredNotification({
761
- data,
762
- profile
763
- });
764
- break;
765
- default:
766
- result = null;
767
- break;
768
- }
769
- return result;
770
- };
771
- var handleAssignNotifPromise = async ({
772
- data: assignments,
773
- profile
774
- }) => {
775
- if (!assignments.length) return;
776
- try {
777
- const notifsPromises = assignments.map(async (assignment) => {
778
- const {
779
- section,
780
- section: { members },
781
- ...rest
782
- } = assignment;
783
- if (!section || !members) throw new Error("Invalid assignment data");
784
- const data = { section, sendTo: members, assignment: { ...rest } };
785
- return createNewAssignmentNotification({ data, profile });
786
- });
787
- await Promise.all(notifsPromises);
788
- return {
789
- success: true,
790
- message: "Assignment notifications sent successfully"
791
- };
792
- } catch (error) {
793
- console.error("Error in handleAssignNotifPromise:", error);
794
- throw error;
795
- }
796
- };
797
- var createNewAssignmentNotification = async ({
798
- data,
799
- profile
800
- }) => {
801
- var _a;
802
- const { assignment, sendTo } = data;
803
- const teacherName = profile.displayName || "Your teacher";
804
- const dueDate = assignment.dueDateTimestamp ? (0, import_dayjs2.default)(assignment.dueDateTimestamp.toDate()).format("MMM Do") : null;
805
- const results = await sendNotification(sendTo, {
806
- courseId: assignment.courseId,
807
- type: SPEAKABLE_NOTIFICATIONS.NEW_ASSIGNMENT,
808
- senderName: teacherName,
809
- link: `${WEB_BASE_URL}/assignment/${assignment.id}`,
810
- messagePreview: `A new assignment "${assignment.name}" is now available. ${dueDate ? `Due ${dueDate}` : ""}`,
811
- title: "New Assignment Available!",
812
- imageUrl: (_a = profile.image) == null ? void 0 : _a.url
813
- });
814
- return results;
815
- };
816
- var createAssessmentSubmissionNotification = async ({
817
- data: assignment,
818
- profile,
819
- userId
820
- }) => {
821
- var _a;
822
- const studentName = profile.displayName || "Your student";
823
- const results = await sendNotification(assignment.owners, {
824
- courseId: assignment.courseId,
825
- type: SPEAKABLE_NOTIFICATIONS.ASSESSMENT_SUBMITTED,
826
- link: `${WEB_BASE_URL}/a/${assignment.id}?studentId=${userId}`,
827
- title: `Assessment Submitted!`,
828
- senderName: studentName,
829
- messagePreview: `${studentName} has submitted the assessment "${assignment.name}"`,
830
- imageUrl: (_a = profile.image) == null ? void 0 : _a.url
831
- });
832
- return results;
833
- };
834
- var createAssessmentScoredNotification = async ({
835
- data,
836
- profile
837
- }) => {
838
- var _a, _b, _c, _d, _e;
839
- const { assignment, sendTo } = data;
840
- const teacherName = profile.displayName || "Your teacher";
841
- const title = `${assignment.isAssessment ? "Assessment" : "Assignment"} Reviewed!`;
842
- const messagePreview = `Your ${assignment.isAssessment ? "assessment" : "assignment"} has been reviewed by your teacher. Click to view the feedback.`;
843
- const results = await sendNotification(sendTo, {
844
- courseId: assignment.courseId,
845
- type: SPEAKABLE_NOTIFICATIONS.ASSESSMENT_SCORED,
846
- link: `${WEB_BASE_URL}/assignment/${assignment.id}`,
847
- title,
848
- messagePreview,
849
- imageUrl: (_a = profile.image) == null ? void 0 : _a.url,
850
- senderName: teacherName
851
- });
852
- await ((_e = (_c = (_b = api).httpsCallable) == null ? void 0 : _c.call(_b, "sendAssessmentScoredEmail")) == null ? void 0 : _e({
853
- assessmentTitle: assignment.name,
854
- link: `${WEB_BASE_URL}/assignment/${assignment.id}`,
855
- senderImage: ((_d = profile.image) == null ? void 0 : _d.url) || "",
856
- studentId: sendTo[0],
857
- teacherName: profile.displayName
858
- }));
859
- return results;
860
- };
861
-
862
- // src/domains/notification/hooks/notification.hooks.ts
863
- var notificationQueryKeys = {
864
- all: ["notifications"],
865
- byId: (id) => [...notificationQueryKeys.all, id]
866
- };
867
- var useCreateNotification = () => {
868
- const { user, queryClient } = useSpeakableApi();
869
- const handleCreateNotifications = async (type, data) => {
870
- var _a, _b;
871
- const result = await createNotification({
872
- type,
873
- userId: user.auth.uid,
874
- profile: (_a = user == null ? void 0 : user.profile) != null ? _a : {},
875
- data
876
- });
877
- queryClient.invalidateQueries({
878
- queryKey: notificationQueryKeys.byId((_b = user == null ? void 0 : user.auth.uid) != null ? _b : "")
879
- });
880
- return result;
881
- };
882
- return {
883
- createNotification: handleCreateNotifications
884
- };
885
- };
886
-
887
- // src/hooks/useGoogleClassroom.ts
888
- var useGoogleClassroom = () => {
889
- const submitAssignmentToGoogleClassroom = async ({
890
- assignment,
891
- scores,
892
- googleUserId = null
893
- // optional to override the user's googleUserId
894
- }) => {
895
- var _a, _b, _c;
896
- try {
897
- const { googleClassroomUserId = null } = scores;
898
- const googleId = googleUserId || googleClassroomUserId;
899
- if (!googleId)
900
- return {
901
- error: true,
902
- message: "No Google Classroom ID found"
903
- };
904
- const { courseWorkId, maxPoints, owners, courseId } = assignment;
905
- const draftGrade = (scores == null ? void 0 : scores.score) ? (scores == null ? void 0 : scores.score) / 100 * maxPoints : 0;
906
- const result = await ((_c = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "submitAssignmentToGoogleClassroomV2")) == null ? void 0 : _c({
907
- teacherId: owners[0],
908
- courseId,
909
- courseWorkId,
910
- userId: googleId,
911
- draftGrade
912
- }));
913
- return result;
914
- } catch (error) {
915
- return { error: true, message: error.message };
916
- }
917
- };
918
- return {
919
- submitAssignmentToGoogleClassroom
920
- };
921
- };
922
-
923
- // src/lib/firebase/firebase-analytics/grading-standard.ts
924
- var logGradingStandardLog = (data) => {
925
- var _a, _b, _c;
926
- if (data.courseId && data.type && data.level) {
927
- (_c = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "handleCouresAnalyticsEvent")) == null ? void 0 : _c({
928
- eventType: data.type || "custom",
929
- level: data.level,
930
- courseId: data.courseId
931
- });
932
- }
933
- api.logEvent("logGradingStandard", data);
934
- };
935
-
936
548
  // src/constants/analytics.constants.ts
937
549
  var ANALYTICS_EVENT_TYPES = {
938
550
  VOICE_SUCCESS: "voice_success",
@@ -972,20 +584,6 @@ var ANALYTICS_EVENT_TYPES = {
972
584
  };
973
585
 
974
586
  // src/lib/firebase/firebase-analytics/assignment.ts
975
- var logOpenAssignment = (data = {}) => {
976
- api.logEvent("open_assignment", data);
977
- };
978
- var logOpenActivityPreview = (data = {}) => {
979
- api.logEvent("open_activity_preview", data);
980
- };
981
- var logSubmitAssignment = (data = {}) => {
982
- var _a, _b, _c;
983
- (_c = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "handleCouresAnalyticsEvent")) == null ? void 0 : _c({
984
- eventType: ANALYTICS_EVENT_TYPES.SUBMISSION,
985
- ...data
986
- });
987
- api.logEvent(ANALYTICS_EVENT_TYPES.SUBMISSION, data);
988
- };
989
587
  var logStartAssignment = (data = {}) => {
990
588
  var _a, _b, _c;
991
589
  if (data.courseId) {
@@ -1228,72 +826,6 @@ var updateCardScore = withErrorHandler(_updateCardScore, "updateCardScore");
1228
826
 
1229
827
  // src/domains/assignment/services/clear-score.service.ts
1230
828
  var import_dayjs3 = __toESM(require("dayjs"));
1231
- async function clearScore(params) {
1232
- var _a, _b, _c, _d, _e;
1233
- const update = {
1234
- [`cards.${params.cardId}`]: {
1235
- attempts: ((_a = params.cardScores.attempts) != null ? _a : 1) + 1,
1236
- correct: (_b = params.cardScores.correct) != null ? _b : 0,
1237
- // save old score history
1238
- history: [
1239
- {
1240
- ...params.cardScores,
1241
- attempts: (_c = params.cardScores.attempts) != null ? _c : 1,
1242
- correct: (_d = params.cardScores.correct) != null ? _d : 0,
1243
- retryTime: (0, import_dayjs3.default)().format("YYYY-MM-DD HH:mm:ss"),
1244
- history: null
1245
- },
1246
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
1247
- ...(_e = params.cardScores.history) != null ? _e : []
1248
- ]
1249
- }
1250
- };
1251
- const path = params.isAssignment ? refsAssignmentFiresotre.assignmentScores({
1252
- id: params.activityId,
1253
- userId: params.userId
1254
- }) : refsScoresPractice.practiceScores({
1255
- setId: params.activityId,
1256
- userId: params.userId
1257
- });
1258
- await api.updateDoc(path, update);
1259
- return {
1260
- update,
1261
- activityId: params.activityId
1262
- };
1263
- }
1264
- async function clearScoreV2(params) {
1265
- var _a, _b, _c, _d, _e;
1266
- const update = {
1267
- [`cards.${params.cardId}`]: {
1268
- ...params.cardScores,
1269
- attempts: ((_a = params.cardScores.attempts) != null ? _a : 1) + 1,
1270
- correct: (_b = params.cardScores.correct) != null ? _b : 0,
1271
- history: [
1272
- {
1273
- ...params.cardScores,
1274
- attempts: (_c = params.cardScores.attempts) != null ? _c : 1,
1275
- correct: (_d = params.cardScores.correct) != null ? _d : 0,
1276
- retryTime: (0, import_dayjs3.default)().format("YYYY-MM-DD HH:mm:ss"),
1277
- history: null
1278
- },
1279
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
1280
- ...(_e = params.cardScores.history) != null ? _e : []
1281
- ]
1282
- }
1283
- };
1284
- const path = params.isAssignment ? refsAssignmentFiresotre.assignmentScores({
1285
- id: params.activityId,
1286
- userId: params.userId
1287
- }) : refsScoresPractice.practiceScores({
1288
- setId: params.activityId,
1289
- userId: params.userId
1290
- });
1291
- await api.updateDoc(path, update);
1292
- return {
1293
- update,
1294
- activityId: params.activityId
1295
- };
1296
- }
1297
829
 
1298
830
  // src/domains/assignment/services/submit-assignment-score.service.ts
1299
831
  var import_dayjs4 = __toESM(require("dayjs"));
@@ -1359,465 +891,15 @@ async function handleCourseAssignment(assignment, userId) {
1359
891
  userId
1360
892
  }));
1361
893
  }
1362
- async function submitPracticeScore({
1363
- setId,
1364
- userId,
1365
- scores
1366
- }) {
1367
- const { serverTimestamp: serverTimestamp2 } = api.accessHelpers();
1368
- const date = (0, import_dayjs4.default)().format("YYYY-MM-DD-HH-mm");
1369
- const ref = refsScoresPractice.practiceScoreHistoryRefDoc({ setId, userId, date });
1370
- const fieldsUpdated = {
1371
- ...scores,
1372
- submitted: true,
1373
- progress: 100,
1374
- submissionDate: serverTimestamp2(),
1375
- status: "SUBMITTED"
1376
- };
1377
- await api.setDoc(ref, { ...fieldsUpdated });
1378
- const refScores = refsScoresPractice.practiceScores({ userId, setId });
1379
- await api.deleteDoc(refScores);
1380
- return { success: true, fieldsUpdated };
1381
- }
1382
894
 
1383
895
  // src/domains/assignment/hooks/score-hooks.ts
1384
- var scoreQueryKeys = {
1385
- all: ["scores"],
1386
- byId: (id) => [...scoreQueryKeys.all, id],
1387
- list: () => [...scoreQueryKeys.all, "list"]
1388
- };
1389
- function useScore({
1390
- isAssignment,
1391
- activityId,
1392
- userId = "",
1393
- courseId,
1394
- enabled = true,
1395
- googleClassroomUserId
1396
- }) {
1397
- return (0, import_react_query2.useQuery)({
1398
- queryFn: () => getScore({
1399
- userId,
1400
- courseId,
1401
- activityId,
1402
- googleClassroomUserId,
1403
- isAssignment
1404
- }),
1405
- queryKey: scoreQueryKeys.byId(activityId),
1406
- enabled
1407
- });
1408
- }
1409
896
  var debounceUpdateScore = debounce(updateScore, 500);
1410
- function useUpdateScore() {
1411
- const { queryClient } = useSpeakableApi();
1412
- const mutation = (0, import_react_query2.useMutation)({
1413
- mutationFn: debounceUpdateScore,
1414
- onMutate: (variables) => {
1415
- return handleOptimisticUpdate({
1416
- queryClient,
1417
- queryKey: scoreQueryKeys.byId(variables.activityId),
1418
- newData: variables.data
1419
- });
1420
- },
1421
- onError: (_, variables, context) => {
1422
- if (context == null ? void 0 : context.previousData)
1423
- queryClient.setQueryData(scoreQueryKeys.byId(variables.activityId), context.previousData);
1424
- },
1425
- onSettled: (_, err, variables) => {
1426
- queryClient.invalidateQueries({
1427
- queryKey: scoreQueryKeys.byId(variables.activityId)
1428
- });
1429
- }
1430
- });
1431
- return {
1432
- mutationUpdateScore: mutation
1433
- };
1434
- }
1435
- function useUpdateCardScore({
1436
- isAssignment,
1437
- activityId,
1438
- userId,
1439
- cardIds,
1440
- weights
1441
- }) {
1442
- const { queryClient } = useSpeakableApi();
1443
- const queryKey = scoreQueryKeys.byId(activityId);
1444
- const mutation = (0, import_react_query2.useMutation)({
1445
- mutationFn: async ({ cardId, cardScore }) => {
1446
- const previousScores = queryClient.getQueryData(queryKey);
1447
- const { progress, score, newScoreUpdated, updatedCardScore } = getScoreUpdated({
1448
- previousScores: previousScores != null ? previousScores : {},
1449
- cardId,
1450
- cardScore,
1451
- cardIds,
1452
- weights
1453
- });
1454
- console.log("updates", {
1455
- cardScore: updatedCardScore,
1456
- progress,
1457
- score
1458
- });
1459
- await updateCardScore({
1460
- userId,
1461
- cardId,
1462
- isAssignment,
1463
- activityId,
1464
- updates: {
1465
- cardScore: updatedCardScore,
1466
- progress,
1467
- score
1468
- }
1469
- });
1470
- return { cardId, scoresUpdated: newScoreUpdated };
1471
- },
1472
- onMutate: ({ cardId, cardScore }) => {
1473
- const previousData = queryClient.getQueryData(queryKey);
1474
- queryClient.setQueryData(queryKey, (previousScore) => {
1475
- const updates = handleOptimisticScore({
1476
- score: previousScore,
1477
- cardId,
1478
- cardScore,
1479
- cardIds,
1480
- weights
1481
- });
1482
- return {
1483
- ...previousScore,
1484
- ...updates
1485
- };
1486
- });
1487
- return { previousData };
1488
- },
1489
- onError: (error, variables, context) => {
1490
- console.log("Error updating card score:", error.message);
1491
- if (context == null ? void 0 : context.previousData) {
1492
- queryClient.setQueryData(queryKey, context.previousData);
1493
- }
1494
- },
1495
- onSettled: () => {
1496
- queryClient.invalidateQueries({
1497
- queryKey
1498
- });
1499
- }
1500
- });
1501
- return {
1502
- mutationUpdateCardScore: mutation
1503
- };
1504
- }
1505
- var getScoreUpdated = ({
1506
- cardId,
1507
- cardScore,
1508
- previousScores,
1509
- cardIds,
1510
- weights
1511
- }) => {
1512
- var _a, _b;
1513
- const previousCard = (_a = previousScores.cards) == null ? void 0 : _a[cardId];
1514
- const newCardScore = {
1515
- ...previousCard != null ? previousCard : {},
1516
- ...cardScore
1517
- };
1518
- const newScores = {
1519
- ...previousScores,
1520
- cards: {
1521
- ...(_b = previousScores.cards) != null ? _b : {},
1522
- [cardId]: newCardScore
1523
- }
1524
- };
1525
- console.log("newScores", newScores, cardIds, weights);
1526
- const { score, progress } = calculateScoreAndProgress_default(newScores, cardIds, weights);
1527
- console.log("score and progress", score, progress);
1528
- return {
1529
- newScoreUpdated: newScores,
1530
- updatedCardScore: cardScore,
1531
- score,
1532
- progress
1533
- };
1534
- };
1535
- var handleOptimisticScore = ({
1536
- score,
1537
- cardId,
1538
- cardScore,
1539
- cardIds,
1540
- weights
1541
- }) => {
1542
- var _a;
1543
- let cards = { ...(_a = score == null ? void 0 : score.cards) != null ? _a : {} };
1544
- cards = {
1545
- ...cards,
1546
- [cardId]: {
1547
- ...cards[cardId],
1548
- ...cardScore
1549
- }
1550
- };
1551
- const { score: scoreValue, progress } = calculateScoreAndProgress_default(
1552
- // @ts-ignore
1553
- {
1554
- ...score != null ? score : {},
1555
- cards
1556
- },
1557
- cardIds,
1558
- weights
1559
- );
1560
- return { cards, score: scoreValue, progress };
1561
- };
1562
- function useClearScore() {
1563
- const { queryClient } = useSpeakableApi();
1564
- const mutation = (0, import_react_query2.useMutation)({
1565
- mutationFn: clearScore,
1566
- onError: (error) => {
1567
- console.log("Error clearing score:", error.message);
1568
- },
1569
- onSettled: (result) => {
1570
- var _a;
1571
- queryClient.invalidateQueries({
1572
- queryKey: scoreQueryKeys.byId((_a = result == null ? void 0 : result.activityId) != null ? _a : "")
1573
- });
1574
- }
1575
- });
1576
- return {
1577
- mutationClearScore: mutation
1578
- };
1579
- }
1580
- function useClearScoreV2() {
1581
- const { queryClient } = useSpeakableApi();
1582
- const mutation = (0, import_react_query2.useMutation)({
1583
- mutationFn: clearScoreV2,
1584
- onError: (error) => {
1585
- console.log("Error clearing score V2:", error.message);
1586
- },
1587
- onSettled: (result) => {
1588
- var _a;
1589
- queryClient.invalidateQueries({
1590
- queryKey: scoreQueryKeys.byId((_a = result == null ? void 0 : result.activityId) != null ? _a : "")
1591
- });
1592
- }
1593
- });
1594
- return {
1595
- mutationClearScore: mutation
1596
- };
1597
- }
1598
- function useSubmitAssignmentScore({
1599
- onAssignmentSubmitted,
1600
- studentName
1601
- }) {
1602
- const { queryClient } = useSpeakableApi();
1603
- const { hasGoogleClassroomGradePassback } = usePermissions_default();
1604
- const { submitAssignmentToGoogleClassroom } = useGoogleClassroom();
1605
- const { createNotification: createNotification2 } = useCreateNotification();
1606
- const mutation = (0, import_react_query2.useMutation)({
1607
- mutationFn: async ({
1608
- assignment,
1609
- userId,
1610
- cardIds,
1611
- weights,
1612
- scores,
1613
- status
1614
- }) => {
1615
- try {
1616
- const scoreUpdated = await submitAssignmentScore({
1617
- assignment,
1618
- userId,
1619
- cardIds,
1620
- weights,
1621
- status,
1622
- studentName
1623
- });
1624
- if (assignment.courseWorkId != null && !assignment.isAssessment && hasGoogleClassroomGradePassback) {
1625
- await submitAssignmentToGoogleClassroom({
1626
- assignment,
1627
- scores
1628
- });
1629
- }
1630
- if (assignment.isAssessment) {
1631
- createNotification2(SpeakableNotificationTypes.ASSESSMENT_SUBMITTED, assignment);
1632
- }
1633
- if (assignment == null ? void 0 : assignment.id) {
1634
- logSubmitAssignment({
1635
- courseId: assignment == null ? void 0 : assignment.courseId
1636
- });
1637
- }
1638
- onAssignmentSubmitted(assignment.id);
1639
- queryClient.setQueryData(scoreQueryKeys.byId(assignment.id), {
1640
- ...scores,
1641
- ...scoreUpdated.fieldsUpdated
1642
- });
1643
- return {
1644
- success: true,
1645
- message: "Score submitted successfully"
1646
- };
1647
- } catch (error) {
1648
- return {
1649
- success: false,
1650
- error
1651
- };
1652
- }
1653
- }
1654
- });
1655
- return {
1656
- submitAssignmentScore: mutation.mutateAsync,
1657
- isLoading: mutation.isPending
1658
- };
1659
- }
1660
- function useSubmitPracticeScore() {
1661
- const { queryClient } = useSpeakableApi();
1662
- const mutation = (0, import_react_query2.useMutation)({
1663
- mutationFn: async ({
1664
- setId,
1665
- userId,
1666
- scores
1667
- }) => {
1668
- try {
1669
- await submitPracticeScore({
1670
- setId,
1671
- userId,
1672
- scores
1673
- });
1674
- queryClient.invalidateQueries({
1675
- queryKey: scoreQueryKeys.byId(setId)
1676
- });
1677
- return {
1678
- success: true,
1679
- message: "Score submitted successfully"
1680
- };
1681
- } catch (error) {
1682
- return {
1683
- success: false,
1684
- error
1685
- };
1686
- }
1687
- }
1688
- });
1689
- return {
1690
- submitPracticeScore: mutation.mutateAsync,
1691
- isLoading: mutation.isPending
1692
- };
1693
- }
1694
897
 
1695
898
  // src/domains/cards/card.hooks.ts
1696
899
  var import_react_query3 = require("@tanstack/react-query");
1697
900
  var import_react2 = require("react");
1698
901
 
1699
- // src/domains/cards/card.model.ts
1700
- var ActivityPageType = /* @__PURE__ */ ((ActivityPageType2) => {
1701
- ActivityPageType2["READ_REPEAT"] = "READ_REPEAT";
1702
- ActivityPageType2["READ_RESPOND"] = "READ_RESPOND";
1703
- ActivityPageType2["FREE_RESPONSE"] = "FREE_RESPONSE";
1704
- ActivityPageType2["REPEAT"] = "REPEAT";
1705
- ActivityPageType2["RESPOND"] = "RESPOND";
1706
- ActivityPageType2["RESPOND_WRITE"] = "RESPOND_WRITE";
1707
- ActivityPageType2["MULTIPLE_CHOICE"] = "MULTIPLE_CHOICE";
1708
- ActivityPageType2["MEDIA_PAGE"] = "MEDIA_PAGE";
1709
- ActivityPageType2["SHORT_ANSWER"] = "SHORT_ANSWER";
1710
- return ActivityPageType2;
1711
- })(ActivityPageType || {});
1712
- var RESPOND_PAGE_ACTIVITY_TYPES = [
1713
- "READ_RESPOND" /* READ_RESPOND */,
1714
- "RESPOND" /* RESPOND */,
1715
- "RESPOND_WRITE" /* RESPOND_WRITE */,
1716
- "FREE_RESPONSE" /* FREE_RESPONSE */
1717
- ];
1718
- var MULTIPLE_CHOICE_PAGE_ACTIVITY_TYPES = ["MULTIPLE_CHOICE" /* MULTIPLE_CHOICE */];
1719
- var REPEAT_PAGE_ACTIVITY_TYPES = ["READ_REPEAT" /* READ_REPEAT */, "REPEAT" /* REPEAT */];
1720
- var RESPOND_WRITE_PAGE_ACTIVITY_TYPES = [
1721
- "RESPOND_WRITE" /* RESPOND_WRITE */,
1722
- "FREE_RESPONSE" /* FREE_RESPONSE */
1723
- ];
1724
- var RESPOND_AUDIO_PAGE_ACTIVITY_TYPES = [
1725
- "RESPOND" /* RESPOND */,
1726
- "READ_RESPOND" /* READ_RESPOND */
1727
- ];
1728
-
1729
902
  // src/domains/cards/card.constants.ts
1730
- var FeedbackTypesCard = /* @__PURE__ */ ((FeedbackTypesCard2) => {
1731
- FeedbackTypesCard2["SuggestedResponse"] = "suggested_response";
1732
- FeedbackTypesCard2["Wida"] = "wida";
1733
- FeedbackTypesCard2["GrammarInsights"] = "grammar_insights";
1734
- FeedbackTypesCard2["Actfl"] = "actfl";
1735
- FeedbackTypesCard2["ProficiencyLevel"] = "proficiency_level";
1736
- return FeedbackTypesCard2;
1737
- })(FeedbackTypesCard || {});
1738
- var LeniencyCard = /* @__PURE__ */ ((LeniencyCard2) => {
1739
- LeniencyCard2["CONFIDENCE"] = "confidence";
1740
- LeniencyCard2["EASY"] = "easy";
1741
- LeniencyCard2["NORMAL"] = "normal";
1742
- LeniencyCard2["HARD"] = "hard";
1743
- return LeniencyCard2;
1744
- })(LeniencyCard || {});
1745
- var LENIENCY_OPTIONS = [
1746
- {
1747
- label: "Build Confidence - most lenient",
1748
- value: "confidence" /* CONFIDENCE */
1749
- },
1750
- {
1751
- label: "Very Lenient",
1752
- value: "easy" /* EASY */
1753
- },
1754
- {
1755
- label: "Normal",
1756
- value: "normal" /* NORMAL */
1757
- },
1758
- {
1759
- label: "No leniency - most strict",
1760
- value: "hard" /* HARD */
1761
- }
1762
- ];
1763
- var STUDENT_LEVELS_OPTIONS = [
1764
- {
1765
- label: "Beginner",
1766
- description: "Beginner Level: Just starting out. Can say a few basic words and phrases.",
1767
- value: "beginner"
1768
- },
1769
- {
1770
- label: "Elementary",
1771
- description: "Elementary Level: Can understand simple sentences and have very basic conversations.",
1772
- value: "elementary"
1773
- },
1774
- {
1775
- label: "Intermediate",
1776
- description: "Intermediate Level: Can talk about everyday topics and handle common situations.",
1777
- value: "intermediate"
1778
- },
1779
- {
1780
- label: "Advanced",
1781
- description: "Advanced Level: Can speak and understand with ease, and explain ideas clearly.",
1782
- value: "advanced"
1783
- },
1784
- {
1785
- label: "Fluent",
1786
- description: "Fluent Level: Speaks naturally and easily. Can use the language in work or school settings.",
1787
- value: "fluent"
1788
- },
1789
- {
1790
- label: "Native-like",
1791
- description: "Native-like Level: Understands and speaks like a native. Can discuss complex ideas accurately.",
1792
- value: "nativeLike"
1793
- }
1794
- ];
1795
- var BASE_RESPOND_FIELD_VALUES = {
1796
- title: "",
1797
- allowRetries: true,
1798
- respondTime: 180,
1799
- maxCharacters: 1e3
1800
- };
1801
- var BASE_REPEAT_FIELD_VALUES = {
1802
- repeat: 1
1803
- };
1804
- var BASE_MULTIPLE_CHOICE_FIELD_VALUES = {
1805
- MCQType: "single",
1806
- answer: ["A"],
1807
- choices: [
1808
- { option: "A", value: "Option A" },
1809
- { option: "B", value: "Option B" },
1810
- { option: "C", value: "Option C" }
1811
- ]
1812
- };
1813
- var VerificationCardStatus = /* @__PURE__ */ ((VerificationCardStatus2) => {
1814
- VerificationCardStatus2["VERIFIED"] = "VERIFIED";
1815
- VerificationCardStatus2["WARNING"] = "WARNING";
1816
- VerificationCardStatus2["NOT_RECOMMENDED"] = "NOT_RECOMMENDED";
1817
- VerificationCardStatus2["NOT_WORKING"] = "NOT_WORKING";
1818
- VerificationCardStatus2["NOT_CHECKED"] = "NOT_CHECKED";
1819
- return VerificationCardStatus2;
1820
- })(VerificationCardStatus || {});
1821
903
  var CARDS_COLLECTION = "flashcards";
1822
904
  var refsCardsFiresotre = {
1823
905
  allCards: CARDS_COLLECTION,
@@ -1864,13 +946,6 @@ var getWordHash = (word, language) => {
1864
946
  console.log("wordHash core library", wordHash);
1865
947
  return wordHash;
1866
948
  };
1867
- function getPhraseLength(phrase, input) {
1868
- if (Array.isArray(phrase) && phrase.includes(input)) {
1869
- return phrase[phrase.indexOf(input)].split(" ").length;
1870
- } else {
1871
- return phrase ? phrase.split(" ").length : 0;
1872
- }
1873
- }
1874
949
 
1875
950
  // src/domains/cards/services/get-card-verification-status.service.ts
1876
951
  var charactarLanguages = ["zh", "ja", "ko"];
@@ -1941,81 +1016,6 @@ async function _createCards({ cards }) {
1941
1016
  }
1942
1017
  var createCards = withErrorHandler(_createCards, "createCards");
1943
1018
 
1944
- // src/domains/cards/card.hooks.ts
1945
- var cardsQueryKeys = {
1946
- all: ["cards"],
1947
- one: (params) => [...cardsQueryKeys.all, params.cardId]
1948
- };
1949
- function useCards({
1950
- cardIds,
1951
- enabled = true,
1952
- asObject
1953
- }) {
1954
- const queries = (0, import_react_query3.useQueries)({
1955
- queries: cardIds.map((cardId) => ({
1956
- enabled: enabled && cardIds.length > 0,
1957
- queryKey: cardsQueryKeys.one({
1958
- cardId
1959
- }),
1960
- queryFn: () => getCard({ cardId })
1961
- }))
1962
- });
1963
- const cards = queries.map((query2) => query2.data).filter(Boolean);
1964
- const cardsObject = (0, import_react2.useMemo)(() => {
1965
- if (!asObject) return null;
1966
- return cards.reduce((acc, card) => {
1967
- acc[card.id] = card;
1968
- return acc;
1969
- }, {});
1970
- }, [asObject, cards]);
1971
- return {
1972
- cards,
1973
- cardsObject,
1974
- cardsQueries: queries
1975
- };
1976
- }
1977
- function useCreateCard() {
1978
- const { queryClient } = useSpeakableApi();
1979
- const mutationCreateCard = (0, import_react_query3.useMutation)({
1980
- mutationFn: createCard,
1981
- onSuccess: (cardCreated) => {
1982
- queryClient.invalidateQueries({ queryKey: cardsQueryKeys.one({ cardId: cardCreated.id }) });
1983
- }
1984
- });
1985
- return {
1986
- mutationCreateCard
1987
- };
1988
- }
1989
- function useCreateCards() {
1990
- const mutationCreateCards = (0, import_react_query3.useMutation)({
1991
- mutationFn: createCards
1992
- });
1993
- return {
1994
- mutationCreateCards
1995
- };
1996
- }
1997
- function getCardFromCache({
1998
- cardId,
1999
- queryClient
2000
- }) {
2001
- return queryClient.getQueryData(cardsQueryKeys.one({ cardId }));
2002
- }
2003
- function updateCardInCache({
2004
- cardId,
2005
- card,
2006
- queryClient
2007
- }) {
2008
- queryClient.setQueryData(cardsQueryKeys.one({ cardId }), card);
2009
- }
2010
- function useGetCard({ cardId, enabled = true }) {
2011
- const query2 = (0, import_react_query3.useQuery)({
2012
- queryKey: cardsQueryKeys.one({ cardId }),
2013
- queryFn: () => getCard({ cardId }),
2014
- enabled: enabled && !!cardId
2015
- });
2016
- return query2;
2017
- }
2018
-
2019
1019
  // src/domains/cards/card.repo.ts
2020
1020
  var createCardRepo = () => {
2021
1021
  return {
@@ -2025,177 +1025,6 @@ var createCardRepo = () => {
2025
1025
  };
2026
1026
  };
2027
1027
 
2028
- // src/domains/cards/utils/check-page-type.ts
2029
- function checkIsRepeatPage(cardType) {
2030
- if (cardType === void 0) return false;
2031
- return REPEAT_PAGE_ACTIVITY_TYPES.includes(cardType);
2032
- }
2033
- function checkIsMCPage(cardType) {
2034
- if (cardType === void 0) return false;
2035
- return MULTIPLE_CHOICE_PAGE_ACTIVITY_TYPES.includes(cardType);
2036
- }
2037
- function checkIsRespondPage(cardType) {
2038
- if (cardType === void 0) return false;
2039
- return RESPOND_PAGE_ACTIVITY_TYPES.includes(cardType);
2040
- }
2041
- function checkIsRespondWrittenPage(cardType) {
2042
- if (cardType === void 0) return false;
2043
- return RESPOND_WRITE_PAGE_ACTIVITY_TYPES.includes(cardType);
2044
- }
2045
- function checkIsRespondAudioPage(cardType) {
2046
- if (cardType === void 0) return false;
2047
- return RESPOND_AUDIO_PAGE_ACTIVITY_TYPES.includes(cardType);
2048
- }
2049
- var checkIsMediaPage = (cardType) => {
2050
- if (cardType === void 0) return false;
2051
- return cardType === "MEDIA_PAGE" /* MEDIA_PAGE */;
2052
- };
2053
- var checkIsShortAnswerPage = (cardType) => {
2054
- if (cardType === void 0) return false;
2055
- return cardType === "SHORT_ANSWER" /* SHORT_ANSWER */;
2056
- };
2057
- var checkTypePageActivity = (cardType) => {
2058
- const isRespondAudio = checkIsRespondAudioPage(cardType);
2059
- const isRespondWritten = checkIsRespondWrittenPage(cardType);
2060
- const isRespond = checkIsRespondPage(cardType);
2061
- const isMC = checkIsMCPage(cardType);
2062
- const isRepeat = checkIsRepeatPage(cardType);
2063
- const isMediaPage = checkIsMediaPage(cardType);
2064
- const isShortAnswer = checkIsShortAnswerPage(cardType);
2065
- const isNoOneOfThem = !isRespond && !isMC && !isRepeat && !isMediaPage && !isShortAnswer;
2066
- if (isNoOneOfThem) {
2067
- return {
2068
- isRespondAudio: false,
2069
- isRespondWritten: false,
2070
- isRespond: false,
2071
- isMC: false,
2072
- isRepeat: true,
2073
- isMediaPage: false,
2074
- isShortAnswer: false,
2075
- hasSomeType: false
2076
- };
2077
- }
2078
- return {
2079
- isRespondAudio,
2080
- isRespondWritten,
2081
- isRespond,
2082
- isMC,
2083
- isRepeat,
2084
- isMediaPage,
2085
- isShortAnswer,
2086
- hasSomeType: true
2087
- };
2088
- };
2089
-
2090
- // src/domains/cards/utils/get-page-prompt.ts
2091
- function extractTextFromRichText(richText) {
2092
- if (!richText) return "";
2093
- return richText.replace(/<[^>]*>/g, "").replace(/&nbsp;/g, " ").replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'").trim();
2094
- }
2095
- function getPagePrompt(card) {
2096
- if (!card) return { has: false, text: "", rich_text: "", isTextEqualToRichText: false };
2097
- const { isMC, isRepeat, isRespond, isShortAnswer } = checkTypePageActivity(card == null ? void 0 : card.type);
2098
- const hidePrompt = (card == null ? void 0 : card.hidePrompt) === true;
2099
- const createReturnObject = (text, richText) => {
2100
- const plainText = text || "";
2101
- const richTextPlain = extractTextFromRichText(richText);
2102
- return {
2103
- has: true,
2104
- text: plainText,
2105
- rich_text: richText || "",
2106
- isTextEqualToRichText: plainText.trim() === richTextPlain.trim()
2107
- };
2108
- };
2109
- if (isRepeat) {
2110
- return createReturnObject(card == null ? void 0 : card.target_text, card == null ? void 0 : card.rich_text);
2111
- }
2112
- if (isRespond && !hidePrompt) {
2113
- return createReturnObject(card == null ? void 0 : card.prompt, card == null ? void 0 : card.rich_text);
2114
- }
2115
- if (isMC) {
2116
- return createReturnObject(card == null ? void 0 : card.question, card == null ? void 0 : card.rich_text);
2117
- }
2118
- if (isShortAnswer && !hidePrompt) {
2119
- return createReturnObject(card == null ? void 0 : card.prompt, card == null ? void 0 : card.rich_text);
2120
- }
2121
- return {
2122
- has: false,
2123
- text: "",
2124
- rich_text: "",
2125
- isTextEqualToRichText: false
2126
- };
2127
- }
2128
-
2129
- // src/domains/cards/utils/get-completed-pages.ts
2130
- var getTotalCompletedCards = (pageScores) => {
2131
- return Object.values(pageScores != null ? pageScores : {}).reduce((acc, cardScore) => {
2132
- var _a, _b;
2133
- if (((_b = (_a = cardScore.completed) != null ? _a : cardScore.score) != null ? _b : cardScore.score === 0) && !cardScore.media_area_opened) {
2134
- acc++;
2135
- }
2136
- return acc;
2137
- }, 0);
2138
- };
2139
-
2140
- // src/domains/cards/utils/get-label-page.ts
2141
- var labels = {
2142
- repeat: {
2143
- short: "Repeat",
2144
- long: "Listen & Repeat"
2145
- },
2146
- mc: {
2147
- short: "Multiple Choice",
2148
- long: "Multiple Choice"
2149
- },
2150
- mediaPage: {
2151
- short: "Media Page",
2152
- long: "Media Page"
2153
- },
2154
- shortAnswer: {
2155
- short: "Short Answer",
2156
- long: "Short Answer"
2157
- },
2158
- respondWritten: {
2159
- short: "Open Response",
2160
- long: "Written Open Response"
2161
- },
2162
- respondAudio: {
2163
- short: "Open Response",
2164
- long: "Spoken Open Response"
2165
- }
2166
- };
2167
- var getLabelPage = (pageType) => {
2168
- if (!pageType) {
2169
- return {
2170
- short: "",
2171
- long: ""
2172
- };
2173
- }
2174
- const { isRepeat, isMC, isMediaPage, isShortAnswer, isRespondWritten, isRespondAudio } = checkTypePageActivity(pageType);
2175
- if (isRepeat) {
2176
- return labels.repeat;
2177
- }
2178
- if (isMC) {
2179
- return labels.mc;
2180
- }
2181
- if (isMediaPage) {
2182
- return labels.mediaPage;
2183
- }
2184
- if (isShortAnswer) {
2185
- return labels.shortAnswer;
2186
- }
2187
- if (isRespondWritten) {
2188
- return labels.respondWritten;
2189
- }
2190
- if (isRespondAudio) {
2191
- return labels.respondAudio;
2192
- }
2193
- return {
2194
- short: "",
2195
- long: ""
2196
- };
2197
- };
2198
-
2199
1028
  // src/domains/sets/set.hooks.ts
2200
1029
  var import_react_query4 = require("@tanstack/react-query");
2201
1030
 
@@ -2213,1191 +1042,6 @@ async function _getSet({ setId }) {
2213
1042
  }
2214
1043
  var getSet = withErrorHandler(_getSet, "getSet");
2215
1044
 
2216
- // src/domains/sets/set.hooks.ts
2217
- var setsQueryKeys = {
2218
- all: ["sets"],
2219
- one: (params) => [...setsQueryKeys.all, params.setId]
2220
- };
2221
- var useSet = ({ setId, enabled }) => {
2222
- return (0, import_react_query4.useQuery)({
2223
- queryKey: setsQueryKeys.one({ setId }),
2224
- queryFn: () => getSet({ setId }),
2225
- enabled: setId !== void 0 && setId !== "" && enabled
2226
- });
2227
- };
2228
- function getSetFromCache({
2229
- setId,
2230
- queryClient
2231
- }) {
2232
- if (!setId) return null;
2233
- return queryClient.getQueryData(setsQueryKeys.one({ setId }));
2234
- }
2235
- function updateSetInCache({
2236
- set,
2237
- queryClient
2238
- }) {
2239
- const { id, ...setData } = set;
2240
- queryClient.setQueryData(setsQueryKeys.one({ setId: id }), setData);
2241
- }
2242
-
2243
- // src/domains/sets/set.repo.ts
2244
- var createSetRepo = () => {
2245
- return {
2246
- getSet
2247
- };
2248
- };
2249
-
2250
- // src/constants/all-langs.json
2251
- var all_langs_default = {
2252
- af: "Afrikaans",
2253
- sq: "Albanian",
2254
- am: "Amharic",
2255
- ar: "Arabic",
2256
- hy: "Armenian",
2257
- az: "Azerbaijani",
2258
- eu: "Basque",
2259
- be: "Belarusian",
2260
- bn: "Bengali",
2261
- bs: "Bosnian",
2262
- bg: "Bulgarian",
2263
- ca: "Catalan",
2264
- ceb: "Cebuano",
2265
- zh: "Chinese",
2266
- co: "Corsican",
2267
- hr: "Croatian",
2268
- cs: "Czech",
2269
- da: "Danish",
2270
- nl: "Dutch",
2271
- en: "English",
2272
- eo: "Esperanto",
2273
- et: "Estonian",
2274
- fi: "Finnish",
2275
- fr: "French",
2276
- fy: "Frisian",
2277
- gl: "Galician",
2278
- ka: "Georgian",
2279
- de: "German",
2280
- el: "Greek",
2281
- gu: "Gujarati",
2282
- ht: "Haitian Creole",
2283
- ha: "Hausa",
2284
- haw: "Hawaiian",
2285
- he: "Hebrew",
2286
- hi: "Hindi",
2287
- hmn: "Hmong",
2288
- hu: "Hungarian",
2289
- is: "Icelandic",
2290
- ig: "Igbo",
2291
- id: "Indonesian",
2292
- ga: "Irish",
2293
- it: "Italian",
2294
- ja: "Japanese",
2295
- jv: "Javanese",
2296
- kn: "Kannada",
2297
- kk: "Kazakh",
2298
- km: "Khmer",
2299
- ko: "Korean",
2300
- ku: "Kurdish",
2301
- ky: "Kyrgyz",
2302
- lo: "Lao",
2303
- la: "Latin",
2304
- lv: "Latvian",
2305
- lt: "Lithuanian",
2306
- lb: "Luxembourgish",
2307
- mk: "Macedonian",
2308
- mg: "Malagasy",
2309
- ms: "Malay",
2310
- ml: "Malayalam",
2311
- mt: "Maltese",
2312
- mi: "Maori",
2313
- mr: "Marathi",
2314
- mn: "Mongolian",
2315
- my: "Myanmar (Burmese)",
2316
- ne: "Nepali",
2317
- no: "Norwegian",
2318
- ny: "Nyanja (Chichewa)",
2319
- ps: "Pashto",
2320
- fa: "Persian",
2321
- pl: "Polish",
2322
- pt: "Portuguese",
2323
- pa: "Punjabi",
2324
- ro: "Romanian",
2325
- ru: "Russian",
2326
- sm: "Samoan",
2327
- gd: "Scots Gaelic",
2328
- sr: "Serbian",
2329
- st: "Sesotho",
2330
- sn: "Shona",
2331
- sd: "Sindhi",
2332
- si: "Sinhala (Sinhalese)",
2333
- sk: "Slovak",
2334
- sl: "Slovenian",
2335
- so: "Somali",
2336
- es: "Spanish",
2337
- su: "Sundanese",
2338
- sw: "Swahili",
2339
- sv: "Swedish",
2340
- tl: "Tagalog (Filipino)",
2341
- tg: "Tajik",
2342
- ta: "Tamil",
2343
- te: "Telugu",
2344
- th: "Thai",
2345
- tr: "Turkish",
2346
- uk: "Ukrainian",
2347
- ur: "Urdu",
2348
- uz: "Uzbek",
2349
- vi: "Vietnamese",
2350
- cy: "Welsh",
2351
- xh: "Xhosa",
2352
- yi: "Yiddish",
2353
- yo: "Yoruba",
2354
- zu: "Zulu"
2355
- };
2356
-
2357
- // src/utils/ai/get-respond-card-tool.ts
2358
- var getRespondCardTool = ({
2359
- language,
2360
- standard = "actfl"
2361
- }) => {
2362
- const lang = all_langs_default[language] || "English";
2363
- const tool = {
2364
- tool_choice: {
2365
- type: "function",
2366
- function: { name: "get_feedback" }
2367
- },
2368
- tools: [
2369
- {
2370
- type: "function",
2371
- function: {
2372
- name: "get_feedback",
2373
- description: "Get feedback on a student's response",
2374
- parameters: {
2375
- type: "object",
2376
- required: [
2377
- "success",
2378
- "score",
2379
- "score_justification",
2380
- "errors",
2381
- "improvedResponse",
2382
- "compliments"
2383
- ],
2384
- properties: {
2385
- success: {
2386
- type: "boolean",
2387
- 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."
2388
- },
2389
- errors: {
2390
- type: "array",
2391
- items: {
2392
- type: "object",
2393
- required: ["error", "grammar_error_type", "correction", "justification"],
2394
- properties: {
2395
- error: {
2396
- type: "string",
2397
- description: "The grammatical error in the student's response."
2398
- },
2399
- correction: {
2400
- type: "string",
2401
- description: "The suggested correction to the error"
2402
- },
2403
- justification: {
2404
- type: "string",
2405
- description: `An explanation of the rationale behind the suggested correction. WRITE THIS IN ${lang}!`
2406
- },
2407
- grammar_error_type: {
2408
- type: "string",
2409
- enum: [
2410
- "subjVerbAgree",
2411
- "tenseErrors",
2412
- "articleMisuse",
2413
- "prepositionErrors",
2414
- "adjNounAgree",
2415
- "pronounErrors",
2416
- "wordOrder",
2417
- "verbConjugation",
2418
- "pluralization",
2419
- "negationErrors",
2420
- "modalVerbMisuse",
2421
- "relativeClause",
2422
- "auxiliaryVerb",
2423
- "complexSentenceAgreement",
2424
- "idiomaticExpression",
2425
- "registerInconsistency",
2426
- "voiceMisuse"
2427
- ],
2428
- 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"
2429
- }
2430
- }
2431
- },
2432
- 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."
2433
- },
2434
- compliments: {
2435
- type: "array",
2436
- items: {
2437
- type: "string"
2438
- },
2439
- description: `An array of strings, each representing something the student did well. Each string should be WRITTEN IN ${lang}!`
2440
- },
2441
- improvedResponse: {
2442
- type: "string",
2443
- description: "An improved response with proper grammar and more detail, if applicable."
2444
- },
2445
- score: {
2446
- type: "number",
2447
- description: "A score between 0 and 100, reflecting the overall quality of the response"
2448
- },
2449
- score_justification: {
2450
- type: "string",
2451
- description: "An explanation of the rationale behind the assigned score, considering both accuracy and fluency"
2452
- }
2453
- }
2454
- }
2455
- }
2456
- }
2457
- ]
2458
- };
2459
- if (standard === "wida") {
2460
- const wida_level = {
2461
- type: "number",
2462
- enum: [1, 2, 3, 4, 5, 6],
2463
- 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
2464
-
2465
- 1 - Entering
2466
- 2 - Emerging
2467
- 3 - Developing
2468
- 4 - Expanding
2469
- 5 - Bridging
2470
- 6 - Reaching
2471
-
2472
- 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.
2473
- `
2474
- };
2475
- const wida_justification = {
2476
- type: "string",
2477
- description: `An explanation of the rationale behind the assigned WIDA level of the response, considering both accuracy and fluency. WRITE THIS IN ENGLISH!`
2478
- };
2479
- tool.tools[0].function.parameters.required.push("wida_level");
2480
- tool.tools[0].function.parameters.required.push("wida_justification");
2481
- tool.tools[0].function.parameters.properties.wida_level = wida_level;
2482
- tool.tools[0].function.parameters.properties.wida_justification = wida_justification;
2483
- } else {
2484
- const actfl_level = {
2485
- type: "string",
2486
- enum: ["NL", "NM", "NH", "IL", "IM", "IH", "AL", "AM", "AH", "S", "D"],
2487
- 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"
2488
- };
2489
- const actfl_justification = {
2490
- type: "string",
2491
- description: "An explanation of the rationale behind the assigned ACTFL level, considering both accuracy and fluency"
2492
- };
2493
- tool.tools[0].function.parameters.required.push("actfl_level");
2494
- tool.tools[0].function.parameters.required.push("actfl_justification");
2495
- tool.tools[0].function.parameters.properties.actfl_level = actfl_level;
2496
- tool.tools[0].function.parameters.properties.actfl_justification = actfl_justification;
2497
- }
2498
- return tool;
2499
- };
2500
-
2501
- // src/hooks/useActivity.ts
2502
- var import_react3 = require("react");
2503
-
2504
- // src/services/add-grading-standard.ts
2505
- var addGradingStandardLog = async (gradingStandard, userId) => {
2506
- logGradingStandardLog(gradingStandard);
2507
- const path = `users/${userId}/grading_standard_logs`;
2508
- await api.addDoc(path, gradingStandard);
2509
- };
2510
-
2511
- // src/hooks/useActivityTracker.ts
2512
- var import_uuid2 = require("uuid");
2513
- function useActivityTracker({ userId }) {
2514
- const trackActivity = async ({
2515
- activityName,
2516
- activityType,
2517
- id = (0, import_uuid2.v4)(),
2518
- language = ""
2519
- }) => {
2520
- if (userId) {
2521
- const { doc: doc2, serverTimestamp: serverTimestamp2, setDoc: setDoc2 } = api.accessHelpers();
2522
- const activityRef = doc2(`users/${userId}/activity/${id}`);
2523
- const timestamp = serverTimestamp2();
2524
- await setDoc2(activityRef, {
2525
- name: activityName,
2526
- type: activityType,
2527
- lastSeen: timestamp,
2528
- id,
2529
- language
2530
- });
2531
- }
2532
- };
2533
- return {
2534
- trackActivity
2535
- };
2536
- }
2537
-
2538
- // src/hooks/useActivity.ts
2539
- function useActivity({
2540
- id,
2541
- isAssignment,
2542
- onAssignmentSubmitted,
2543
- ltiData
2544
- }) {
2545
- var _a, _b;
2546
- const { queryClient, user } = useSpeakableApi();
2547
- const userId = user.auth.uid;
2548
- const assignmentQuery = useAssignment({
2549
- assignmentId: id,
2550
- userId,
2551
- enabled: isAssignment
2552
- });
2553
- const activeAssignment = assignmentQuery.data;
2554
- const setId = isAssignment ? (_a = activeAssignment == null ? void 0 : activeAssignment.setId) != null ? _a : "" : id;
2555
- const querySet = useSet({ setId });
2556
- const setData = querySet.data;
2557
- const assignmentContent = activeAssignment == null ? void 0 : activeAssignment.content;
2558
- const assignmentWeights = activeAssignment == null ? void 0 : activeAssignment.weights;
2559
- const setContent = setData == null ? void 0 : setData.content;
2560
- const setWeights = setData == null ? void 0 : setData.weights;
2561
- const contentCardsToUse = isAssignment ? assignmentContent != null ? assignmentContent : setContent : setContent;
2562
- const weightsToUse = isAssignment ? assignmentWeights != null ? assignmentWeights : setWeights : setWeights;
2563
- const activityId = isAssignment ? (_b = activeAssignment == null ? void 0 : activeAssignment.id) != null ? _b : "" : setId;
2564
- const { cardsObject, cardsQueries, cards } = useCards({
2565
- cardIds: contentCardsToUse != null ? contentCardsToUse : [],
2566
- enabled: querySet.isSuccess,
2567
- asObject: true
2568
- });
2569
- const scorableCardIds = (contentCardsToUse != null ? contentCardsToUse : []).filter((cardId) => {
2570
- const card = cardsObject == null ? void 0 : cardsObject[cardId];
2571
- return (card == null ? void 0 : card.type) !== "MEDIA_PAGE" /* MEDIA_PAGE */;
2572
- });
2573
- const scoreQuery = useScore({
2574
- isAssignment,
2575
- activityId: id,
2576
- userId,
2577
- courseId: activeAssignment == null ? void 0 : activeAssignment.courseId,
2578
- googleClassroomUserId: user.profile.googleClassroomUserId,
2579
- enabled: isAssignment ? assignmentQuery.isSuccess : querySet.isSuccess
2580
- });
2581
- const { mutationUpdateScore } = useUpdateScore();
2582
- const { mutationUpdateCardScore } = useUpdateCardScore({
2583
- activityId,
2584
- isAssignment,
2585
- userId,
2586
- cardIds: scorableCardIds,
2587
- weights: weightsToUse != null ? weightsToUse : {}
2588
- });
2589
- const { mutationClearScore } = useClearScore();
2590
- const { submitAssignmentScore: submitAssignmentScore2 } = useSubmitAssignmentScore({
2591
- onAssignmentSubmitted,
2592
- studentName: user.profile.displayName
2593
- });
2594
- const { submitPracticeScore: submitPracticeScore2 } = useSubmitPracticeScore();
2595
- const handleUpdateScore = (data) => {
2596
- mutationUpdateScore.mutate({
2597
- data,
2598
- isAssignment,
2599
- activityId,
2600
- userId
2601
- });
2602
- };
2603
- const handleUpdateCardScore = (cardId, cardScore) => {
2604
- mutationUpdateCardScore.mutate({ cardId, cardScore });
2605
- if (cardScore.proficiency_level) {
2606
- logGradingStandardEntry({
2607
- type: cardScore.proficiency_level.standardId,
2608
- cardId,
2609
- gradingStandard: cardScore.proficiency_level
2610
- });
2611
- } else if (cardScore.wida || cardScore.actfl) {
2612
- logGradingStandardEntry({
2613
- type: cardScore.wida ? "wida" : "actfl",
2614
- cardId,
2615
- gradingStandard: cardScore.wida || cardScore.actfl || { level: "", justification: "" }
2616
- });
2617
- }
2618
- };
2619
- const onClearScore = ({
2620
- cardId,
2621
- wasCompleted = true
2622
- }) => {
2623
- var _a2, _b2;
2624
- const currentCard = cardsObject == null ? void 0 : cardsObject[cardId];
2625
- if ((currentCard == null ? void 0 : currentCard.type) === "MULTIPLE_CHOICE" /* MULTIPLE_CHOICE */ || (currentCard == null ? void 0 : currentCard.type) === "READ_REPEAT" /* READ_REPEAT */) {
2626
- return;
2627
- }
2628
- const queryKeys = scoreQueryKeys.byId(activityId);
2629
- const activeCardScores = (_b2 = (_a2 = queryClient.getQueryData(queryKeys)) == null ? void 0 : _a2.cards) == null ? void 0 : _b2[cardId];
2630
- if (activeCardScores === void 0) return;
2631
- mutationClearScore.mutate({
2632
- isAssignment,
2633
- activityId,
2634
- cardScores: activeCardScores,
2635
- cardId,
2636
- userId
2637
- });
2638
- };
2639
- const onSubmitScore = async () => {
2640
- var _a2, _b2, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w;
2641
- try {
2642
- let results;
2643
- if (isAssignment) {
2644
- const someCardIsManualGraded = cards.some((page) => page.grading_method === "manual");
2645
- results = await submitAssignmentScore2({
2646
- assignment: {
2647
- id: (_b2 = (_a2 = assignmentQuery.data) == null ? void 0 : _a2.id) != null ? _b2 : "",
2648
- name: (_d = (_c = assignmentQuery.data) == null ? void 0 : _c.name) != null ? _d : "",
2649
- owners: (_f = (_e = assignmentQuery.data) == null ? void 0 : _e.owners) != null ? _f : [],
2650
- courseId: (_h = (_g = assignmentQuery.data) == null ? void 0 : _g.courseId) != null ? _h : "",
2651
- courseWorkId: (_j = (_i = assignmentQuery.data) == null ? void 0 : _i.courseWorkId) != null ? _j : "",
2652
- isAssessment: (_l = (_k = assignmentQuery.data) == null ? void 0 : _k.isAssessment) != null ? _l : false,
2653
- maxPoints: (_n = (_m = assignmentQuery.data) == null ? void 0 : _m.maxPoints) != null ? _n : 0
2654
- },
2655
- userId,
2656
- cardIds: scorableCardIds,
2657
- scores: scoreQuery.data,
2658
- weights: weightsToUse != null ? weightsToUse : {},
2659
- status: someCardIsManualGraded ? "PENDING_REVIEW" : "SUBMITTED"
2660
- });
2661
- if ((_o = assignmentQuery.data) == null ? void 0 : _o.ltiDeeplink) {
2662
- submitLTIScore({
2663
- maxPoints: (_p = assignmentQuery.data) == null ? void 0 : _p.maxPoints,
2664
- score: (_r = (_q = scoreQuery.data) == null ? void 0 : _q.score) != null ? _r : 0,
2665
- SERVICE_KEY: (_s = ltiData == null ? void 0 : ltiData.serviceKey) != null ? _s : "",
2666
- lineItemId: (_t = ltiData == null ? void 0 : ltiData.lineItemId) != null ? _t : "",
2667
- lti_id: (_u = ltiData == null ? void 0 : ltiData.lti_id) != null ? _u : ""
2668
- });
2669
- }
2670
- } else {
2671
- results = await submitPracticeScore2({
2672
- setId: (_w = (_v = querySet.data) == null ? void 0 : _v.id) != null ? _w : "",
2673
- userId,
2674
- scores: scoreQuery.data
2675
- });
2676
- }
2677
- return results;
2678
- } catch (error) {
2679
- return {
2680
- success: false,
2681
- error
2682
- };
2683
- }
2684
- };
2685
- const logGradingStandardEntry = ({
2686
- cardId,
2687
- gradingStandard,
2688
- type
2689
- }) => {
2690
- var _a2, _b2, _c, _d, _e, _f, _g, _h, _i;
2691
- const card = cardsObject == null ? void 0 : cardsObject[cardId];
2692
- const scoresObject = queryClient.getQueryData(scoreQueryKeys.byId(activityId));
2693
- const cardScore = (_a2 = scoresObject == null ? void 0 : scoresObject.cards) == null ? void 0 : _a2[cardId];
2694
- const serverTimestamp2 = api.helpers.serverTimestamp;
2695
- addGradingStandardLog(
2696
- {
2697
- assignmentId: (_b2 = activeAssignment == null ? void 0 : activeAssignment.id) != null ? _b2 : "",
2698
- courseId: (_c = activeAssignment == null ? void 0 : activeAssignment.courseId) != null ? _c : "",
2699
- teacherId: (_d = activeAssignment == null ? void 0 : activeAssignment.owners[0]) != null ? _d : "",
2700
- setId: (_e = setData == null ? void 0 : setData.id) != null ? _e : "",
2701
- cardId,
2702
- level: gradingStandard.level,
2703
- justification: gradingStandard.justification,
2704
- transcript: (_f = cardScore == null ? void 0 : cardScore.transcript) != null ? _f : "",
2705
- audioUrl: (_g = cardScore == null ? void 0 : cardScore.audio) != null ? _g : "",
2706
- prompt: (_h = card == null ? void 0 : card.prompt) != null ? _h : "",
2707
- responseType: (card == null ? void 0 : card.type) === "RESPOND_WRITE" /* RESPOND_WRITE */ ? "written" : "spoken",
2708
- type,
2709
- dateMade: serverTimestamp2(),
2710
- language: (_i = card == null ? void 0 : card.language) != null ? _i : ""
2711
- },
2712
- userId
2713
- );
2714
- };
2715
- (0, import_react3.useEffect)(() => {
2716
- if (isAssignment) {
2717
- logOpenAssignment({ assignmentId: id });
2718
- } else {
2719
- logOpenActivityPreview({ setId: id });
2720
- }
2721
- }, []);
2722
- useInitActivity({
2723
- assignment: activeAssignment != null ? activeAssignment : void 0,
2724
- set: setData != null ? setData : void 0,
2725
- enabled: !!setData,
2726
- userId
2727
- });
2728
- return {
2729
- set: {
2730
- data: setData,
2731
- query: querySet
2732
- },
2733
- cards: {
2734
- data: cardsObject,
2735
- query: cardsQueries,
2736
- cardsArray: cards
2737
- },
2738
- assignment: {
2739
- data: isAssignment ? activeAssignment : void 0,
2740
- query: assignmentQuery
2741
- },
2742
- scores: {
2743
- data: scoreQuery.data,
2744
- query: scoreQuery,
2745
- actions: {
2746
- update: handleUpdateScore,
2747
- clear: onClearScore,
2748
- submit: onSubmitScore,
2749
- updateCard: handleUpdateCardScore,
2750
- logGradingStandardEntry
2751
- }
2752
- }
2753
- };
2754
- }
2755
- var useInitActivity = ({
2756
- assignment,
2757
- set,
2758
- enabled,
2759
- userId
2760
- }) => {
2761
- const { trackActivity } = useActivityTracker({ userId });
2762
- const init = () => {
2763
- var _a, _b, _c, _d, _e, _f, _g;
2764
- if (!enabled) return;
2765
- if (!assignment) {
2766
- trackActivity({
2767
- activityName: (_a = set == null ? void 0 : set.name) != null ? _a : "",
2768
- activityType: "set",
2769
- id: set == null ? void 0 : set.id,
2770
- language: set == null ? void 0 : set.language
2771
- });
2772
- } else if (assignment.name) {
2773
- trackActivity({
2774
- activityName: assignment.name,
2775
- activityType: assignment.isAssessment ? "assessment" : "assignment",
2776
- id: assignment.id,
2777
- language: set == null ? void 0 : set.language
2778
- });
2779
- }
2780
- if (set == null ? void 0 : set.public) {
2781
- (_d = (_c = (_b = api).httpsCallable) == null ? void 0 : _c.call(_b, "onSetOpened")) == null ? void 0 : _d({
2782
- setId: set.id,
2783
- language: set.language
2784
- });
2785
- }
2786
- (_g = (_f = (_e = api).httpsCallable) == null ? void 0 : _f.call(_e, "updateAlgoliaIndex")) == null ? void 0 : _g({
2787
- updatePlays: true,
2788
- objectID: set == null ? void 0 : set.id
2789
- });
2790
- };
2791
- (0, import_react3.useEffect)(() => {
2792
- init();
2793
- }, [set]);
2794
- };
2795
- var submitLTIScore = async ({
2796
- maxPoints,
2797
- score,
2798
- SERVICE_KEY,
2799
- lineItemId,
2800
- lti_id
2801
- }) => {
2802
- var _a, _b, _c;
2803
- try {
2804
- if (!SERVICE_KEY || !lineItemId || !lti_id) {
2805
- throw new Error("Missing required LTI credentials");
2806
- }
2807
- const earnedPoints = score ? score / 100 * maxPoints : 0;
2808
- const { data } = await ((_c = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "submitLTIAssignmentScore")) == null ? void 0 : _c({
2809
- SERVICE_KEY,
2810
- scoreData: {
2811
- lineItemId,
2812
- userId: lti_id,
2813
- maxPoints,
2814
- earnedPoints
2815
- }
2816
- }));
2817
- return { success: true, data };
2818
- } catch (error) {
2819
- console.error("Failed to submit LTI score:", error);
2820
- return {
2821
- success: false,
2822
- error: error instanceof Error ? error : new Error("Unknown error occurred")
2823
- };
2824
- }
2825
- };
2826
-
2827
- // src/hooks/useCredits.ts
2828
- var import_react_query5 = require("@tanstack/react-query");
2829
- var creditQueryKeys = {
2830
- userCredits: (uid) => ["userCredits", uid]
2831
- };
2832
- var useUserCredits = () => {
2833
- const { user } = useSpeakableApi();
2834
- const email = user.auth.email;
2835
- const uid = user.auth.uid;
2836
- const query2 = (0, import_react_query5.useQuery)({
2837
- queryKey: creditQueryKeys.userCredits(uid),
2838
- queryFn: () => fetchUserCredits({ uid, email }),
2839
- enabled: !!uid,
2840
- refetchInterval: 1e3 * 60 * 5
2841
- });
2842
- return {
2843
- ...query2
2844
- };
2845
- };
2846
- var fetchUserCredits = async ({ uid, email }) => {
2847
- if (!uid) {
2848
- throw new Error("User ID is required");
2849
- }
2850
- const contractSnap = await api.getDoc(`creditContracts/${uid}`);
2851
- if (contractSnap.data == null) {
2852
- return {
2853
- id: uid,
2854
- userId: uid,
2855
- email,
2856
- effectivePlanId: "free_tier",
2857
- status: "inactive",
2858
- isUnlimited: false,
2859
- creditsAvailable: 100,
2860
- creditsAllocatedThisPeriod: 100,
2861
- topOffCreditsAvailable: 0,
2862
- topOffCreditsTotal: 0,
2863
- allocationSource: "free_tier",
2864
- sourceDetails: {},
2865
- periodStart: null,
2866
- periodEnd: null,
2867
- planTermEndTimestamp: null,
2868
- ownerType: "individual",
2869
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
2870
- lastUpdatedAt: (/* @__PURE__ */ new Date()).toISOString()
2871
- };
2872
- }
2873
- const contractData = contractSnap.data;
2874
- const monthlyCredits = (contractData == null ? void 0 : contractData.creditsAvailable) || 0;
2875
- const topOffCredits = (contractData == null ? void 0 : contractData.topOffCreditsAvailable) || 0;
2876
- const totalCredits = monthlyCredits + topOffCredits;
2877
- return {
2878
- id: contractSnap.id,
2879
- ...contractData,
2880
- // Add computed total for convenience
2881
- totalCreditsAvailable: totalCredits
2882
- };
2883
- };
2884
-
2885
- // src/hooks/useOrganizationAccess.ts
2886
- var import_react_query6 = require("@tanstack/react-query");
2887
- var useOrganizationAccess = () => {
2888
- const { user } = useSpeakableApi();
2889
- const email = user.auth.email;
2890
- const query2 = (0, import_react_query6.useQuery)({
2891
- queryKey: ["organizationAccess", email],
2892
- queryFn: async () => {
2893
- if (!email) {
2894
- return {
2895
- hasUnlimitedAccess: false,
2896
- subscriptionId: null,
2897
- organizationId: null,
2898
- organizationName: null,
2899
- subscriptionEndDate: null,
2900
- accessType: "individual"
2901
- };
2902
- }
2903
- return getOrganizationAccess(email);
2904
- },
2905
- enabled: !!email,
2906
- // Only run query if we have a user email
2907
- staleTime: 5 * 60 * 1e3,
2908
- // Consider data fresh for 5 minutes
2909
- gcTime: 10 * 60 * 1e3,
2910
- // Keep in cache for 10 minutes
2911
- retry: 2
2912
- // Retry failed requests twice
2913
- });
2914
- return {
2915
- ...query2
2916
- };
2917
- };
2918
- var getOrganizationAccess = async (email) => {
2919
- const { limit: limit2, where: where2 } = api.accessQueryConstraints();
2920
- try {
2921
- const organizationSnapshot = await api.getDocs(
2922
- "organizations",
2923
- where2("members", "array-contains", email),
2924
- where2("masterSubscriptionStatus", "==", "active"),
2925
- limit2(1)
2926
- );
2927
- if (!organizationSnapshot.empty) {
2928
- const orgData = organizationSnapshot.data[0];
2929
- return {
2930
- hasUnlimitedAccess: true,
2931
- subscriptionId: orgData == null ? void 0 : orgData.masterSubscriptionId,
2932
- organizationId: orgData.id,
2933
- organizationName: orgData.name || "Unknown Organization",
2934
- subscriptionEndDate: orgData.masterSubscriptionEndDate || null,
2935
- accessType: "organization"
2936
- };
2937
- }
2938
- const institutionSnapshot = await api.getDocs(
2939
- "institution_subscriptions",
2940
- where2("users", "array-contains", email),
2941
- where2("active", "==", true),
2942
- limit2(1)
2943
- );
2944
- if (!institutionSnapshot.empty) {
2945
- const institutionData = institutionSnapshot.data[0];
2946
- const isUnlimited = (institutionData == null ? void 0 : institutionData.plan) === "organization" || (institutionData == null ? void 0 : institutionData.plan) === "school_starter";
2947
- return {
2948
- hasUnlimitedAccess: isUnlimited,
2949
- subscriptionId: institutionData.id,
2950
- organizationId: institutionData == null ? void 0 : institutionData.institutionId,
2951
- organizationName: institutionData.name || institutionData.institutionId || "Legacy Institution",
2952
- subscriptionEndDate: institutionData.endDate || null,
2953
- accessType: "institution_subscriptions"
2954
- };
2955
- }
2956
- return {
2957
- hasUnlimitedAccess: false,
2958
- subscriptionId: null,
2959
- organizationId: null,
2960
- organizationName: null,
2961
- subscriptionEndDate: null,
2962
- accessType: "individual"
2963
- };
2964
- } catch (error) {
2965
- console.error("Error checking organization access:", error);
2966
- return {
2967
- hasUnlimitedAccess: false,
2968
- subscriptionId: null,
2969
- organizationId: null,
2970
- organizationName: null,
2971
- subscriptionEndDate: null,
2972
- accessType: "individual"
2973
- };
2974
- }
2975
- };
2976
-
2977
- // src/hooks/useUpdateStudentVoc.ts
2978
- var useUpdateStudentVocab = (page) => {
2979
- const { user } = useSpeakableApi();
2980
- const currentUserId = user == null ? void 0 : user.auth.uid;
2981
- if (!page || !currentUserId || !page.target_text || !page.language) {
2982
- return {
2983
- studentVocabMarkVoiceSuccess: void 0,
2984
- studentVocabMarkVoiceFail: void 0
2985
- };
2986
- }
2987
- const getDataObject = () => {
2988
- var _a, _b;
2989
- const { serverTimestamp: serverTimestamp2 } = api.accessHelpers();
2990
- const language = (_a = page.language) != null ? _a : "en";
2991
- const word = (_b = page.target_text) != null ? _b : "";
2992
- const phrase_length = getPhraseLength(word);
2993
- const wordHash = getWordHash(word, language);
2994
- const docPath = `users/${currentUserId}/vocab/${wordHash}`;
2995
- const communityPath = `checked-pronunciations/${wordHash}`;
2996
- const id = `${language}-${cleanString(word)}`;
2997
- const data = {
2998
- id,
2999
- word,
3000
- words: (word == null ? void 0 : word.split(" ")) || [],
3001
- wordHash,
3002
- language,
3003
- lastSeen: serverTimestamp2(),
3004
- phrase_length
3005
- };
3006
- return {
3007
- docPath,
3008
- communityPath,
3009
- data
3010
- };
3011
- };
3012
- const markVoiceSuccess = async () => {
3013
- const { docPath, communityPath, data } = getDataObject();
3014
- const { increment: increment2 } = api.accessQueryConstraints();
3015
- const { serverTimestamp: serverTimestamp2 } = api.accessHelpers();
3016
- data.voiceSuccess = increment2(1);
3017
- try {
3018
- await api.updateDoc(docPath, data);
3019
- } catch (error) {
3020
- if (error instanceof Error && error.message === "not-found") {
3021
- data.firstSeen = serverTimestamp2();
3022
- await api.setDoc(docPath, data, { merge: true });
3023
- } else {
3024
- console.log(error);
3025
- }
3026
- }
3027
- try {
3028
- data.pronunciations = increment2(1);
3029
- await api.setDoc(communityPath, data, { merge: true });
3030
- } catch (error) {
3031
- console.log(error);
3032
- }
3033
- };
3034
- const markVoiceFail = async () => {
3035
- const { docPath, communityPath, data } = getDataObject();
3036
- const { increment: increment2 } = api.accessQueryConstraints();
3037
- const { serverTimestamp: serverTimestamp2 } = api.accessHelpers();
3038
- data.voiceFail = increment2(1);
3039
- try {
3040
- await api.updateDoc(docPath, data);
3041
- } catch (error) {
3042
- if (error instanceof Error && error.message === "not-found") {
3043
- data.firstSeen = serverTimestamp2();
3044
- await api.setDoc(docPath, data, { merge: true });
3045
- } else {
3046
- console.log(error);
3047
- }
3048
- }
3049
- try {
3050
- data.fails = increment2(1);
3051
- await api.setDoc(communityPath, data, { merge: true });
3052
- } catch (error) {
3053
- console.log(error);
3054
- }
3055
- };
3056
- return {
3057
- studentVocabMarkVoiceSuccess: markVoiceSuccess,
3058
- studentVocabMarkVoiceFail: markVoiceFail
3059
- };
3060
- };
3061
-
3062
- // src/hooks/useActivityFeedbackAccess.ts
3063
- var import_react_query7 = require("@tanstack/react-query");
3064
- var activityFeedbackAccessQueryKeys = {
3065
- activityFeedbackAccess: (args) => ["activityFeedbackAccess", ...Object.values(args)]
3066
- };
3067
- var useActivityFeedbackAccess = ({
3068
- aiEnabled = false,
3069
- isActivityRoute = false
3070
- }) => {
3071
- var _a, _b, _c;
3072
- const { user } = useSpeakableApi();
3073
- const uid = user.auth.uid;
3074
- const isTeacher = (_a = user.profile) == null ? void 0 : _a.isTeacher;
3075
- const isStudent = (_b = user.profile) == null ? void 0 : _b.isStudent;
3076
- const userRoles = ((_c = user.profile) == null ? void 0 : _c.roles) || [];
3077
- const query2 = (0, import_react_query7.useQuery)({
3078
- queryKey: activityFeedbackAccessQueryKeys.activityFeedbackAccess({
3079
- aiEnabled,
3080
- isActivityRoute
3081
- }),
3082
- queryFn: async () => {
3083
- var _a2, _b2, _c2;
3084
- if (!uid) {
3085
- return {
3086
- canAccessFeedback: false,
3087
- reason: "Missing user ID",
3088
- isUnlimited: false,
3089
- accessType: "none"
3090
- };
3091
- }
3092
- try {
3093
- if (aiEnabled) {
3094
- return {
3095
- canAccessFeedback: true,
3096
- reason: "AI feedback enabled",
3097
- isUnlimited: true,
3098
- accessType: "ai_enabled"
3099
- };
3100
- }
3101
- if (isTeacher || userRoles.includes("ADMIN")) {
3102
- return {
3103
- canAccessFeedback: true,
3104
- reason: "Teacher preview access",
3105
- isUnlimited: true,
3106
- accessType: "teacher_preview"
3107
- };
3108
- }
3109
- if (isStudent && isActivityRoute) {
3110
- try {
3111
- const result = await ((_c2 = (_b2 = (_a2 = api).httpsCallable) == null ? void 0 : _b2.call(_a2, "checkStudentTeacherPlan")) == null ? void 0 : _c2({
3112
- studentId: uid
3113
- }));
3114
- const planCheckResult = result.data;
3115
- if (planCheckResult.canAccessFeedback) {
3116
- return {
3117
- canAccessFeedback: true,
3118
- reason: planCheckResult.reason || "Student access via teacher with active plan",
3119
- isUnlimited: planCheckResult.hasTeacherWithUnlimitedAccess,
3120
- accessType: "student_with_teacher_plan"
3121
- };
3122
- } else {
3123
- return {
3124
- canAccessFeedback: false,
3125
- reason: planCheckResult.reason || "No teacher with active plan found",
3126
- isUnlimited: false,
3127
- accessType: "none"
3128
- };
3129
- }
3130
- } catch (error) {
3131
- console.error("Error checking student teacher plan:", error);
3132
- return {
3133
- canAccessFeedback: false,
3134
- reason: "Error checking teacher plans",
3135
- isUnlimited: false,
3136
- accessType: "none"
3137
- };
3138
- }
3139
- }
3140
- return {
3141
- canAccessFeedback: false,
3142
- reason: "No access permissions found for current context",
3143
- isUnlimited: false,
3144
- accessType: "none"
3145
- };
3146
- } catch (error) {
3147
- console.error("Error checking activity feedback access:", error);
3148
- return {
3149
- canAccessFeedback: false,
3150
- reason: "Error checking access permissions",
3151
- isUnlimited: false,
3152
- accessType: "none"
3153
- };
3154
- }
3155
- },
3156
- enabled: !!uid,
3157
- staleTime: 5 * 60 * 1e3,
3158
- // 5 minutes
3159
- gcTime: 10 * 60 * 1e3
3160
- // 10 minutes
3161
- });
3162
- return {
3163
- ...query2
3164
- };
3165
- };
3166
-
3167
- // src/hooks/useOpenAI.ts
3168
- var useBaseOpenAI = ({
3169
- onTranscriptSuccess,
3170
- onTranscriptError,
3171
- onCompletionSuccess,
3172
- onCompletionError,
3173
- aiEnabled,
3174
- submitAudioResponse,
3175
- uploadAudioAndGetTranscript,
3176
- onGetAudioUrlAndTranscript
3177
- }) => {
3178
- const { user, queryClient } = useSpeakableApi();
3179
- const currentUserId = user.auth.uid;
3180
- const { data: feedbackAccess } = useActivityFeedbackAccess({
3181
- aiEnabled
3182
- });
3183
- const getTranscript = async (audioUrl, language, prompt) => {
3184
- var _a, _b, _c, _d;
3185
- const getGeminiTranscript = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "getGeminiTranscript");
3186
- const getAssemblyAITranscript = (_d = (_c = api).httpsCallable) == null ? void 0 : _d.call(_c, "transcribeAssemblyAIAudio");
3187
- try {
3188
- const { data } = await (getGeminiTranscript == null ? void 0 : getGeminiTranscript({
3189
- audioUrl,
3190
- targetLanguage: language,
3191
- prompt: prompt || ""
3192
- }));
3193
- const transcript = data.transcript;
3194
- if (transcript) {
3195
- return transcript;
3196
- }
3197
- } catch (error) {
3198
- console.log("Gemini transcript failed, trying AssemblyAI fallback:", error);
3199
- }
3200
- try {
3201
- const response = await (getAssemblyAITranscript == null ? void 0 : getAssemblyAITranscript({
3202
- audioUrl,
3203
- language
3204
- }));
3205
- const transcript = response == null ? void 0 : response.data;
3206
- if (transcript) {
3207
- return transcript;
3208
- }
3209
- throw new Error("Both transcript services failed");
3210
- } catch (error) {
3211
- console.log("AssemblyAI transcript also failed:", error);
3212
- onTranscriptError({
3213
- type: "TRANSCRIPT",
3214
- message: (error == null ? void 0 : error.message) || "Error getting transcript from both services"
3215
- });
3216
- throw new Error(error);
3217
- }
3218
- };
3219
- const getFreeResponseCompletion = async (messages, isFreeResponse, feedbackLanguage, gradingStandard = "actfl") => {
3220
- var _a, _b, _c, _d, _e;
3221
- const responseTool = getRespondCardTool({
3222
- language: feedbackLanguage,
3223
- standard: gradingStandard
3224
- });
3225
- try {
3226
- const createChatCompletion = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "createChatCompletion");
3227
- const {
3228
- data: {
3229
- response,
3230
- prompt_tokens = 0,
3231
- completion_tokens = 0,
3232
- success: aiSuccess = false
3233
- // the AI was able to generate a response
3234
- }
3235
- } = await (createChatCompletion == null ? void 0 : createChatCompletion({
3236
- chat: {
3237
- model: isFreeResponse ? "gpt-4-1106-preview" : "gpt-3.5-turbo-1106",
3238
- messages,
3239
- temperature: 0.7,
3240
- ...responseTool
3241
- },
3242
- type: isFreeResponse ? "LONG_RESPONSE" : "SHORT_RESPONSE"
3243
- }));
3244
- 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) || "{}");
3245
- const result = {
3246
- ...functionArguments,
3247
- prompt_tokens,
3248
- completion_tokens,
3249
- aiSuccess
3250
- };
3251
- onCompletionSuccess(result);
3252
- return result;
3253
- } catch (error) {
3254
- onCompletionError({
3255
- type: "COMPLETION",
3256
- message: (error == null ? void 0 : error.message) || "Error getting completion"
3257
- });
3258
- throw new Error(error);
3259
- }
3260
- };
3261
- const getFeedback = async ({
3262
- cardId,
3263
- language = "en",
3264
- // required
3265
- writtenResponse = null,
3266
- // if the type = RESPOND_WRITE
3267
- audio = null,
3268
- autoGrade = true,
3269
- file = null,
3270
- pagePrompt = null
3271
- }) => {
3272
- try {
3273
- if (!(feedbackAccess == null ? void 0 : feedbackAccess.canAccessFeedback)) {
3274
- const result = {
3275
- noFeedbackAvailable: true,
3276
- success: true,
3277
- reason: (feedbackAccess == null ? void 0 : feedbackAccess.reason) || "No feedback access",
3278
- accessType: (feedbackAccess == null ? void 0 : feedbackAccess.accessType) || "none"
3279
- };
3280
- onCompletionSuccess(result);
3281
- return result;
3282
- }
3283
- let transcript;
3284
- let audioUrl = void 0;
3285
- if (writtenResponse) {
3286
- transcript = writtenResponse;
3287
- onTranscriptSuccess(writtenResponse);
3288
- } else if (typeof audio === "string" && file) {
3289
- if (feedbackAccess == null ? void 0 : feedbackAccess.canAccessFeedback) {
3290
- transcript = await getTranscript(audio, language, pagePrompt != null ? pagePrompt : "");
3291
- audioUrl = audio;
3292
- onTranscriptSuccess(transcript);
3293
- } else {
3294
- console.info(
3295
- `Transcript not available: ${(feedbackAccess == null ? void 0 : feedbackAccess.reason) || "No feedback access"}`
3296
- );
3297
- }
3298
- } else {
3299
- const response = await uploadAudioAndGetTranscript(audio || "", language, pagePrompt != null ? pagePrompt : "");
3300
- transcript = response.transcript;
3301
- audioUrl = response.audioUrl;
3302
- }
3303
- onGetAudioUrlAndTranscript == null ? void 0 : onGetAudioUrlAndTranscript({ transcript, audioUrl });
3304
- if (feedbackAccess == null ? void 0 : feedbackAccess.canAccessFeedback) {
3305
- const results = await getAIResponse({
3306
- cardId,
3307
- transcript: transcript || ""
3308
- });
3309
- let output = results;
3310
- if (!autoGrade) {
3311
- output = {
3312
- ...output,
3313
- noFeedbackAvailable: true,
3314
- success: true
3315
- };
3316
- }
3317
- onCompletionSuccess(output);
3318
- return output;
3319
- } else {
3320
- const result = {
3321
- noFeedbackAvailable: true,
3322
- success: true,
3323
- reason: (feedbackAccess == null ? void 0 : feedbackAccess.reason) || "No feedback access",
3324
- accessType: (feedbackAccess == null ? void 0 : feedbackAccess.accessType) || "none"
3325
- };
3326
- onCompletionSuccess(result);
3327
- return result;
3328
- }
3329
- } catch (error) {
3330
- console.error("Error getting feedback:", error);
3331
- throw new Error(error);
3332
- }
3333
- };
3334
- const getAIResponse = async ({ cardId, transcript }) => {
3335
- var _a, _b, _c, _d, _e;
3336
- try {
3337
- const getGeminiFeedback = (_b = (_a = api).httpsCallable) == null ? void 0 : _b.call(_a, "callGetFeedback");
3338
- const getProficiencyEstimate = (_d = (_c = api).httpsCallable) == null ? void 0 : _d.call(_c, "getProficiencyEstimate");
3339
- const card = getCardFromCache({
3340
- cardId,
3341
- queryClient
3342
- });
3343
- let feedbackData;
3344
- let proficiencyData = {};
3345
- if (card && card.grading_method === "manual") {
3346
- } else if (card && card.grading_method !== "standards_based") {
3347
- const [geminiResult, proficiencyResult] = await Promise.all([
3348
- getGeminiFeedback == null ? void 0 : getGeminiFeedback({
3349
- cardId,
3350
- studentId: currentUserId,
3351
- studentResponse: transcript
3352
- }),
3353
- getProficiencyEstimate == null ? void 0 : getProficiencyEstimate({
3354
- cardId,
3355
- studentId: currentUserId,
3356
- studentResponse: transcript
3357
- })
3358
- ]);
3359
- proficiencyData = (proficiencyResult == null ? void 0 : proficiencyResult.data) || {};
3360
- feedbackData = {
3361
- ...(_e = geminiResult == null ? void 0 : geminiResult.data) != null ? _e : {},
3362
- // @ts-ignore
3363
- proficiency_level: (proficiencyData == null ? void 0 : proficiencyData.proficiency_level) || null
3364
- };
3365
- } else {
3366
- const geminiResult = await (getGeminiFeedback == null ? void 0 : getGeminiFeedback({
3367
- cardId,
3368
- studentId: currentUserId,
3369
- studentResponse: transcript
3370
- }));
3371
- feedbackData = geminiResult == null ? void 0 : geminiResult.data;
3372
- }
3373
- const results = {
3374
- ...proficiencyData,
3375
- ...feedbackData,
3376
- aiSuccess: true,
3377
- promptSuccess: (feedbackData == null ? void 0 : feedbackData.success) || false,
3378
- transcript
3379
- };
3380
- return results;
3381
- } catch (error) {
3382
- onCompletionError({
3383
- type: "AI_FEEDBACK",
3384
- message: (error == null ? void 0 : error.message) || "Error getting ai feedback"
3385
- });
3386
- throw new Error(error);
3387
- }
3388
- };
3389
- return {
3390
- submitAudioResponse,
3391
- uploadAudioAndGetTranscript,
3392
- getTranscript,
3393
- getFreeResponseCompletion,
3394
- getFeedback
3395
- };
3396
- };
3397
-
3398
- // src/lib/create-firebase-client-native.ts
3399
- var import_firestore = require("@react-native-firebase/firestore");
3400
-
3401
1045
  // src/lib/create-firebase-client.ts
3402
1046
  function createFsClientBase({
3403
1047
  db,