DigitalConsumer.FixMyGlass/src/layouts/part-questions/part-questions.vue
2022-08-19 10:37:07 -04:00

465 lines
23 KiB
Vue

<template>
<Form
@submit="onSubmit"
@invalid-submit="onInvalidSubmit"
ref="theForm"
v-slot="{ meta }"
>
<div class="page-container-grouped-styles part-questions">
<loadingModal ref="loadingModal"/>
<funnelHeader cmsWidgetName="FunnelHeaderWidget" />
<vehicleBanner cmsWidgetName="VehicleBannerWidget" :displayGenericVehicleImage=false />
<funnelSubHeader cmsWidgetName="FunnelSubHeaderWidget" />
<div class="fade-on-route-transition sub-container make-tall">
<alert
ref="alertFewMoreQuestions"
cmsWidgetName="AlertFewMoreQuestionsWidget"
class="my-5"
alertClass="alert-warning"
:manualHeadline="AlertFewMoreQuestionsHeader"
:manualCopy="AlertFewMoreQuestionsCopy"
v-bind:isDismissible="false"
/>
<div v-for="(part, i) in partsQuestionsData" :key="i">
<questionChain
ref="questionChain"
:key="part.key"
:keyString="part.key"
v-model="selectedAnswers[part.glassLocation + '-' + part.glassName]"
:questionData="part.partQuestions"
:partIndex="i"
v-if="showThisPartQuestionChain(part, i)"
validationRules="questions-required"
/>
</div>
<funnel-footer
ref="funnelFooter"
cmsWidgetName="FunnelFooterWidget"
:isForwardActionDisabled="!meta.valid"
@back-clicked="backButtonAction"
@ForwardClicked="forwardButtonAction"
/>
</div>
</div>
</Form>
</template>
<script>
// Components
import funnelHeader from "@/common-components/funnel-header/funnel-header";
import vehicleBanner from "@/common-components/vehicle-banner/vehicle-banner";
import alert from "@/ux-components/alert/alert";
import questionChain from "@/common-components/question-chain/question-chain";
import funnelSubHeader from "@/common-components/funnel-sub-header/funnel-sub-header";
import funnelFooter from "@/common-components/funnel-footer/funnel-footer";
import loadingModal from '@/common-components/loading-modal/loading-modal.vue';
// Supporting Files
import { fetchCmsContentForPage } from "@/helpers/cms-content-helper";
import { settleAllPromises } from "@/helpers/layout-helper";
import store from "@/store";
import { storeActions } from "@/constants/store-actions";
import { storeMutations } from "@/constants/store-mutations";
import { fmgPageValues } from "@/router/router-constants/fmgPage-values";
import { Form, defineRule } from "vee-validate";
import { required } from "@/helpers/validation-rules";
import { errorMessages } from "@/constants/error-messages";
import vehicleQuestionsMixin from "@/mixins/vehicle-questions-mixin";
import { navigateToHeritageFunnel } from "@/helpers/heritage-integration/navigation-helper";
// DEFINE VALIDATION RULES
defineRule("questions-required", required(errorMessages.OPTION_REQUIRED));
export default {
name: "part-questions",
async beforeRouteEnter(to, from, next) {
// Call APIs
const cmsContentPromise = fetchCmsContentForPage(to.query.fmgPage);
// Settle promises and get results
const promiseResultMap = [
{
resultKey: "cmsContent",
promise: cmsContentPromise,
},
];
const resultMap = await settleAllPromises(promiseResultMap);
// Call the "next" function to complete the transition to this page.
next((vm) => {
vm.setCmsContent(resultMap.cmsContent);
});
},
data() {
return {
partsQuestionsFromApi: this.$store.getters.pageData(fmgPageValues.PART_QUESTIONS)?.partsOrQuestions.filter((p) => {
return Array.isArray(p.partQuestions) && p.partQuestions.length > 0;
}),
selectedAnswers: {},
currentPartNum: 0,
newAnswersArray: [],
partsQuestionsData: [],
foundDuplicateQuestions: [],
};
},
computed: {
AlertFewMoreQuestionsHeader() {
return this.getCmsContent("AlertPartsQuestions", "HeadlineText");
},
AlertFewMoreQuestionsCopy() {
return this.getCmsContent("AlertPartsQuestions", "BodyText");
},
},
mixins: [vehicleQuestionsMixin],
mounted() {
this.LoadInitialPartsData();
},
methods: {
showThisPartQuestionChain(part, i) {
if (part.partQuestions?.length < 1 || part.isSuppressedPart) { return false; } // return false if no partQuestions or if suppressed
if (this.currentPartNum === i || part.answerData?.answerResult?.length > 0) { return true; }
return false;
},
async forwardButtonAction() {
const partQuestionAnswersArray = this.partsQuestionsData.map((item) => {
return {
glassLocation: item.glassLocation,
glassName: item.glassName,
result: item.answerData.answerResult,
answeredQuestions: item.answerData.answeredQuestions,
isSuppressedPart: item.isSuppressedPart,
};
});
// clear out answerData for future page loads; must occur prior to store save
this.partsQuestionsData.forEach((part) => {
part.answerData = {};
});
// save to vuex store as order.damage.partQuestionAnswers (array)
await this.dispatchStoreAction(this.storeActions.SAVE_PART_QUESTION_ANSWERS, partQuestionAnswersArray, false);
// call API parts method
const partsLookup = await this.dispatchStoreAction(storeActions.GET_PARTS)
.catch(() => {
return this.$refs.funnelFooter.removeLoader();
});
const glassNameAndPartsForStore = partsLookup.data.glassNameAndParts;
this.navigateForward(glassNameAndPartsForStore);
},
arePagePrerequisitesValid() {
const partQuestionsFromPageData = store.getters.pageData(fmgPageValues.PART_QUESTIONS);
return partQuestionsFromPageData && Object.keys(partQuestionsFromPageData).length > 0;
},
handleAnswerUpdates(key, answer) { // only runs when all questions in a question-chain have been answered
// when selectedAnswers updates, user has completed this part's question chain and has a final answer
// (does not get run for each invididual question's answer, only when
// all relevent questions for the current part have been answered)
const glassPartWithAnswer = this.partsQuestionsData[answer.partIndex];
const completeAnsweredQuestions = answer.answeredQuestions ? [...answer.answeredQuestions] : [];
const answeredQuestionIndexes = [];
// since user has answered a question differently than anything that was preloaded,
// then clear out the preloaded answers
this.selectedAnswers = {};
// examine all the answers returned that were part of the user's journey through question-chain
// loop through every answered question on currently answered glass part
answer.answeredQuestions?.forEach((aq) => {
// gather all the question numbers of the answered questions
answeredQuestionIndexes.push(aq.questionNum);
const answeredQuestionText = aq.questionText.toUpperCase();
const answeredQuestionAnswer = aq.selectedAnswerText.toUpperCase();
// HANDLE DUPLICATE QUESTIONS
// loop through all glass parts data (but only examining parts after currently being answered part)
this.partsQuestionsData.forEach((glassPart, i) => {
// restrict duplicate logic to only parts that follow the currently being answered part
if (i > answer.partIndex) {
// loop through this glass part's part questions, looking for a questionText match
glassPart.partQuestions.forEach((pq, pqIndex) => {
// clear out any previously set answers
//delete pq.answerSelected;
pq.answerSelected = null;
// does pq.questionText match answeredQuestionText? (aka do we have a duplicate question?)
if (pq.questionText.toUpperCase() === answeredQuestionText) {
// which one of this partQuestions' answers matches our answer?
let matchedAnswer;
pq.answers.forEach((ans, ansIndex) => {
// delete pq.answers[ansIndex].selected;
pq.answers[ansIndex].selected = null;
if (ans.answerText.toUpperCase() === answeredQuestionAnswer) {
matchedAnswer = ans;
pq.answers[ansIndex].selected = true;
}
});
if (matchedAnswer) {
const thisAnsweredPartQuestion = glassPart.partQuestions[pqIndex];
// remove answerData from this glass part
glassPart.answerData = null;
glassPart.isSuppressedPart = null;
// Update the key to re-render this part's question-chain component
this.partsQuestionsData[i].key = this.partsQuestionsData[i].glassLocation + this.partsQuestionsData[i].glassName + Date.now().toString();
// handle suppressing downstream in this question chain
const rejectedAnswer = thisAnsweredPartQuestion.answers.filter((ans) => {
return !ans.selected;
});
if (rejectedAnswer[0].nextQuestionSequence) {
glassPart.partQuestions[rejectedAnswer[0].nextQuestionSequence - 1].suppressDuplicateQuestion = true;
}
if (matchedAnswer.nextQuestionSequence) {
// ensure that accepted answer is NOT suppressed
glassPart.partQuestions[matchedAnswer.nextQuestionSequence - 1].suppressDuplicateQuestion = null;
}
// handle suppressing upstream in this question chain
glassPart.partQuestions.forEach((q) => {
q.answers.forEach((thisAns) => {
// restore any of the answers that formerly led to the duplicated question
if (thisAns.originalNextQuestionSequence === pq.questionSequence) {
// restore original nextQuestionSequence
thisAns.nextQuestionSequence = thisAns.originalNextQuestionSequence;
this.originalNextQuestionSequence = null;
// restore original answerResult
if (thisAns.originalAnswerResult) {
thisAns.answerResult = thisAns.originalAnswerResult;
thisAns.originalAnswerResult = null;
}
}
// search for any of the answers that lead to the duplicated question
if (thisAns.nextQuestionSequence === pq.questionSequence) {
// update either the nextQuestionSequence or the answerResult
if (matchedAnswer.nextQuestionSequence) {
thisAns.originalNextQuestionSequence = thisAns.nextQuestionSequence;
thisAns.nextQuestionSequence = matchedAnswer.nextQuestionSequence;
} else {
thisAns.originalNextQuestionSequence = thisAns.nextQuestionSequence;
thisAns.nextQuestionSequence = null;
thisAns.originalAnswerResult = thisAns.originalAnswerResult || thisAns.answerResult;
thisAns.answerResult = matchedAnswer.answerResult;
}
}
});
});
// suppress current question
thisAnsweredPartQuestion.suppressDuplicateQuestion = true;
const thisGlassPart = "glassPart" + i;
if (this.foundDuplicateQuestions[thisGlassPart]) {
if (!this.foundDuplicateQuestions[thisGlassPart].includes(thisAnsweredPartQuestion.questionSequence)) {
this.foundDuplicateQuestions[thisGlassPart].push(thisAnsweredPartQuestion.questionSequence);
}
} else {
this.foundDuplicateQuestions[thisGlassPart] = [thisAnsweredPartQuestion.questionSequence];
}
// are there any questions left that are not suppressed?
const remainingQuestions = glassPart.partQuestions.filter((q) => {
return !q.suppressDuplicateQuestion;
});
if (remainingQuestions.length < 1) {
// this is the final answer for this glass part
// mark this part as completely answered by adding answerData
const answeredQuestionObj = {
questionText: pq.questionText,
selectedAnswerText: matchedAnswer.answerText,
questionNum: pq.questionSequence,
isDuplicateQuestion: pq.suppressDuplicateQuestion,
};
// set the answerData as 'already answered'
glassPart.answerData = {
answerResult: matchedAnswer.nextQuestionSequence ? matchedAnswer.nextQuestionSequence : matchedAnswer.answerResult,
answeredQuestions: [answeredQuestionObj],
};
// suppress this glassPart because it has an answer
glassPart.isSuppressedPart = true;
}
} // END of if (matchedAnswer)
}
});
// Update the key to re-render this part's question-chain component
this.partsQuestionsData[i].key = this.partsQuestionsData[i].glassLocation + this.partsQuestionsData[i].glassName + Date.now().toString();
}
});
});
// look through all (this part's) part questions for any duplicates that were suppressed;
// add them to the list of answered questions if found
// EX answeredQuestionIndexes: [1,5,11,13]
// EX this.foundDuplicateQuestions = {
// "glassPart1": [1],
// "glassPart2": [7, 10]
// };
const thisPartsDupes = this.foundDuplicateQuestions["glassPart" + answer.partIndex];
thisPartsDupes?.forEach((dupe) => {
// dupe is a single integer
const dupeQuestion = glassPartWithAnswer.partQuestions[dupe - 1];
const dupeQuestionAnswer = dupeQuestion.answers.find((q) => q.selected === true);
glassPartWithAnswer.partQuestions.forEach((q) => {
let includeThisDupeInAnsweredQuestions = false;
// did one of the answers of this question point to the duplicated question?
q.answers.forEach((a) => {
if ((dupe === a.originalNextQuestionSequence) &&
(answeredQuestionIndexes.includes(q.questionSequence)) &&
(a.answerText.toUpperCase() === dupeQuestionAnswer.answerText.toUpperCase())) {
includeThisDupeInAnsweredQuestions = true;
}
});
// is this q.questionSequence listed as the duplicated question's nextQuestionSequence?
if ((q.questionSequence === dupeQuestionAnswer.nextQuestionSequence) && (answeredQuestionIndexes.includes(q.questionSequence))) {
includeThisDupeInAnsweredQuestions = true;
}
if (includeThisDupeInAnsweredQuestions) {
completeAnsweredQuestions.push({
questionNum: dupeQuestion.questionSequence,
questionText: dupeQuestion.questionText,
selectedAnswerText: dupeQuestionAnswer.answerText,
isDuplicateQuestion: dupeQuestion.suppressDuplicateQuestion,
});
}
});
});
// make sure there are no duplicated dupes in the list...
const foundInCompleteAnsweredQuestions = new Set();
let filteredCompleteAnsweredQuestions = completeAnsweredQuestions.filter(el => {
const duplicate = foundInCompleteAnsweredQuestions.has(el.questionText);
foundInCompleteAnsweredQuestions.add(el.questionText);
return !duplicate;
});
filteredCompleteAnsweredQuestions = filteredCompleteAnsweredQuestions.sort((a,b) => a.questionNum - b.questionNum);
// set final answer data for the current answered glass part
glassPartWithAnswer.answerData = {
answerResult: answer.answerResult,
answeredQuestions: filteredCompleteAnsweredQuestions,
}
// this part has been fully answered, so advance to next part's question chain
for (let i = answer.partIndex + 1; i < this.partsQuestionsData.length; i++) {
// if this part has not yet been fully answered, then make it the current part
if (!this.partsQuestionsData[i].answerData?.answerResult) {
this.currentPartNum = i;
break;
}
}
},
LoadInitialPartsData() {
// are there alreadyAnsweredQuestions?
const alreadyAnsweredQuestions = store.getters.damage.partQuestionAnswers;
this.partsQuestionsData = this.partsQuestionsFromApi.map((part, i) => {
part.key = part.glassLocation + "-" + part.glassName;
this.selectedAnswers[part.key] = [];
alreadyAnsweredQuestions?.forEach((savedPart) => {
if (!savedPart.glassLocation || !savedPart.glassName || !savedPart.answeredQuestions || !savedPart.result) {
return;
}
if (part.glassLocation === savedPart.glassLocation && part.glassName === savedPart.glassName) {
let answerString = "";
// matches; loop through answeredQuestions for matches
savedPart.answeredQuestions.forEach((aq) => {
if (!aq.questionNum || !aq.selectedAnswerText) {
return;
}
// determine which answer was previously chosen
const theAns = part.partQuestions[aq.questionNum-1].answers.find((a) => {
return a.answerText.toUpperCase() === aq.selectedAnswerText.toUpperCase();
});
if (theAns.nextQuestionSequence) {
answerString = `${aq.questionNum}|nextQuestion|${theAns.nextQuestionSequence}|${theAns.answerText}`
} else {
answerString = `${aq.questionNum}|answer|${theAns.answerResult}|${theAns.answerText}`
}
// mark this partQuestion as answered (question-chain will read this)
part.partQuestions[aq.questionNum-1].answerSelected = answerString;
// mark this partQuestion as duplicate if it is (question-chain will read this)
if (aq.isDuplicateQuestion) {
part.partQuestions[aq.questionNum-1].isDuplicateQuestion = true;
}
});
// advance the currentPartNum
this.currentPartNum = i;
// add answerData to current part
part.answerData = {
answerResult: savedPart.result,
answeredQuestions: savedPart.answeredQuestions
}
}
});
// Set up watch for each set of part questions, which gets updated when all questions for a part have been answered
this.$watch("selectedAnswers." + part.key, (newValue) => {
if (newValue) {
this.handleAnswerUpdates(part.key, newValue);
}
}, {deep: true})
return part;
});
},
},
components: {
funnelHeader,
vehicleBanner,
alert,
questionChain,
funnelSubHeader,
funnelFooter,
loadingModal,
Form,
},
};
</script>
<style lang="scss">
.part-questions {
.question-text {
margin-bottom: .5rem;
span {
text-align: left;
}
}
}
</style>