@speakableio/core 0.1.99 → 0.1.101

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