
/* /survey/static/src/js/survey_session_colors.js */
odoo.define('@survey/js/survey_session_colors',[],function(require){'use strict';let __exports={};__exports[Symbol.for("default")]=["31,119,180","255,127,14","174,199,232","255,187,120","44,160,44","152,223,138","214,39,40","255,152,150","148,103,189","197,176,213","140,86,75","196,156,148","227,119,194","247,182,210","127,127,127","199,199,199","188,189,34","219,219,141","23,190,207","158,218,229",];return __exports;});;

/* /survey/static/src/js/survey_session_chart.js */
odoo.define('@survey/js/survey_session_chart',['@web/core/assets','@web/legacy/js/public/public_widget','@survey/js/survey_session_colors'],function(require){'use strict';let __exports={};const{loadJS}=require("@web/core/assets");const publicWidget=require("@web/legacy/js/public/public_widget")[Symbol.for("default")];const SESSION_CHART_COLORS=require("@survey/js/survey_session_colors")[Symbol.for("default")];publicWidget.registry.SurveySessionChart=publicWidget.Widget.extend({init:function(parent,options){this._super.apply(this,arguments);this.questionType=options.questionType;this.answersValidity=options.answersValidity;this.hasCorrectAnswers=options.hasCorrectAnswers;this.questionStatistics=this._processQuestionStatistics(options.questionStatistics);this.showInputs=options.showInputs;this.showAnswers=false;},start:function(){var self=this;return this._super.apply(this,arguments).then(function(){self._setupChart();});},willStart:async function(){await loadJS("/survey/static/src/js/libs/chartjs-plugin-datalabels.js");},updateChart:function(questionStatistics,newAttendeesCount){if(questionStatistics){this.questionStatistics=this._processQuestionStatistics(questionStatistics);}
if(this.chart){var chartData=this.chart.data.datasets[0].data;for(var i=0;i<chartData.length;i++){var value=0;if(this.showInputs){value=this.questionStatistics[i].count;}
this.chart.data.datasets[0].data[i]=value;}
this.chart.update();}},setShowAnswers:function(showAnswers){this.showAnswers=showAnswers;},setShowInputs:function(showInputs){this.showInputs=showInputs;},_setupChart:function(){var $canvas=this.$('canvas');var ctx=$canvas.get(0).getContext('2d');this.chart=new Chart(ctx,this._buildChartConfiguration());},_buildChartConfiguration:function(){return{type:'bar',data:{labels:this._extractChartLabels(),datasets:[{backgroundColor:this._getBackgroundColor.bind(this),data:this._extractChartData(),}]},options:{maintainAspectRatio:false,plugins:{datalabels:{color:this._getLabelColor.bind(this),font:{size:'50',weight:'bold',},anchor:'end',align:'top',},legend:{display:false,},tooltip:{enabled:false,},},scales:{y:{ticks:{display:false,},grid:{display:false}},x:{ticks:{minRotation:20,maxRotation:90,font:{size:"35",weight:"bold"},color:'#212529',autoSkip:false,},grid:{drawOnChartArea:false,color:'rgba(0, 0, 0, 0.2)'}}},layout:{padding:{left:0,right:0,top:70,bottom:0}}},plugins:[ChartDataLabels,{beforeInit:function(chart){const nbrCol=chart.data.labels.length;const minRatio=0.4;const charPerLineBreakpoints=[[1,2,35,minRatio],[3,4,30,minRatio],[5,6,30,0.45],[7,8,30,0.65],[9,null,30,0.7],];let charPerLine;let fontRatio;charPerLineBreakpoints.forEach(([lowerBound,upperBound,value,ratio])=>{if(nbrCol>=lowerBound&&(upperBound===null||nbrCol<=upperBound)){charPerLine=value;fontRatio=ratio;}});if(charPerLine<35){const allWords=chart.data.labels.reduce((accumulator,words)=>accumulator.concat(' '.concat(words)));const maxWordLength=Math.max(...allWords.split(' ').map((word)=>word.length));fontRatio=maxWordLength>charPerLine?minRatio:fontRatio;chart.options.scales.x.ticks.font.size=Math.min(parseInt(chart.options.scales.x.ticks.font.size),chart.width*fontRatio/(nbrCol));}
chart.data.labels.forEach(function(label,index,labelsList){const words=label.split(" ");let resultLines=[];let currentLine=[];for(let i=0;i<words.length;i++){let word=words[i];while(word.length>charPerLine){resultLines.push(word.slice(0,charPerLine-1)+'-');word=word.slice(charPerLine-1);}
currentLine.push(word);const nextWord=i+1<words.length?words[i+1]:null;if(nextWord){const nextLength=currentLine.join(' ').length+nextWord.length;if(nextLength<=charPerLine){continue;}}
const newLabelLine=currentLine.join(' ');resultLines.push(newLabelLine);currentLine=[];}
labelsList[index]=resultLines;});},}],};},_extractChartLabels:function(){return this.questionStatistics.map(function(point){return point.text;});},_extractChartData:function(){return this.questionStatistics.map(function(){return 0;});},_getBackgroundColor:function(metaData){var opacity='0.8';if(this.showAnswers&&this.hasCorrectAnswers){if(!this._isValidAnswer(metaData.dataIndex)){opacity='0.2';}}
var rgb=SESSION_CHART_COLORS[metaData.dataIndex%SESSION_CHART_COLORS.length];return`rgba(${rgb},${opacity})`;},_getLabelColor:function(metaData){if(this.showAnswers&&this.hasCorrectAnswers){if(this._isValidAnswer(metaData.dataIndex)){return'#2CBB70';}else{return'#D9534F';}}
return'#212529';},_isValidAnswer:function(answerIndex){return this.answersValidity[answerIndex];},_processQuestionStatistics:function(rawStatistics){if(["multiple_choice","scale"].includes(this.questionType)){return rawStatistics[0].values;}
return rawStatistics;}});__exports[Symbol.for("default")]=publicWidget.registry.SurveySessionChart;return __exports;});;

/* /survey/static/src/js/survey_session_text_answers.js */
odoo.define('@survey/js/survey_session_text_answers',['@web/legacy/js/public/public_widget','@web/core/utils/render','@survey/js/survey_session_colors','@web/core/l10n/dates'],function(require){'use strict';let __exports={};const publicWidget=require("@web/legacy/js/public/public_widget")[Symbol.for("default")];const{renderToElement}=require("@web/core/utils/render");const SESSION_CHART_COLORS=require("@survey/js/survey_session_colors")[Symbol.for("default")];const{formatDate,formatDateTime}=require("@web/core/l10n/dates");const{DateTime}=luxon;publicWidget.registry.SurveySessionTextAnswers=publicWidget.Widget.extend({init:function(parent,options){this._super.apply(this,arguments);this.answerIds=[];this.questionType=options.questionType;},updateTextAnswers:function(inputLineValues){var self=this;inputLineValues.forEach(function(inputLineValue){if(!self.answerIds.includes(inputLineValue.id)&&inputLineValue.value){var textValue=inputLineValue.value;if(self.questionType==='char_box'){textValue=textValue.length>25?textValue.substring(0,22)+'...':textValue;}else if(self.questionType==='date'){textValue=formatDate(DateTime.fromFormat(textValue,"yyyy-MM-dd"));}else if(self.questionType==='datetime'){textValue=formatDateTime(DateTime.fromFormat(textValue,"yyyy-MM-dd HH:mm:ss"));}
var $textAnswer=$(renderToElement('survey.survey_session_text_answer',{value:textValue,borderColor:`rgb(${SESSION_CHART_COLORS[self.answerIds.length % 10]})`}));self.$el.append($textAnswer);var spanWidth=$textAnswer.find('span').width();var calculatedWidth=`calc(${spanWidth}px + 1.2rem)`;$textAnswer.css('width',calculatedWidth);setTimeout(function(){$textAnswer.find('.o_survey_session_text_answer_container').css('width',calculatedWidth).css('opacity','1');},1);self.answerIds.push(inputLineValue.id);}});},});__exports[Symbol.for("default")]=publicWidget.registry.SurveySessionTextAnswers;return __exports;});;

/* /survey/static/src/js/survey_session_leaderboard.js */
odoo.define('@survey/js/survey_session_leaderboard',['@web/core/network/rpc','@web/legacy/js/public/public_widget','@survey/js/survey_session_colors'],function(require){'use strict';let __exports={};const{rpc}=require("@web/core/network/rpc");const publicWidget=require("@web/legacy/js/public/public_widget")[Symbol.for("default")];const SESSION_CHART_COLORS=require("@survey/js/survey_session_colors")[Symbol.for("default")];publicWidget.registry.SurveySessionLeaderboard=publicWidget.Widget.extend({init:function(parent,options){this._super.apply(this,arguments);this.surveyAccessToken=options.surveyAccessToken;this.$sessionResults=options.sessionResults;this.BAR_MIN_WIDTH='3rem';this.BAR_WIDTH='24rem';this.BAR_HEIGHT='3.8rem';},showLeaderboard:function(fadeOut,isScoredQuestion){var self=this;var resolveFadeOut;var fadeOutPromise;if(fadeOut){fadeOutPromise=new Promise(function(resolve,reject){resolveFadeOut=resolve;});self.$sessionResults.fadeOut(400,function(){resolveFadeOut();});}else{fadeOutPromise=Promise.resolve();self.$sessionResults.hide();self.$('.o_survey_session_leaderboard_container').empty();}
var leaderboardPromise=rpc(`/survey/session/leaderboard/${this.surveyAccessToken}`);Promise.all([fadeOutPromise,leaderboardPromise]).then(function(results){var leaderboardResults=results[1];var $renderedTemplate=$(leaderboardResults);self.$('.o_survey_session_leaderboard_container').append($renderedTemplate);self.$('.o_survey_session_leaderboard_item').each(function(index){var rgb=SESSION_CHART_COLORS[index%10];$(this).find('.o_survey_session_leaderboard_bar').css('background-color',`rgba(${rgb},1)`);$(this).find('.o_survey_session_leaderboard_bar_question').css('background-color',`rgba(${rgb},${0.4})`);});self.$el.fadeIn(400,async function(){if(isScoredQuestion){await self._prepareScores();await self._showQuestionScores();await self._sumScores();await self._reorderScores();}});});},hideLeaderboard:function(){var self=this;this.$el.fadeOut(400,function(){self.$('.o_survey_session_leaderboard_container').empty();self.$sessionResults.fadeIn(400);});},_animateScoreCounter:function($scoreEl,currentScore,totalScore,increment,plusSign){var self=this;setTimeout(function(){var nextScore=currentScore+increment;if(nextScore>totalScore){nextScore=totalScore;}
$scoreEl.text(`${plusSign ? '+ ' : ''}${Math.round(nextScore)} p`);if(nextScore<totalScore){self._animateScoreCounter($scoreEl,nextScore,totalScore,increment,plusSign);}},25);},_animateMoveTo:function($score,position,offset,timeout){var animationDone;var animationPromise=new Promise(function(resolve){animationDone=resolve;});$score.css('top',`calc(calc(${this.BAR_HEIGHT} * ${position}) + ${offset}rem)`);setTimeout(animationDone,timeout);return animationPromise;},_prepareScores:function(){var self=this;var animationDone;var animationPromise=new Promise(function(resolve){animationDone=resolve;});setTimeout(function(){this.$('.o_survey_session_leaderboard_bar').each(function(){var currentScore=parseInt($(this).closest('.o_survey_session_leaderboard_item').data('currentScore'))
if(currentScore&&currentScore!==0){$(this).css('transition',`width 1s cubic-bezier(.4,0,.4,1)`);$(this).css('width',self.BAR_MIN_WIDTH);}});setTimeout(animationDone,1000);},300);return animationPromise;},_reorderScores:function(){var self=this;var animationDone;var animationPromise=new Promise(function(resolve){animationDone=resolve;});setTimeout(function(){self.$('.o_survey_session_leaderboard_item').each(async function(){var $score=$(this);var currentPosition=parseInt($(this).data('currentPosition'));var newPosition=parseInt($(this).data('newPosition'));if(currentPosition!==newPosition){var offset=newPosition>currentPosition?2:-2;await self._animateMoveTo($score,newPosition,offset,300);$score.css('transition','top ease-in-out .1s');await self._animateMoveTo($score,newPosition,offset*-0.3,100);await self._animateMoveTo($score,newPosition,0,0);animationDone();}});},1800);return animationPromise;},_showQuestionScores:function(){var self=this;var animationDone;var animationPromise=new Promise(function(resolve){animationDone=resolve;});setTimeout(function(){this.$('.o_survey_session_leaderboard_bar_question').each(function(){var $barEl=$(this);var width=`calc(calc(100% - ${self.BAR_WIDTH}) * ${$barEl.data('widthRatio')} + ${self.BAR_MIN_WIDTH})`;$barEl.css('transition','width 1s ease-out');$barEl.css('width',width);var $scoreEl=$barEl.find('.o_survey_session_leaderboard_bar_question_score').text('0 p');var questionScore=parseInt($barEl.data('questionScore'));if(questionScore&&questionScore>0){var increment=parseInt($barEl.data('maxQuestionScore')/40);if(!increment||increment===0){increment=1;}
$scoreEl.text('+ 0 p');console.log($barEl.data('maxQuestionScore'));setTimeout(function(){self._animateScoreCounter($scoreEl,0,questionScore,increment,true);},400);}
setTimeout(animationDone,1400);});},300);return animationPromise;},_sumScores:function(){var self=this;var animationDone;var animationPromise=new Promise(function(resolve){animationDone=resolve;});var growthAnimation='cubic-bezier(.5,0,.66,1.11)';setTimeout(function(){this.$('.o_survey_session_leaderboard_item').each(function(){var currentScore=parseInt($(this).data('currentScore'));var updatedScore=parseInt($(this).data('updatedScore'));var increment=parseInt($(this).data('maxQuestionScore')/40);if(!increment||increment===0){increment=1;}
self._animateScoreCounter($(this).find('.o_survey_session_leaderboard_score'),currentScore,updatedScore,increment,false);var maxUpdatedScore=parseInt($(this).data('maxUpdatedScore'));var baseRatio=maxUpdatedScore?updatedScore/maxUpdatedScore:1;var questionScore=parseInt($(this).data('questionScore'));var questionRatio=questionScore/(updatedScore&&updatedScore!==0?updatedScore:1);var questionWith=`calc(calc(calc(100% - ${self.BAR_WIDTH}) * ${questionRatio * baseRatio}) + ${self.BAR_MIN_WIDTH})`;$(this).find('.o_survey_session_leaderboard_bar_question').css('transition',`width ease .5s ${growthAnimation}`).css('width',questionWith);var updatedScoreRatio=1-questionRatio;var updatedScoreWidth=`calc(calc(100% - ${self.BAR_WIDTH}) * ${updatedScoreRatio * baseRatio})`;$(this).find('.o_survey_session_leaderboard_bar').css('min-width','0px').css('transition',`width ease .5s ${growthAnimation}`).css('width',updatedScoreWidth);setTimeout(animationDone,500);});},1400);return animationPromise;}});__exports[Symbol.for("default")]=publicWidget.registry.SurveySessionLeaderboard;return __exports;});;

/* /survey/static/src/js/survey_session_manage.js */
odoo.define('@survey/js/survey_session_manage',['@web/legacy/js/public/public_widget','@survey/js/survey_preload_image_mixin','@survey/js/survey_session_chart','@survey/js/survey_session_text_answers','@survey/js/survey_session_leaderboard','@web/core/l10n/translation','@web/core/network/rpc','@web/core/browser/browser'],function(require){'use strict';let __exports={};const publicWidget=require("@web/legacy/js/public/public_widget")[Symbol.for("default")];const SurveyPreloadImageMixin=require("@survey/js/survey_preload_image_mixin")[Symbol.for("default")];const SurveySessionChart=require("@survey/js/survey_session_chart")[Symbol.for("default")];const SurveySessionTextAnswers=require("@survey/js/survey_session_text_answers")[Symbol.for("default")];const SurveySessionLeaderBoard=require("@survey/js/survey_session_leaderboard")[Symbol.for("default")];const{_t}=require("@web/core/l10n/translation");const{rpc}=require("@web/core/network/rpc");const{browser}=require("@web/core/browser/browser");const nextPageTooltips={closingWords:_t('End of Survey'),leaderboard:_t('Show Leaderboard'),leaderboardFinal:_t('Show Final Leaderboard'),nextQuestion:_t('Next'),results:_t('Show Correct Answer(s)'),startScreen:_t('Start'),userInputs:_t('Show Results'),};publicWidget.registry.SurveySessionManage=publicWidget.Widget.extend(SurveyPreloadImageMixin,{selector:'.o_survey_session_manage',events:{'click .o_survey_session_copy':'_onCopySessionLink','click .o_survey_session_navigation_next, .o_survey_session_start':'_onNext','click .o_survey_session_navigation_previous':'_onBack','click .o_survey_session_close':'_onEndSessionClick',},init(){this._super(...arguments);this.orm=this.bindService("orm");},start:function(){var self=this;this.fadeInOutTime=500;return this._super.apply(this,arguments).then(function(){if(self.$el.data('isSessionClosed')){self._displaySessionClosedPage();self.$el.removeClass('invisible');return;}
self.surveyId=self.$el.data('surveyId');self.surveyHasConditionalQuestions=self.$el.data('surveyHasConditionalQuestions');self.surveyAccessToken=self.$el.data('surveyAccessToken');self.isStartScreen=self.$el.data('isStartScreen');self.isFirstQuestion=self.$el.data('isFirstQuestion');self.isLastQuestion=self.$el.data('isLastQuestion');self.isScoredQuestion=self.$el.data('isScoredQuestion');self.sessionShowLeaderboard=self.$el.data('sessionShowLeaderboard');self.hasCorrectAnswers=self.$el.data('hasCorrectAnswers');self.showBarChart=self.$el.data('showBarChart');self.showTextAnswers=self.$el.data('showTextAnswers');self.stopNextQuestion=false;self.refreshBackground=self.$el.data('refreshBackground');self.$('.o_survey_session_copy').tooltip({delay:0,title:'Click to copy link',placement:'right'});var isRpcCall=self.$el.data('isRpcCall');if(!isRpcCall){self._startTimer();$(document).on('keydown',self._onKeyDown.bind(self));}
self._setupIntervals();self._setupCurrentScreen();var setupPromises=[];setupPromises.push(self._setupTextAnswers());setupPromises.push(self._setupChart());setupPromises.push(self._setupLeaderboard());self.$el.removeClass('invisible');return Promise.all(setupPromises);});},_onCopySessionLink:async function(ev){ev.preventDefault();var $clipboardBtn=this.$('.o_survey_session_copy');$clipboardBtn.tooltip('dispose');$clipboardBtn.popover({placement:'right',container:'body',offset:'0, 3',content:function(){return _t("Copied!");}});await browser.navigator.clipboard.writeText(this.target.querySelector('.o_survey_session_copy_url').textContent);$clipboardBtn.popover('show');setTimeout(()=>$clipboardBtn.popover('dispose'),800);},_onKeyDown:function(ev){if(ev.key==="ArrowRight"||ev.key===" "){this._onNext(ev);}else if(ev.key==="ArrowLeft"){this._onBack(ev);}},_onNext:function(ev){ev.preventDefault();var screenToDisplay=this._getNextScreen();if(screenToDisplay==='userInputs'){this._setShowInputs(true);}else if(screenToDisplay==='results'){this._setShowAnswers(true);clearInterval(this.resultsRefreshInterval);delete this.resultsRefreshInterval;}else if(['leaderboard','leaderboardFinal'].includes(screenToDisplay)&&!['leaderboard','leaderboardFinal'].includes(this.currentScreen)){if(this.isLastQuestion){this.$('.o_survey_session_navigation_next').addClass('d-none');}
this.leaderBoard.showLeaderboard(true,this.isScoredQuestion);}else if(!this.isLastQuestion||!this.sessionShowLeaderboard){this._nextQuestion();}
this.currentScreen=screenToDisplay;if(!['question','nextQuestion'].includes(screenToDisplay)){this._updateNextScreenTooltip();}},_onBack:function(ev){ev.preventDefault();var screenToDisplay=this._getPreviousScreen();if(screenToDisplay==='question'){this._setShowInputs(false);}else if(screenToDisplay==='userInputs'){this._setShowAnswers(false);if(!this.resultsRefreshInterval){this.resultsRefreshInterval=setInterval(this._refreshResults.bind(this),2000);}}else if(screenToDisplay==='results'){if(this.leaderBoard){this.leaderBoard.hideLeaderboard();}
clearInterval(this.resultsRefreshInterval);delete this.resultsRefreshInterval;}else if(screenToDisplay==='previousQuestion'){if(this.isFirstQuestion){return;}
this._nextQuestion(true);}
this.currentScreen=screenToDisplay;if(!['question','nextQuestion'].includes(screenToDisplay)){this._updateNextScreenTooltip();}},_onEndSessionClick:function(ev){var self=this;ev.preventDefault();this.orm.call("survey.survey","action_end_session",[[this.surveyId]]).then(function(){if($(ev.currentTarget).data('showResults')){document.location=`/survey/results/${encodeURIComponent(self.surveyId)}`;}else{document.location.reload();}});},_getNextScreen:function(){if(this.currentScreen==='question'&&this.isScoredQuestion){return'userInputs';}else if(this.hasCorrectAnswers&&['question','userInputs'].includes(this.currentScreen)){return'results';}else if(this.sessionShowLeaderboard){if(['question','userInputs','results'].includes(this.currentScreen)&&this.isScoredQuestion){return'leaderboard';}else if(this.isLastQuestion){return'leaderboardFinal';}}
return'nextQuestion';},_getPreviousScreen:function(){if(this.currentScreen==='userInputs'&&this.isScoredQuestion){return'question';}else if((this.currentScreen==='results'&&this.isScoredQuestion)||(this.currentScreen==='leaderboard'&&!this.isScoredQuestion)||(this.currentScreen==='leaderboardFinal'&&this.isScoredQuestion)){return'userInputs';}else if((this.currentScreen==='leaderboard'&&this.isScoredQuestion)||(this.currentScreen==='leaderboardFinal'&&!this.isScoredQuestion)){return'results';}
return'previousQuestion';},_nextQuestion:function(goBack){var self=this;if(this.stopNextQuestion){return;}
this.stopNextQuestion=true;this.isStartScreen=false;if(this.surveyTimerWidget){this.surveyTimerWidget.destroy();}
var resolveFadeOut;var fadeOutPromise=new Promise(function(resolve,reject){resolveFadeOut=resolve;});this.$el.fadeOut(this.fadeInOutTime,function(){resolveFadeOut();});if(this.refreshBackground){$('div.o_survey_background').addClass('o_survey_background_transition');}
if(this.resultsRefreshInterval){clearInterval(this.resultsRefreshInterval);delete this.resultsRefreshInterval;}
var nextQuestionPromise=rpc(`/survey/session/next_question/${self.surveyAccessToken}`,{'go_back':goBack,}).then(function(result){self.nextQuestion=result;if(self.refreshBackground&&result.background_image_url){return self._preloadBackground(result.background_image_url);}else{return Promise.resolve();}});Promise.all([fadeOutPromise,nextQuestionPromise]).then(function(){return self._onNextQuestionDone(goBack);});},_displaySessionClosedPage:function(){this.$('.o_survey_question_header').addClass('invisible');this.$('.o_survey_session_results, .o_survey_session_navigation_previous, .o_survey_session_navigation_next').addClass('d-none');this.$('.o_survey_session_description_done').removeClass('d-none');},_onNextQuestionDone:async function(goBack){var self=this;if(this.nextQuestion.question_html){var $renderedTemplate=$(this.nextQuestion.question_html);this.$el.replaceWith($renderedTemplate);await this.attachTo($renderedTemplate);if(goBack){this._setShowInputs(true);this._setShowAnswers(true);if(this.sessionShowLeaderboard&&this.isScoredQuestion){this.currentScreen='leaderboard';this.leaderBoard.showLeaderboard(false,this.isScoredQuestion);}else{this.currentScreen='results';this._refreshResults();}}else{this._startTimer();}
this.$el.fadeIn(this.fadeInOutTime);}else if(this.sessionShowLeaderboard){this.isLastQuestion=true;this._setupLeaderboard().then(function(){self.$('.o_survey_session_leaderboard_title').text(_t('Final Leaderboard'));self.$('.o_survey_session_navigation_next').addClass('d-none');self.$('.o_survey_leaderboard_buttons').removeClass('d-none');self.leaderBoard.showLeaderboard(false,false);});}else{self.$('.o_survey_session_close').first().click();self._displaySessionClosedPage();}
if(this.refreshBackground){$('div.o_survey_background').css("background-image","url("+this.nextQuestion.background_image_url+")");$('div.o_survey_background').removeClass('o_survey_background_transition');}},_startTimer:function(){var self=this;var $timer=this.$('.o_survey_timer');if($timer.length){var timeLimitMinutes=this.$el.data('timeLimitMinutes');var timer=this.$el.data('timer');this.surveyTimerWidget=new publicWidget.registry.SurveyTimerWidget(this,{'timer':timer,'timeLimitMinutes':timeLimitMinutes});this.surveyTimerWidget.attachTo($timer);this.surveyTimerWidget.on('time_up',this,function(){if(self.currentScreen==='question'&&this.isScoredQuestion){self.$('.o_survey_session_navigation_next').click();}});}},_refreshResults:function(){var self=this;return rpc(`/survey/session/results/${self.surveyAccessToken}`).then(function(questionResults){if(questionResults){self.attendeesCount=questionResults.attendees_count;if(self.resultsChart&&questionResults.question_statistics_graph){self.resultsChart.updateChart(JSON.parse(questionResults.question_statistics_graph));}else if(self.textAnswers){self.textAnswers.updateTextAnswers(questionResults.input_line_values);}
var max=self.attendeesCount>0?self.attendeesCount:1;var percentage=Math.min(Math.round((questionResults.answer_count/max)*100),100);self.$('.progress-bar').css('width',`${percentage}%`);if(self.attendeesCount&&self.attendeesCount>0){var answerCount=Math.min(questionResults.answer_count,self.attendeesCount);self.$('.o_survey_session_answer_count').text(answerCount);self.$('.progress-bar.o_survey_session_progress_small span').text(`${answerCount} / ${self.attendeesCount}`);}}
return Promise.resolve();},function(){clearInterval(self.resultsRefreshInterval);delete self.resultsRefreshInterval;});},_refreshAttendeesCount:function(){var self=this;return self.orm.read("survey.survey",[self.surveyId],['session_answer_count'],).then(function(result){if(result&&result.length===1){self.$('.o_survey_session_attendees_count').text(result[0].session_answer_count);}},function(err){clearInterval(self.attendeesRefreshInterval);console.error(err);});},_setupChart:function(){if(this.resultsChart){this.resultsChart.setElement(null);this.resultsChart.destroy();delete this.resultsChart;}
if(!this.isStartScreen&&this.showBarChart){this.resultsChart=new SurveySessionChart(this,{questionType:this.$el.data('questionType'),answersValidity:this.$el.data('answersValidity'),hasCorrectAnswers:this.hasCorrectAnswers,questionStatistics:this.$el.data('questionStatistics'),showInputs:this.showInputs});return this.resultsChart.attachTo(this.$('.o_survey_session_chart'));}else{return Promise.resolve();}},_setupLeaderboard:function(){if(this.leaderBoard){this.leaderBoard.setElement(null);this.leaderBoard.destroy();delete this.leaderBoard;}
if(this.isScoredQuestion||this.isLastQuestion){this.leaderBoard=new SurveySessionLeaderBoard(this,{surveyAccessToken:this.surveyAccessToken,sessionResults:this.$('.o_survey_session_results')});return this.leaderBoard.attachTo(this.$('.o_survey_session_leaderboard'));}else{return Promise.resolve();}},_setupTextAnswers:function(){if(this.textAnswers){this.textAnswers.setElement(null);this.textAnswers.destroy();delete this.textAnswers;}
if(!this.isStartScreen&&this.showTextAnswers){this.textAnswers=new SurveySessionTextAnswers(this,{questionType:this.$el.data('questionType')});return this.textAnswers.attachTo(this.$('.o_survey_session_text_answers_container'));}else{return Promise.resolve();}},_setupIntervals:function(){this.attendeesCount=this.$el.data('attendeesCount')?this.$el.data('attendeesCount'):0;if(this.isStartScreen){this.attendeesRefreshInterval=setInterval(this._refreshAttendeesCount.bind(this),2000);}else{if(this.attendeesRefreshInterval){clearInterval(this.attendeesRefreshInterval);}
if(!this.resultsRefreshInterval){this.resultsRefreshInterval=setInterval(this._refreshResults.bind(this),2000);}}},_setupCurrentScreen:function(){if(this.isStartScreen){this.currentScreen='startScreen';}else if(!this.isScoredQuestion&&this.showBarChart){this.currentScreen='userInputs';}else{this.currentScreen='question';}
this.$('.o_survey_session_navigation_previous').toggleClass('d-none',!!this.isFirstQuestion);this._setShowInputs(this.currentScreen==='userInputs');this._updateNextScreenTooltip();},_setShowInputs(showInputs){this.showInputs=showInputs;if(this.resultsChart){this.resultsChart.setShowInputs(showInputs);this.resultsChart.updateChart();}},_setShowAnswers(showAnswers){this.showAnswers=showAnswers;if(this.resultsChart){this.resultsChart.setShowAnswers(showAnswers);this.resultsChart.updateChart();}},_updateNextScreenTooltip(){let tooltip;if(this.currentScreen==='startScreen'){tooltip=nextPageTooltips['startScreen'];}else if(this.isLastQuestion&&!this.surveyHasConditionalQuestions&&!this.isScoredQuestion&&!this.sessionShowLeaderboard){tooltip=nextPageTooltips['closingWords'];}else{const nextScreen=this._getNextScreen();if(nextScreen==='nextQuestion'||this.surveyHasConditionalQuestions){tooltip=nextPageTooltips['nextQuestion'];}
tooltip=nextPageTooltips[nextScreen];}
const sessionNavigationNextEl=this.el.querySelector('.o_survey_session_navigation_next_label');if(sessionNavigationNextEl&&tooltip){sessionNavigationNextEl.textContent=tooltip;}}});__exports[Symbol.for("default")]=publicWidget.registry.SurveySessionManage;return __exports;});

                    /*******************************************
                    *  Templates                               *
                    *******************************************/

                    odoo.define("survey.survey_user_input_session_assets.bundle.xml", ["@web/core/templates"], function(require) {
                        "use strict";
                        const { checkPrimaryTemplateParents, registerTemplate, registerTemplateExtension } = require("@web/core/templates");
                        /* survey.survey_user_input_session_assets */
                        registerTemplate("survey.survey_session_text_answer", `/survey/static/src/xml/survey_session_text_answer_template.xml`, `<div t-name="survey.survey_session_text_answer" class="o_survey_session_text_answer d-inline-block m-1" xml:space="preserve">
    <div class="o_survey_session_text_answer_container d-inline-block p-2 fw-bold" t-attf-style="border-color: #{borderColor}">
        <span class="d-inline-block" t-esc="value"/>
    </div>
</div>

`);
                    });
