1"use strict";(self.webpackChunkblocksurvey=self.webpackChunkblocksurvey||[]).push([[2594],{84092(K,L,m){m.d(L,{q:()=>u});var v=m(10467),I=m(84412),B=m(54843),P=m(7673),D=m(99437),T=m(96354),C=m(88141),_=m(95095),O=m(49072),A=m(60414),M=m(76417),R=m(45224),E=m(61941),U=m(49797),l=m(39049);let u=(()=>{class y{isReportPasswordValidated(e){return!(!e||!this.reportPasswordValidation[e])}markReportPasswordValidated(e,r=!0){if(e){if(r)return void(this.reportPasswordValidation[e]=!0);delete this.reportPasswordValidation[e]}}resetReportPasswordValidation(e){e?delete this.reportPasswordValidation[e]:this.reportPasswordValidation={}}clearSurveyGoalsCache(e,r){if(!e)return void this.surveyGoalsCache.clear();const t=this.getSurveyGoalsCacheKey(r||"personal",e);this.surveyGoalsCache.delete(t)}fetchSurveyGoals(e,r){var t=this;return(0,v.A)(function*(s,i,a={}){if(!i)return{goals:[],actionItems:[]};const n=s||"personal",o=t.getSurveyGoalsCacheKey(n,i,a.analysisType);if(!a.forceRefresh&&t.isSurveyGoalsCacheValid(o)){const S=t.surveyGoalsCache.get(o);if(S?.data)return t.cloneSurveyGoalsResponse(S.data)}const{userId:h,userKey:d}=yield t.waitForUserCredentials(),p={stacksId:h,stacksKey:d,teamId:n},k={userId:h,key:d,teamId:n,surveyId:i,regenerateMode:a.regenerateMode||"goals"};a.analysisType&&(k.analysisType=a.analysisType),a.surveyObjSnapshot&&(k.surveyObj=a.surveyObjSnapshot),k.goals=Array.isArray(a.goalsOverride)?a.goalsOverride.map(S=>t.normalizeGoalForApi(S)):[];try{const S=`${_.Y.AI_DATA_ANALYSIS_API_SVC_URL}/ai-survey-analysis/survey-goals`,g=yield(0,B._)(t.restService.postWithHeader(S,k,{headers:p})),x=t.normalizeSurveyGoalsResponse(g);return t.updateSurveyGoalsCache(o,x),t.cloneSurveyGoalsResponse(x)}catch(S){console.error("Failed to fetch survey goals:",S);const g=t.surveyGoalsCache.get(o);if(g?.data)return t.cloneSurveyGoalsResponse(g.data);throw S}}).apply(this,arguments)}getSurveyGoalsCacheKey(e,r,t){const s=`${e||"personal"}-${r}`;return t?`${s}-${t}`:s}isSurveyGoalsCacheValid(e){const r=this.surveyGoalsCache.get(e);return!!r&&Date.now()-r.timestamp<this.GOAL_CACHE_TTL}updateSurveyGoalsCache(e,r){this.surveyGoalsCache.set(e,{timestamp:Date.now(),data:this.cloneSurveyGoalsResponse(r)})}cloneSurveyGoalsResponse(e){return{goals:Array.isArray(e?.goals)?e.goals.map(r=>({...r})):[],actionItems:Array.isArray(e?.actionItems)?e.actionItems.map(r=>({...r})):[],generatedAt:e?.generatedAt,metadata:e?.metadata?{...e.metadata}:void 0}}normalizeSurveyGoalsResponse(e){if(!e||"object"!=typeof e)return{goals:[],actionItems:[]};const r=Array.isArray(e.goals)?e.goals:e.goalCandidates||[],t=Array.isArray(e.actionItems)?e.actionItems:e.suggestedActions||[];return{goals:r.map((s,i)=>this.normalizeGoalFromApi(s,i)),actionItems:t.map((s,i)=>this.normalizeActionItemFromApi(s,i)),generatedAt:e.generatedAt||e.generated_at,metadata:e.metadata||void 0}}normalizeGoalFromApi(e,r){(!e||"object"!=typeof e)&&(e={});const t=e.title||e.summary||e.text||e.goal||"";return{id:e.id||e.goalId||`goal-${r+1}`,title:"string"==typeof t?t:"",description:"string"==typeof e.description?e.description:void 0,source:e.source||e.origin||e.reason||void 0,confidence:this.normalizeConfidence(e.confidence),priority:e.priority,category:e.category,metadata:e.metadata||e.meta||void 0,goalType:e.goalType||e.type||void 0,createdAt:e.createdAt||e.created_at,updatedAt:e.updatedAt||e.updated_at,draft:e.draft}}normalizeActionItemFromApi(e,r){(!e||"object"!=typeof e)&&(e={});const t=e.description||e.summary||e.text||e.recommendation||"";return{id:e.id||e.actionId||`action-${r+1}`,goalId:e.goalId||e.goal_id,title:e.title||e.summaryTitle||void 0,description:"string"==typeof t?t:"",source:e.source||e.origin||void 0,confidence:this.normalizeConfidence(e.confidence),priority:e.priority,metadata:e.metadata||e.meta||void 0,actionType:e.actionType||e.type||void 0,createdAt:e.createdAt||e.created_at,updatedAt:e.updatedAt||e.updated_at,draft:e.draft}}normalizeConfidence(e){if(null!=e){if("number"==typeof e&&!isNaN(e))return e>1?Math.min(e/100,1):Math.max(Math.min(e,1),0);if("string"==typeof e){const r=parseFloat(e);
1if(!isNaN(r))return this.normalizeConfidence(r)}}}normalizeGoalForApi(e){return e?{id:e.id,title:e.title,description:e.description,source:e.source,confidence:this.normalizeConfidence(e.confidence),priority:e.priority,category:e.category,metadata:e.metadata,goalType:e.goalType}:{id:`goal-${Date.now()}`,title:""}}waitForUserCredentials(){return new Promise((e,r)=>{const t=Date.now(),i=()=>{const a=this.blockstackService.userBlockStackProfile?.username,n=this.blockstackService.userBlockSurveyProfile?.key;a&&n?e({userId:a,userKey:n}):Date.now()-t>6e3?r(new Error("User credentials not available")):setTimeout(i,200)};i()})}constructor(e,r,t,s,i){this.blockstackService=e,this.restService=r,this.intercomService=t,this.utilService=s,this.activationSignalsService=i,this.analysisTypes=[{id:"statistics",name:"Statistics",prompt:"Please analyze the provided dataset to calculate the Positive Sentiment Percentage using the TextBlob library. The dataset may includes both text and numerical data. For each text entry, determine the polarity score using TextBlob. Positive sentiment is indicated by a positive polarity score (greater than 0). Classify each text entry as 'Positive', 'Neutral', or 'Negative' based on its polarity score. Calculate the proportion of text entries that have a positive sentiment to determine the Positive Sentiment Percentage. Additionally, integrate the analysis of numerical data to provide further insights, such as computing descriptive statistics and identifying correlations between numerical features and sentiment classifications. The final output should include the original text, its polarity score, sentiment classification, the Positive Sentiment Percentage, and relevant numerical data insights.",output:'{\n "positiveSentimentPercentage": 0\n}',processMsg:"Calculating detailed statistics from the survey..."},{id:"topInsights",name:"Top Insights",prompt:"Extract top three insights by analyzing the given dataset to find the most significant patterns, trends, and relationships using advanced data analysis techniques, including machine learning algorithms. Just give insights with more details, do not suggest further action and summary.",output:'{\n "insights": [\n // List of insights and more detailed description with minimum four lines. \n {\n "title": "",\n "description": ""\n }\n ]\n }',processMsg:"Identifying the top insights from your data..."},{id:"thematicAnalysis",name:"Thematic Analysis",prompt:"Give me top themes or patterns from the given dataset. Perform a Thematic analysis is a qualitative research method used to identify, analyze, and report patterns or themes within data.",output:'{\n "themes": [\n // List of themes with title and more detailed description.\n {\n "title": "",\n "description": ""\n }\n ]\n}',processMsg:"Conducting thematic analysis to uncover common themes..."},{id:"anomalyDetection",name:"Anomaly Detection",prompt:"Perform anomaly detection analysis to identify unusual patterns in text data. By leveraging machine learning algorithms and statistical methods, we can detect anomalies and uncover hidden insights in both types of data. With the ability to identify anomalies in textual information, we can enhance text analysis, detect fraud, and optimize business processes. Similarly, by applying anomaly detection techniques to numeric data, we can improve predictive modeling, detect anomalies, and uncover hidden patterns. This comprehensive approach allows us to make data-driven decisions based on both text and numeric data.",output:'{\n "anomalies": [\n // List of anomalies which are Unusual and Unexpected responses\n {\n "title": "",\n "description": ""\n }\n ]\n }',processMsg:"Detecting anomalies in the data..."},{id:"personaAnalysis",name:"Persona Analysis",prompt:"Identify only the different type of personas in the given dataset, if applicable. These personas should help us to understand the varied customer needs, behaviors, and motivations by embodying the characteristics of different user types",output:'{\n "personas": [\n // List of personas with title and more detailed description\n {\n "title": "",\n "description": ""\n }\n ]\n }',processMsg:"Creating detailed personas based on the survey responses..."},{id:"emotionAnalytics",name:"Sentiment Analysis",prompt:"Find out 'Frustration' and 'Excitement' emotion on the given dataset. Use natural language processing (NLP) tools to categorize the emotions expressed in each textual response and use better tools for other type of columns.",output:'{\n "frustration": [\n // List of frustrations with title and more detailed description.\n {\n "title": "",\n "description": "",\n "question": ""\n }\n ],\n "excitement": [\n // list of excitement with title and description.\n {\n "title": "",\n "description": "",\n "question": ""\n\n }\n ]\n }',processMsg:"Capturing the emotional pulse..."},{id:"fatigueAnalysis",name:"Fatigue Analysis",prompt:"Perform a Fatigue Analysis in the context of survey responses refers to the phenomenon where the quality and reliability of responses deteriorate as respondents progress through the survey. This can occur due to the length of the survey, the complexity of questions, or simply respondent boredom or loss of interest. Let us perform a Fatigue Analysis and find the solution",output:'{\n "fatigue": [\n // List of questions and more detailed tip\n {\n "question": "",\n "tip": ""\n }\n ]\n }',processMsg:"Analyzing response patterns for signs of fatigue..."},{id:"actionItems",name:"Action Items",processMsg:"Generating action items from the survey..."}],this.surveyAnalysisListCache=new Map,this.analysisReportCache=new Map,this.CACHE_TTL=18e5,this.cacheTimestamps=new Map,this.GOAL_CACHE_TTL=3e5,this.surveyGoalsCache=new Map,this.reportPasswordValidation={},this.analysisToBeDone=[],this.processTypeMsg={},this.processStatus={}}fetchAiDataAnalysisReport(e,r){var t=this;return new Promise(function(){var s=(0,v.A)(function*(i,a){let n=setInterval(()=>{t.blockstackService.userBlockStackProfile&&t.blockstackService.userBlockStackProfile.username&&t.blockstackService.userBlockSurveyProfile&&t.blockstackService.userBlockSurveyProfile.key&&(n&&clearInterval(n),"default"==e?t.restService.get("https://static-files.blocksurvey.io/demo_ai_data_analyisis_report.json").subscribe({next:o=>{o&&i({data:o})},error:o=>{console.error(o),a(o)}}):t.restService.getWithHeader(_.Y.AI_DATA_ANALYSIS_API_SVC_URL+"/get-report?report_id="+e,{headers:{stacksId:t.blockstackService.userBlockStackProfile?.username,stacksKey:t.blockstackService.userBlockSurveyProfile?.key,teamId:r||""}}).subscribe({next:c=>{c&&i(c)},error:c=>{console.error(c),a(c)}}))},300)});return function(i,a){return s.apply(this,arguments)}}())}fetchAiSurveyAnalysisReport(e,r){var t=this;return new Promise(function(){var s=(0,v.A)(function*(i,a){let n=setInterval(()=>{t.blockstackService.userBlockStackProfile&&t.blockstackService.userBlockStackProfile.username&&t.blockstackService.userBlockSurveyProfile&&t.blockstackService.userBlockSurveyProfile.key&&(n&&clearInterval(n),t.restService.getWithHeader(_.Y.AI_DATA_ANALYSIS_API_SVC_URL+"/ai-survey-analysis/get-report?report_id="+e,{headers:{stacksId:t.blockstackService.userBlockStackProfile?.username,stacksKey:t.blockstackService.userBlockSurveyProfile?.key,teamId:r||""}}).subscribe({next:c=>{c&&i(c)},error:c=>{console.error(c),a(c)}}))},300)});return function(i,a){return s.apply(this,arguments)}}())}fetchAiDataAnalysisReports(e,r){var t=this;return new Promise(function(){var s=(0,v.A)(function*(i,a){let n=setInterval(()=>{t.blockstackService.userBlockStackProfile&&t.blockstackService.userBlockStackProfile.username&&t.blockstackService.userBlockSurveyProfile&&t.blockstackService.userBlockSurveyProfile.key&&(n&&clearInterval(n),t.restService.getWithHeader(_.Y.AI_DATA_ANALYSIS_API_SVC_URL+"/get-reports",{headers:{stacksId:t.blockstackService.userBlockStackProfile?.username,stacksKey:t.blockstackService.userBlockSurveyProfile?.key,teamId:e||"",owner:r||""}}).subscribe({next:c=>{c&&i(c)},error:c=>{console.error(c),a(c)}}))},300)});return function(i,a){return s.apply(this,arguments)}}())}fetchAiDataAnalysisReportsForSurvey(e,r){return new Promise((t,s)=>{if(!r)return void t({status:"success",aiSurveyAnalysis:[]});const i=setInterval(()=>{const a=this.blockstackService.userBlockStackProfile?.username,n=this.blockstackService.userBlockSurveyProfile?.key;if(!a||!n)return;clearInterval(i);const o=e||"personal";this.restService.postWithHeader(`${_.Y.AI_DATA_ANALYSIS_API_SVC_URL}/ai-survey-analysis/get-survey-analysis`,{userId:a,key:n,teamId:o,surveyId:r},{headers:{stacksId:a,stacksKey:n,teamId:o}}).subscribe({next:d=>t(d),error:d=>{console.error(d),s(d)}})},300)})}extractQuantitativeData(e,r){if(!e||!r?.questions)return[];const t=[];return r.questions.forEach(s=>{if(!s?.id)return;const a=e[s.id];if(!a)return;const n=this.getCleanQuestionLabel(s),o=(s.type||s.bType||"").toString().toLowerCase(),c=(s.bType||s.type||"").toString().toLowerCase();if(this.isQualitativeQuestion(o,c))return;const h=s.bType||s.type||"",p=O.d.TYPES_AS_OBJECT[h]?.value||h;let k=null;
1this.isMatrixType(o,c)?k=this.extractMatrixData(a,s):this.isChoiceBasedType(o,c)?k=this.extractChoiceData(a,s):this.isRatingScaleType(o,c)?k=this.extractScaleData(a,s):this.isNumericType(o,c)&&(k=this.extractNumericData(a,s)),k&&Object.keys(k).length>0&&t.push({question:n,type:p,answer:k})}),t}getCleanQuestionLabel(e){return(e?.label||e?.title||e?.question||"Question").replace(/<[^>]*>/g,"").trim()}isQualitativeQuestion(e,r){const t=["singletextbox","commentbox","email","website","phonenumber","country","statement","fileupload","imagecapture","signature","contactform","list","questiongroup","twittersocial","discordsocial","githubsocial","googlesocial","linkedinsocial","outlooksocial","redditsocial","farcastersocial","tiktoksocial","stacksnetwork","solananetwork","ethereumnetwork","bitcoinnetwork","polygonnetwork","avalanchenetwork","bnbnetwork","celonetwork","gnosisnetwork"];return t.includes(e)||t.includes(r)}isMatrixType(e,r){return e.startsWith("matrix")||["matrixrating","matrixratingmultiple","matrixtext","matrixnumber","matrixdropdown","matrixstarrating"].includes(r)}isChoiceBasedType(e,r){const t=["multiplechoice","checkboxes","dropdown","dropdownmultiple","consent","ranking","colorpicker","maxdiff","conjoint","bipolar"];return t.includes(e)||t.includes(r)}isRatingScaleType(e,r){const t=["numberrating","slider","starrating","customerexperience"];return t.includes(e)||t.includes(r)}isNumericType(e,r){const t=["number","multiplenumber","vanwestendorp","gaborgranger"];return t.includes(e)||t.includes(r)}extractMatrixData(e,r){const t={},s=e?.agg?.data||e?.data;if(!s||!r?.matrixrating?.rows||!r?.matrixrating?.columns)return t;const i=new Map,a=new Map;return r.matrixrating.rows.forEach(n=>{n?.id&&n?.value&&i.set(n.id,this.utilService.getTextOutOfHtmlString(n.value))}),r.matrixrating.columns.forEach(n=>{n?.id&&n?.value&&a.set(n.id,this.utilService.getTextOutOfHtmlString(n.value))}),Object.keys(s).forEach(n=>{const o=s[n],c=i.get(n)||n;t[c]={},"object"==typeof o&&null!==o&&Object.keys(o).forEach(h=>{const d=a.get(h)||h;t[c][d]="number"==typeof o[h]?o[h]:0})}),t}extractChoiceData(e,r){const t={},s=e?.agg?.data||e?.data;if(!s)return t;const i=new Map;return r?.options&&Array.isArray(r.options)&&r.options.forEach(a=>{a?.id&&a?.value&&i.set(a.id,this.utilService.getTextOutOfHtmlString(a.value))}),r?.other?.id&&r?.other?.value&&i.set(r.other.id,this.utilService.getTextOutOfHtmlString(r.other.value)),r?.preferNotToAnswer?.id&&r?.preferNotToAnswer?.value&&i.set(r.preferNotToAnswer.id,this.utilService.getTextOutOfHtmlString(r.preferNotToAnswer.value)),Object.keys(s).forEach(a=>{const n=i.get(a)||a,o="number"==typeof s[a]?s[a]:0;o>0&&(t[n]=o)}),t}extractScaleData(e,r){const t={},s=e?.agg?.data||e?.data;return s&&Object.keys(s).forEach(i=>{const a="number"==typeof s[i]?s[i]:0;a>0&&(t[i]=a)}),t}extractNumericData(e,r){const t={},s=e?.agg?.data||e?.data;return s&&Object.keys(s).forEach(i=>{const a="number"==typeof s[i]?s[i]:0;a>0&&(t[i]=a)}),t}startAnalysesForReport(e,r,t,s){var i=this;return new Promise(function(){var a=(0,v.A)(function*(n,o){let c=setInterval(()=>{if(i.blockstackService.userBlockStackProfile&&i.blockstackService.userBlockStackProfile.username&&i.blockstackService.userBlockSurveyProfile&&i.blockstackService.userBlockSurveyProfile.key){c&&clearInterval(c);const h={stacksId:i.blockstackService.userBlockStackProfile?.username,stacksKey:i.blockstackService.userBlockSurveyProfile?.key,teamId:e||""},d={report_id:r,analysis_types:t};s&&(d.quantitative_data=s),i.activationSignalsService.recordAiUsage("dataAnalysis"),i.restService.postWithHeader(_.Y.AI_DATA_ANALYSIS_API_SVC_URL+"/ai-survey-analysis/start-analyses",d,{headers:h}).subscribe({next:p=>{i.invalidateReportCache(r),i.surveyAnalysisListCache.clear(),i.cacheTimestamps.clear(),n(p)},error:p=>{console.error(p),o(p)}})}},300)});return function(n,o){return a.apply(this,arguments)}}())}getSurveyAnalysisStatus(e,r){return new Promise((t,s)=>{let i=setInterval(()=>{this.blockstackService.userBlockStackProfile&&this.blockstackService.userBlockStackProfile.username&&this.blockstackService.userBlockSurveyProfile&&this.blockstackService.userBlockSurveyProfile.key&&(i&&clearInterval(i),this.restService.getWithHeader(`${_.Y.AI_DATA_ANALYSIS_API_SVC_URL}
1/ai-survey-analysis/status?analysis_id=${r}`,{headers:{stacksId:this.blockstackService.userBlockStackProfile?.username,stacksKey:this.blockstackService.userBlockSurveyProfile?.key,teamId:e||"personal"}}).subscribe({next:o=>t(o),error:o=>{console.error(o),s(o)}}))},300)})}deleteAiDataAnalysisReport(e,r){var t=this;return new Promise(function(){var s=(0,v.A)(function*(i,a){let n=setInterval(()=>{t.blockstackService.userBlockStackProfile&&t.blockstackService.userBlockStackProfile.username&&t.blockstackService.userBlockSurveyProfile&&t.blockstackService.userBlockSurveyProfile.key&&(n&&clearInterval(n),t.restService.deleteWithHeader(_.Y.AI_DATA_ANALYSIS_API_SVC_URL+"/delete-report?report_id="+e,{headers:{stacksId:t.blockstackService.userBlockStackProfile?.username,stacksKey:t.blockstackService.userBlockSurveyProfile?.key,teamId:r||""}}).subscribe({next:c=>{t.invalidateReportCache(e),t.surveyAnalysisListCache.clear(),t.cacheTimestamps.clear(),i(c)},error:c=>{const h=c?.message?.toLowerCase()||c?.error?.message?.toLowerCase()||c?.statusText?.toLowerCase()||"",d=404===c?.status,p=h.includes("not found")||h.includes("does not exist")||h.includes("already deleted");d||p?(t.invalidateReportCache(e),t.surveyAnalysisListCache.clear(),t.cacheTimestamps.clear(),i({status:"success",message:"Report deleted successfully (was already removed)"})):(console.error("Delete report error:",c),a(c))}}))},300)});return function(i,a){return s.apply(this,arguments)}}())}extractErrorMessage(e,r="Something went wrong. Please try again later."){const t=e?.error??e,s=t?.error?.message??t?.detail??t?.message;if("string"==typeof s&&s.trim())return s.trim();if(Array.isArray(t?.detail)&&t.detail[0]?.msg)return t.detail[0].msg;switch(e?.status){case 0:return"We couldn't reach the analysis service. Check your internet connection and try again.";case 401:case 403:return"Your session has expired. Please sign in again and retry the upload.";case 413:return"That file is too large to upload. Keep it under 20MB, or split it into smaller files.";case 429:return"Too many requests right now. Please wait a moment and try again.";case 502:case 503:case 504:return"The analysis service is temporarily unavailable. Please try again in a few minutes."}return r}uploadFileToCloudflare(e,r,t,s){var i=this;return new Promise(function(){var a=(0,v.A)(function*(n,o){let c=setInterval(()=>{if(i.blockstackService.userBlockStackProfile&&i.blockstackService.userBlockStackProfile.username&&i.blockstackService.userBlockSurveyProfile&&i.blockstackService.userBlockSurveyProfile.key){c&&clearInterval(c);const h={stacksId:i.blockstackService.userBlockStackProfile?.username,stacksKey:i.blockstackService.userBlockSurveyProfile?.key,teamId:e||"",owner:s||""},d=new FormData;d.append("file",r),d.append("analysisType",t),i.restService.postWithHeader(_.Y.AI_DATA_ANALYSIS_API_SVC_URL+"/upload-dataset",d,{headers:h}).subscribe({next:p=>{p&&n(p)},error:p=>{console.error(p),o(p)}})}},300)});return function(n,o){return a.apply(this,arguments)}}())}getSummaryOfFile(e,r,t){var s=this;return new Promise(function(){var i=(0,v.A)(function*(a,n){let o=setInterval(()=>{s.blockstackService.userBlockStackProfile&&s.blockstackService.userBlockStackProfile.username&&s.blockstackService.userBlockSurveyProfile&&s.blockstackService.userBlockSurveyProfile.key&&(o&&clearInterval(o),s.restService.postWithHeader(_.Y.AI_DATA_ANALYSIS_API_SVC_URL+"/summarize-dataset",{report_id:t,dataset_details:r},{headers:{stacksId:s.blockstackService.userBlockStackProfile?.username,stacksKey:s.blockstackService.userBlockSurveyProfile?.key,teamId:e||""}}).subscribe({next:d=>{d&&a(d)},error:d=>{console.error(d),n(d)}}))},300)});return function(a,n){return i.apply(this,arguments)}}())}generateAnswer(e,r,t,s,i,a){var n=this;return new Promise(function(){var o=(0,v.A)(function*(c,h){let d=setInterval(()=>{n.blockstackService.userBlockStackProfile&&n.blockstackService.userBlockStackProfile.username&&n.blockstackService.userBlockSurveyProfile&&n.blockstackService.userBlockSurveyProfile.key&&(d&&clearInterval(d),n.restService.postWithHeader(_.Y.AI_DATA_ANALYSIS_API_SVC_URL+"/generate-answer",{report_id:i,analysis_type:a,dataset_details:r,dataset_summary:t,question:s},{headers:{stacksId:n.blockstackService.userBlockStackProfile?.username,stacksKey:n.blockstackService.userBlockSurveyProfile?.key,teamId:e||""}}).subscribe({next:S=>{S&&c(S)},error:S=>{console.error(S),h(S)}}))},300)});return function(c,h){return o.apply(this,arguments)}}())}generateProgram(e,r,t,s,i,a,n){var o=this;return new Promise(function(){var c=(0,v.A)(function*(h,d){let p=setInterval(()=>{o.blockstackService.userBlockStackProfile&&o.blockstackService.userBlockStackProfile.username&&o.blockstackService.userBlockSurveyProfile&&o.blockstackService.userBlockSurveyProfile.key&&(p&&clearInterval(p),o.restService.postWithHeader(_.Y.AI_DATA_ANALYSIS_API_SVC_URL+"/generate-program",{report_id:a,analysis_type:n,dataset_details:r,dataset_summary:t,answer_summary:s,file_key:i},{headers:{stacksId:o.blockstackService.userBlockStackProfile?.username,stacksKey:o.blockstackService.userBlockSurveyProfile?.key,teamId:e||""}}).subscribe({next:g=>{g&&h(g)},error:g=>{console.error(g),d(g)}}))},300)});return function(h,d){return c.apply(this,arguments)}}())}generateFinalAnswer(e,r,t,s,i,a,n,o){var c=this;return new Promise(function(){var h=(0,v.A)(function*(d,p){let k=setInterval(()=>{c.blockstackService.userBlockStackProfile&&c.blockstackService.userBlockStackProfile.username&&c.blockstackService.userBlockSurveyProfile&&c.blockstackService.userBlockSurveyProfile.key&&(k&&clearInterval(k),c.restService.postWithHeader(_.Y.AI_DATA_ANALYSIS_API_SVC_URL+"/summarize-final-answer-to-json",{report_id:n,analysis_type:o,dataset_summary:r,answer_summary:t,program_result:s,question:i,output_format:a},{headers:{stacksId:c.blockstackService.userBlockStackProfile?.username,stacksKey:c.blockstackService.userBlockSurveyProfile?.key,teamId:e||""}}).subscribe({next:x=>{x&&d(x)},error:x=>{console.error(x),p(x)}}))},300)});return function(d,p){return h.apply(this,arguments)}}())}generateAnalysis(e,r,t,s,i){var a=this;return new Promise(function(){var n=(0,v.A)(function*(o,c){let h=setInterval(()=>{a.blockstackService.userBlockStackProfile&&a.blockstackService.userBlockStackProfile.username&&a.blockstackService.userBlockSurveyProfile&&a.blockstackService.userBlockSurveyProfile.key&&(h&&clearInterval(h),a.restService.postWithHeader(_.Y.AI_DATA_ANALYSIS_API_SVC_URL+"/ai-data-analysis/"+i,{report_id:s,analysis_type:i,dataset_summary:r,file_key:t},{headers:{stacksId:a.blockstackService.userBlockStackProfile?.username,stacksKey:a.blockstackService.userBlockSurveyProfile?.key,teamId:e||""}}).subscribe({next:k=>{k&&o(k)},error:k=>{console.error(k),c(k)}}))},300)});return function(o,c){return n.apply(this,arguments)}}())}generateDetailedSummary(e,r,t){var s=this;return new Promise(function(){var i=(0,v.A)(function*(a,n){let o=setInterval(()=>{s.blockstackService.userBlockStackProfile&&s.blockstackService.userBlockStackProfile.username&&s.blockstackService.userBlockSurveyProfile&&s.blockstackService.userBlockSurveyProfile.key&&(o&&clearInterval(o),s.restService.postWithHeader(_.Y.AI_DATA_ANALYSIS_API_SVC_URL+"/generate-detailed-summary",{report_id:r,dataset_details:t,analysis_type:"detailedSummary"},{headers:{stacksId:s.blockstackService.userBlockStackProfile?.username,stacksKey:s.blockstackService.userBlockSurveyProfile?.key,teamId:e||""}}).subscribe({next:d=>{d&&a(d)},error:d=>{console.error(d),n(d)}}))},300)});return function(a,n){return i.apply(this,arguments)}}())}generateActionItemsForInsights(e,r,t){var s=this;return new Promise(function(){var i=(0,v.A)(function*(a,n){let o=setInterval(()=>{s.blockstackService.userBlockStackProfile&&s.blockstackService.userBlockStackProfile.username&&s.blockstackService.userBlockSurveyProfile&&s.blockstackService.userBlockSurveyProfile.key&&(o&&clearInterval(o),s.restService.postWithHeader(_.Y.AI_DATA_ANALYSIS_API_SVC_URL+"/generate-action-items-for-insights",{report_id:r,analysis_type:"actionItems",insights:t},{headers:{stacksId:s.blockstackService.userBlockStackProfile?.username,stacksKey:s.blockstackService.userBlockSurveyProfile?.key,teamId:e||""}}).subscribe({next:d=>{d&&a(d)},error:d=>{console.error(d),n(d)}}))},300)});return function(a,n){return i.apply(this,arguments)}}())}generateReportForAnalysis(e,r,t,s,i){var a=this;return(0,v.A)(function*(){const n=r,o=s,c=t,h=i||"personal";let p={},k=[];const S=[],g=[];a.processTypeMsg[h]="Analyzing your responses...";for(let b of a.analysisToBeDone){let N;a.processStatus[h]||(a.processStatus[h]={}),a.processStatus[h][b.id]="",a.processStatus[h].detailedSummary="",N=a.generateAnalysis(i,o,c,e,b.id).then(w=>
1{w&&w.data&&(p[b.id]=w.data.final_answer),g.push(b.id),a.processStatus[h][b.id]=!0}).catch(w=>(console.error(w),S.push({id:b.id,name:b.name||b.id,message:a.extractErrorMessage(w,`We couldn't complete the ${b.name||b.id}.`)}),a.processStatus[h][b.id]="failed",null)),k.push(N)}const x=a.generateDetailedSummary(i,e,n).then(b=>{b&&b.data&&(p.detailedSummary=b.data.final_answer),g.push("detailedSummary"),a.processStatus[h].detailedSummary=!0}).catch(b=>(console.error(b),S.push({id:"detailedSummary",name:"Detailed Summary",message:a.extractErrorMessage(b,"We couldn't generate the detailed summary.")}),a.processStatus[h].detailedSummary="failed",null));return k.push(x),yield Promise.all(k),g.length>0&&a.intercomService.sendCustomAttributes({ai_analysis_comprehensive:"yes"}),{data:p,succeeded:g,failed:S}})()}isCacheValid(e){const r=this.cacheTimestamps.get(e);return!!r&&Date.now()-r<this.CACHE_TTL}isCacheValidForKey(e){return this.isCacheValid(e)}updateCacheTimestamp(e){this.cacheTimestamps.set(e,Date.now())}getOrCreateAnalysisListSubject(e){return this.surveyAnalysisListCache.has(e)||this.surveyAnalysisListCache.set(e,new I.t([])),this.surveyAnalysisListCache.get(e)}getOrCreateReportSubject(e){return this.analysisReportCache.has(e)||this.analysisReportCache.set(e,new I.t(null)),this.analysisReportCache.get(e)}invalidateSurveyCache(e){const r=[];for(const t of this.surveyAnalysisListCache.keys())t.includes(e)&&r.push(t);r.forEach(t=>{this.surveyAnalysisListCache.delete(t),this.cacheTimestamps.delete(t)})}invalidateReportCache(e){const r=[];for(const t of this.analysisReportCache.keys())t.includes(e)&&r.push(t);r.forEach(t=>{this.analysisReportCache.delete(t),this.cacheTimestamps.delete(t)})}fetchOptimizedSurveyAnalysisList(e,r,t=!1){if(!r)return(0,P.of)([]);const s=`analysis-list-${e}-${r}`,i=this.getOrCreateAnalysisListSubject(s);if(!t&&this.isCacheValid(s)&&i.value.length>0)return i.asObservable();const a=setInterval(()=>{const n=this.blockstackService.userBlockStackProfile?.username,o=this.blockstackService.userBlockSurveyProfile?.key;if(!n||!o)return;clearInterval(a);const c=e||"personal";this.restService.postWithHeader(`${_.Y.AI_DATA_ANALYSIS_API_SVC_URL}/ai-survey-analysis/get-survey-analysis`,{userId:n,key:o,teamId:c,surveyId:r},{headers:{stacksId:n,stacksKey:o,teamId:c}}).pipe((0,T.T)(p=>p?.aiSurveyAnalysis||[]),(0,C.M)(p=>{this.updateCacheTimestamp(s),i.next(p)}),(0,D.W)(p=>(console.error("Failed to fetch survey analysis list:",p),(0,P.of)([])))).subscribe()},300);return i.asObservable()}fetchOptimizedAnalysisReport(e,r,t,s=!1,i=!1){const a=`analysis-report-${e}-${s?"summary":"full"}`,n=this.getOrCreateReportSubject(a);if(!i&&this.isCacheValid(a)&&n.value)return n.asObservable();if("default"===e)return this.restService.get("https://static-files.blocksurvey.io/demo_ai_data_analyisis_report.json").pipe((0,C.M)(c=>{this.updateCacheTimestamp(a),n.next({data:c})}),(0,D.W)(c=>(console.error("Failed to fetch sample analysis report:",c),n.next(null),(0,P.of)(null)))).subscribe(),n.asObservable();const o=setInterval(()=>{if(this.blockstackService.userBlockStackProfile&&this.blockstackService.userBlockStackProfile.username&&this.blockstackService.userBlockSurveyProfile&&this.blockstackService.userBlockSurveyProfile.key){clearInterval(o);const c=this.blockstackService.userBlockStackProfile?.username,h=this.blockstackService.userBlockSurveyProfile?.key,d=r||"personal",p={stacksId:c,stacksKey:h,teamId:d},k={userId:c,key:h,teamId:d,reportId:e,summaryMode:s||!1};t&&(k.surveyId=t),this.restService.postWithHeader(`${_.Y.AI_DATA_ANALYSIS_API_SVC_URL}/ai-survey-analysis/get-report`,k,{headers:p}).pipe((0,C.M)(g=>{this.updateCacheTimestamp(a),n.next(g)}),(0,D.W)(g=>(console.error(`Failed to fetch ${s?"summary":"full"} analysis report:`,g),(0,P.of)(null)))).subscribe()}},300);return n.asObservable()}getOptimizedSurveyAnalysisStatus(e,r){return new Promise((t,s)=>{const i=setInterval(()=>{this.blockstackService.userBlockStackProfile&&this.blockstackService.userBlockStackProfile.username&&this.blockstackService.userBlockSurveyProfile&&this.blockstackService.userBlockSurveyProfile.key&&(clearInterval(i),this.restService.getWithHeader(`${_.Y.AI_DATA_ANALYSIS_API_SVC_URL}
1/ai-survey-analysis/status?analysis_id=${r}`,{headers:{stacksId:this.blockstackService.userBlockStackProfile?.username,stacksKey:this.blockstackService.userBlockSurveyProfile?.key,teamId:e||"personal"}}).subscribe({next:o=>t(o),error:o=>{console.error("Failed to fetch analysis status:",o),s(o)}}))},300)})}clearAnalysisCache(){this.surveyAnalysisListCache.clear(),this.analysisReportCache.clear(),this.cacheTimestamps.clear()}clearSurveyCache(e){this.invalidateSurveyCache(e)}refreshSurveyAnalyses(e,r){return this.fetchOptimizedSurveyAnalysisList(e,r,!0)}refreshAnalysisReport(e,r,t,s=!1){return this.fetchOptimizedAnalysisReport(e,r,t,s,!0)}savePublicAiReportSnapshot(e){return new Promise((r,t)=>{const s=setInterval(()=>{const i=this.blockstackService.userBlockStackProfile?.username,a=this.blockstackService.userBlockSurveyProfile?.key;i&&a&&(clearInterval(s),this.restService.postWithHeader(`${_.Y.AI_DATA_ANALYSIS_API_SVC_URL}/ai-survey-analysis/save-public-snapshot`,e,{headers:{stacksId:i,stacksKey:a,teamId:e.teamId||"personal"}}).subscribe({next:o=>{this.invalidateReportCache(e.reportId),r(o)},error:o=>{console.error("Failed to save public AI report snapshot:",o),t(o)}}))},300)})}getQualityColor(e){return{excellent:"#10b981",good:"#14b8a6",fair:"#f59e0b",poor:"#f97316",critical:"#ef4444"}[e]||"#6b7280"}getQualityTextColor(e){return{excellent:"text-emerald-600",good:"text-teal-600",fair:"text-amber-600",poor:"text-orange-600",critical:"text-red-600"}[e]||"text-gray-600"}getQualityBgColor(e){return{excellent:"bg-emerald-50",good:"bg-teal-50",fair:"bg-amber-50",poor:"bg-orange-50",critical:"bg-red-50"}[e]||"bg-gray-50"}getConfidenceBadgeColor(e){return e>=85?"text-emerald-600 bg-emerald-50":e>=70?"text-amber-600 bg-amber-50":e>=50?"text-orange-600 bg-orange-50":"text-red-600 bg-red-50"}getStatusIcon(e){return{passed:"\u2705",warning:"\u26a0\ufe0f",error:"\u274c"}[e]||"\u2753"}static{this.\u0275fac=function(r){return new(r||y)(A.KVO(M.L),A.KVO(R.G),A.KVO(E.l),A.KVO(U.a),A.KVO(l.f))}}static{this.\u0275prov=A.jDH({token:y,factory:y.\u0275fac,providedIn:"root"})}}return y})()},54205(K,L,m){m.d(L,{Vh:()=>A,lU:()=>O,oA:()=>R});var v=m(10467),I=m(91413),B=m(54843),P=m(62087),D=m(95095),T=m(60414),C=m(76417);const O={generate:12e3,edit:6e3,element:3e3};class A extends Error{constructor(U,l,u){super(l),this.code=U,this.status=u}}const M={generate:135e3,edit:105e3,"edit-element":6e4,"edit-block":6e4,"suggest-prompts":3e4};let R=(()=>{class E{constructor(l,u){this.http=l,this.blockstackService=u,this.tokenBannerDismissed=!1}auth(l){return{userId:this.blockstackService.userBlockStackProfile?.username,key:this.blockstackService.userBlockSurveyProfile?.key,orgId:this.blockstackService.selectedOrganizationId,teamId:l||null}}toError(l){if(l instanceof I.yz){const u=l.error&&"object"==typeof l.error?l.error:{};if(102===u.errorCode)return new A("INSUFFICIENT_TOKENS",u.message,l.status);const y=u.message||u.detail||(0===l.status?"You appear to be offline. Check your connection and try again.":"Something went wrong. Try again.");return new A(u.errorCode||`HTTP_${l.status}`,"string"==typeof y?y:"Something went wrong. Try again.",l.status)}return new A("UNKNOWN","Something went wrong. Try again.",0)}api(l,u){var y=this;return(0,v.A)(function*(f,e,r={}){try{return yield(0,B._)(y.http.post(`${D.Y.API_SVC_URL}/blocksurvey/pdf-report/${f}`,{...y.auth(e),...r}))}catch(t){throw y.toError(t)}}).apply(this,arguments)}ai(l,u,y){var f=this;return(0,v.A)(function*(){const e=M[l]||6e4,r={stacksId:f.blockstackService.userBlockStackProfile?.username||"",stacksKey:f.blockstackService.userBlockSurveyProfile?.key||"",teamId:u||""};try{return yield(0,B._)(f.http.post(`${D.Y.AI_SURVEY_CREATION_API_SVC_URL}/ai-pdf-report/${l}`,{orgId:f.blockstackService.selectedOrganizationId,...y},{headers:r}).pipe((0,P.w)({first:e})))}catch(t){throw t instanceof P.M?new A("TIMEOUT","The AI took too long to respond. Try again.",0):f.toError(t)}})()}list(l){return this.api("list",l).then(u=>u.pdfReports)}get(l,u){return this.api("get",l,{pdfReportId:u}).then(y=>y.pdfReport)}getVersion(l,u,y){return this.api("get-version",l,{pdfReportId:u,version:y}).then(f=>f.version)}
1create(l,u,y,f,e){return this.api("create",l,{name:u,source:y,draft:f,boundSurveyId:e}).then(r=>r.pdfReport)}saveDraft(l,u,y,f,e){const r={pdfReportId:u,draft:y};return void 0!==f&&(r.expectedDraftUpdatedAt=f),void 0!==e&&(r.boundSurveyId=e),this.api("save-draft",l,r).then(t=>t.draftUpdatedAt)}publish(l,u,y,f){return this.api("publish",l,{pdfReportId:u,surveyId:y,aiGenerated:f}).then(e=>e.version)}rename(l,u,y){return this.api("rename",l,{pdfReportId:u,name:y}).then(f=>f.name)}duplicate(l,u,y={}){return this.api("duplicate",l,{pdfReportId:u,...y}).then(f=>f.pdfReport)}detach(l,u,y){return this.api("detach",l,{pdfReportId:u,surveyId:y}).then(()=>{})}delete(l,u){return this.api("delete",l,{pdfReportId:u}).then(()=>{})}renderResponse(l,u,y,f,e,r){var t=this;return(0,v.A)(function*(){try{const s=yield(0,B._)(t.http.post(`${D.Y.API_SVC_URL}/blocksurvey/pdf-report/render-response`,{...t.auth(l),surveyId:u,pdfReportId:y,version:f,data:e,purpose:r},{responseType:"blob",observe:"response"}));return{blob:s.body,fileName:decodeURIComponent(s.headers.get("x-file-name")||"report.pdf")}}catch(s){if(s instanceof I.yz&&s.error instanceof Blob){const i=yield s.error.text().catch(()=>"{}");let a={};try{a=JSON.parse(i)}catch{}throw t.toError(new I.yz({error:a,status:s.status}))}throw t.toError(s)}})()}testRender(l,u,y){var f=this;return(0,v.A)(function*(){try{const e=yield(0,B._)(f.http.post(`${D.Y.API_SVC_URL}/blocksurvey/pdf-report/test-render`,{...f.auth(l),content:u,data:y},{responseType:"blob",observe:"response"}));return{blob:e.body,fileName:decodeURIComponent(e.headers.get("x-file-name")||"report.pdf")}}catch(e){if(e instanceof I.yz&&e.error instanceof Blob){const r=yield e.error.text().catch(()=>"{}");let t={};try{t=JSON.parse(r)}catch{}throw f.toError(new I.yz({error:t,status:e.status}))}throw f.toError(e)}})()}generate(l,u,y){return this.ai("generate",l,{survey:u,prompt:y}).then(f=>(this.applyUsage(f.usedTokens),f))}editBlocks(l,u,y,f){return this.ai("edit",l,{survey:u,prompt:y,currentBlocks:f}).then(e=>(this.applyUsage(e.usedTokens),e))}edit(l,u,y,f){return this.ai("edit",l,{survey:u,prompt:y,current:f}).then(e=>(this.applyUsage(e.usedTokens),e))}editBlock(l,u,y,f){return this.ai("edit-block",l,{survey:u,prompt:y,block:f}).then(e=>(this.applyUsage(e.usedTokens),e))}editElement(l,u,y,f,e,r){return this.ai("edit-element",l,{survey:u,prompt:y,element:f,css:e,pjId:r}).then(t=>(this.applyUsage(t.usedTokens),t))}suggestPrompts(l,u,y){return this.ai("suggest-prompts",l,{surveyId:u,survey:y}).then(f=>f.suggestions||[]).catch(()=>[])}availableTokens(){const l=this.blockstackService.selectedOrganization?.openAIConfig;return l?(l.maxTokens||0)-(l.usedTokens||0):0}needsUpgradeForAi(){const l=this.blockstackService.selectedOrganization;return!(!l||"plan_free"!==l?.plan?.id&&"plan_student"!==l?.plan?.id&&l?.plan?.subscription)}isPaidPlan(){const l=this.blockstackService.selectedOrganization?.plan?.id;return!!l&&"plan_free"!==l}tokenUsagePercent(){const l=this.blockstackService.selectedOrganization?.openAIConfig,u=l?.maxTokens||0;return u>0?Math.round((l?.usedTokens||0)/u*100):0}applyUsage(l){const u=this.blockstackService.selectedOrganization;u&&"number"==typeof l&&(u.openAIConfig={...u.openAIConfig||{},usedTokens:l})}static{this.\u0275fac=function(u){return new(u||E)(T.KVO(I.Qq),T.KVO(C.L))}}static{this.\u0275prov=T.jDH({token:E,factory:E.\u0275fac,providedIn:"root"})}}return E})()},69187(K,L,m){m.d(L,{J:()=>B});var v=m(35547),I=m(60177);let B=(()=>{class P{constructor(T,C){this.el=T,this.platformId=C}onWheel(T){(0,I.UE)(this.platformId)&&this.el.nativeElement===this.el.nativeElement.ownerDocument.activeElement&&T.preventDefault()}static{this.\u0275fac=function(C){return new(C||P)(v.rXU(v.aKT),v.rXU(v.Agw))}}static{this.\u0275dir=v.FsC({type:P,selectors:[["input","type","number"]],hostBindings:function(C,_){1&C&&v.bIt("wheel",function(A){return _.onWheel(A)})},standalone:!1})}}return P})()}}]);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.