Skip to content

Commit

Permalink
Merge pull request #4 from levante-framework/survey-data-update
Browse files Browse the repository at this point in the history
saving all responses for survey, fixing survey data fetching
  • Loading branch information
Zio-4 authored Jun 7, 2024
2 parents aca6d08 + cbda230 commit 597f799
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 47 deletions.
3 changes: 2 additions & 1 deletion src/components/ParticipantSidebar.vue
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<p>{{ $t('participantSidebar.tasksCompleted') }}</p>
</div>
</div>
<ul v-if="!!studentInfo" class="sidebar-info">
<ul v-if="!_isEmpty(studentInfo)" class="sidebar-info">
<li class="sidebar-title">
<strong>{{ $t('participantSidebar.studentInfo') }}</strong>
</li>
Expand All @@ -19,6 +19,7 @@
</template>
<script setup>
import { ref, computed } from 'vue';
import _isEmpty from 'lodash/isEmpty';
const props = defineProps({
totalGames: { type: Number, required: true, default: 0 },
Expand Down
49 changes: 23 additions & 26 deletions src/helpers/query/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -188,32 +188,29 @@ export const matchMode2Op = {
notEquals: 'NOT_EQUAL',
};

export const fetchSubcollection = async (collectionPath, subcollectionName, select = [], db = 'admin') => {
const axiosInstance = getAxiosInstance(db);
// Construct the path to the subcollection
const subcollectionPath = `/${collectionPath}/${subcollectionName}`;
const queryParams = select.map((field) => `mask.fieldPaths=${field}`).join('&');
const queryString = queryParams ? `?${queryParams}` : '';
export const fetchSubcollection = async (collectionPath, subcollectionName, select = [], db = 'admin') => {
try {
const axiosInstance = getAxiosInstance(db);
const subcollectionPath = `/${collectionPath}/${subcollectionName}`;

return axiosInstance
.get(subcollectionPath + queryString)
.then(({ data }) => {
// console.log('subcollection data: ', data);
// Build query string for selected fields
const queryParams = select.map((field) => `mask.fieldPaths=${field}`).join('&');
const queryString = queryParams ? `?${queryParams}` : '';

// Assuming the API returns an array of document data in the subcollection
return data.documents
? data.documents.map((doc) => {
return {
id: doc.name.split('/').pop(), // Extract document ID from the document name/path
..._mapValues(doc.fields, (value) => convertValues(value)),
};
})
: [];
})
.catch((error) => {
console.error(error);
return {
error: `${error.response?.status === 404 ? 'Subcollection not found' : error.message}`,
};
});
const response = await axiosInstance.get(subcollectionPath + queryString);

// Check if the API returns an array of document data in the subcollection
const documents = response.data.documents || [];

// Map and return the documents with the required format
return documents.map((doc) => ({
id: doc.name.split('/').pop(), // Extract document ID from the document name/path
..._mapValues(doc.fields, (value) => convertValues(value)),
}));
} catch (error) {
console.error('Failed to fetch subcollection: ', error);
return {
error: error.response?.status === 404 ? 'Subcollection not found' : error.message,
};
}
};
18 changes: 8 additions & 10 deletions src/pages/HomeParticipant.vue
Original file line number Diff line number Diff line change
Expand Up @@ -265,12 +265,15 @@ const {
staleTime: 5 * 60 * 1000,
});
const { data: surveyResponsesData, error } = useQuery({
const { data: surveyResponsesData, } = useQuery({
queryKey: ['surveyResponses', uid],
queryFn: () => fetchSubcollection(`users/${uid.value}`, 'surveyResponses'),
keepPreviousData: true,
enabled: initialized.value && import.meta.env.MODE === 'LEVANTE',
staleTime: 5 * 60 * 1000,
enabled: initialized && import.meta.env.MODE === 'LEVANTE',
staleTime: 5 * 60 * 1000, // 5 minutes
cacheTime: 10 * 60 * 1000,
// refetchOnMount: false,
// refetchOnWindowFocus: false,
// refetchOnReconnect: false,
});
const isLoading = computed(() => {
Expand Down Expand Up @@ -324,11 +327,6 @@ const assessments = computed(() => {
if (authStore.userData?.userType === 'student' && import.meta.env.MODE === 'LEVANTE') {
// This is just to mark the card as complete
// console.log('surveyResponsesData: ', surveyResponsesData.value);
// console.log('isSurveyCompleted: ', gameStore.isSurveyCompleted);
// console.log('surveyResponses error: ', surveyResponsesData.error?.value);
if (gameStore.isSurveyCompleted || surveyResponsesData.value?.length) {
fetchedAssessments.forEach((assessment) => {
if (assessment.taskId === 'survey') {
Expand Down Expand Up @@ -376,7 +374,7 @@ let completeGames = computed(() => {
// Set up studentInfo for sidebar
const studentInfo = computed(() => {
if (isLevante) {
return null;
return {};
}
return {
grade: _get(userData.value, 'studentData.grade'),
Expand Down
19 changes: 9 additions & 10 deletions src/pages/LEVANTE/UserSurvey.vue
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { useI18n } from 'vue-i18n';
import { BufferLoader, AudioContext } from '@/helpers/audio';
import { useToast } from 'primevue/usetoast';
import { useQueryClient } from '@tanstack/vue-query'
import _merge from 'lodash/merge';
const fetchAudioLinks = async (surveyType) => {
const response = await axios.get('https://storage.googleapis.com/storage/v1/b/road-dashboard/o/');
Expand Down Expand Up @@ -155,23 +156,21 @@ async function playAudio(name) {
}
async function saveResults(sender) {
// If user did not fill out the survey, do not save the results
if (Object.keys(sender.data).length === 0) {
// update game store to let game tabs know
gameStore.requireHomeRefresh();
gameStore.setSurveyCompleted();
router.push({ name: 'Home' });
return;
}
const allQuestions = sender.getAllQuestions();
const unansweredQuestions = {}
allQuestions.forEach((question) => unansweredQuestions[question.name] = null);
// Values from the second object overwrite values from the first
const responsesWithAllQuestions = _merge(unansweredQuestions, sender.data);
// turn on loading state
isSavingResponses.value = true;
// call cloud function to save the survey results
// TODO: Use tanstack-query mutation for automaitic retries.
try {
const res = await roarfirekit.value.saveSurveyResponses(sender.data);
console.log('response: ', res);
const res = await roarfirekit.value.saveSurveyResponses(responsesWithAllQuestions);
// update game store to let game tabs know
gameStore.setSurveyCompleted();
Expand Down

0 comments on commit 597f799

Please sign in to comment.