// FILE: src/core/scoring.ts /** * Pontuação 100% estática (sem backend). * * Porto de `ScoringService.java`: acumula as respostas (e os efeitos das * perguntas de arquétipo) em médias ponderadas por eixo, com eixo vazio neutro * (50%), e reconstrói `AxisResult` a partir de um vetor de leftPercents * (`scoreFromLeftPercents`). Todos os dados vêm de `getCatalog()`; nenhum * endpoint REST é chamado e nenhum dado de negócio é hardcoded. * * O vetor devolvido por `scoreToLeftPercents` contém exatamente os valores * `AxisResult.leftPercent` (já com clamp 0..100 e round1), na ordem de * `axes.json` — é o mesmo vetor que o backend entrega em `result.axes` e que * alimenta todas as compatibilidades de `buildResult`. */ import { getCatalog, type RawAxis } from './catalog'; import { scoreTowardAgreement } from './quiz'; import type { AnswerValue, AxisResult, SubmittedAnswer } from '../types/quiz'; const CENTER = 50; function round1(value: number): number { return Math.round(value * 10.0) / 10.0; } function clamp(value: number): number { return Math.max(0.0, Math.min(100.0, value)); } /** `ScoringService.intensityFor`: distância ao centro em 4 faixas. */ const INTENSITIES = ['Balanced', 'Leaning', 'Strong', 'Very strong'] as const; function intensityFor(distanceFromCenter: number): string { const level = distanceFromCenter < 7.5 ? 0 : distanceFromCenter < 22.5 ? 1 : distanceFromCenter < 37.5 ? 2 : 3; return INTENSITIES[level]; } /** `ScoringService.buildAxisResult`. */ function buildAxisResult(axis: RawAxis, rawLeftPercent: number): AxisResult { const leftPercent = round1(clamp(rawLeftPercent)); const rightPercent = round1(100.0 - leftPercent); const dominantPole = leftPercent >= rightPercent ? axis.leftPole : axis.rightPole; return { axisId: axis.id, label: axis.label, leftPole: axis.leftPole, rightPole: axis.rightPole, leftPercent, rightPercent, dominantPole, intensity: intensityFor(Math.abs(leftPercent - CENTER)) }; } /** `ScoringService.WeightedScore`: total/weight, com peso zero = 0.5 (50%). */ interface WeightedScore { total: number; weight: number; } function add(score: WeightedScore, value: number, itemWeight: number): void { score.total += value * itemWeight; score.weight += itemWeight; } function average(score: WeightedScore): number { return score.weight === 0 ? 0.5 : score.total / score.weight; } /** `ScoringService.leftScore`: concordar com o polo direito vale o oposto. */ function leftScore(agreePole: 'LEFT' | 'RIGHT', answer: AnswerValue): number { const towardAgreement = scoreTowardAgreement(answer); return agreePole === 'LEFT' ? towardAgreement : 1.0 - towardAgreement; } // --------------------------------------------------------------------------- // API pública // --------------------------------------------------------------------------- /** * Equivale à pontuação do endpoint de resultados: 12 leftPercents, um por eixo na * ordem de `axes.json`. Respostas e efeitos de arquétipo entram na mesma média * ponderada; eixos sem nenhuma resposta ficam neutros em 50. */ export async function scoreToLeftPercents( answers: SubmittedAnswer[], archetype: Record = {} ): Promise { const catalog = await getCatalog(); const questionById = new Map(catalog.questions.map((question) => [question.id, question])); // `validateAnswers`: ids desconhecidos são erro (o Java responde 400). const unknown = answers .map((submitted) => submitted.questionId) .filter((id) => !questionById.has(id)); if (unknown.length > 0) { throw new Error(`Invalid answers. Unknown IDs: ${[...new Set(unknown)].join(', ')}`); } const scores = new Map(); for (const submitted of answers) { const question = questionById.get(submitted.questionId)!; let score = scores.get(question.axisId); if (!score) { score = { total: 0, weight: 0 }; scores.set(question.axisId, score); } add(score, leftScore(question.agreePole, submitted.answer), question.weight); } // `addArchetypeAnswers`: cada efeito (leftPercent 0..100) entra como uma // resposta a mais naquele eixo, com peso 1. const archetypeById = new Map(catalog.archetypeQuestions.map((question) => [question.id, question])); for (const [questionId, optionId] of Object.entries(archetype)) { const question = archetypeById.get(questionId); const option = question?.options.find((candidate) => candidate.id === optionId); if (!option) { throw new Error(`Invalid archetype answer: ${questionId}=${optionId}`); } for (const [axisId, leftPercent] of Object.entries(option.effects)) { let score = scores.get(axisId); if (!score) { score = { total: 0, weight: 0 }; scores.set(axisId, score); } add(score, leftPercent / 100.0, 1.0); } } return catalog.axes.map((axis) => { const score = scores.get(axis.id) ?? { total: 0, weight: 0 }; return round1(clamp(average(score) * 100.0)); }); } /** * `ScoringService.scoreFromLeftPercents`: um `AxisResult` por eixo, na ordem de * `axes.json`, com clamp + round1, polo dominante e intensidade. Valores * ausentes ou não finitos caem no centro (50) em vez de derrubar a tela. */ export async function axisResultsFromPercents(leftPercents: number[]): Promise { const catalog = await getCatalog(); return catalog.axes.map((axis, index) => { const raw = leftPercents[index]; return buildAxisResult(axis, Number.isFinite(raw) ? raw : CENTER); }); } // FILE: src/core/compare.ts /** * Comparação 100% estática (sem backend). * * Porta de `CompareController` / `CompareService` e de `ProfileMatchScorer`: todos os dados * vêm de `getCatalog()` (os 16 JSON de `public/data`), nenhum `/api` é chamado e nenhum * dado de negócio é hardcoded. As funções de catálogo, similaridade, filtro de religião, * construção de matches e rankings também são exportadas para `premium.ts` reutilizar. * * Diferenças em relação ao Java (equivalências/aproximações documentadas no relatório final): * - `leftPercents` vira o vetor do usuário na ordem de `axes.json` (como `scoreFromLeftPercents`); * valores ausentes/fora do tamanho caem no centro (50) em vez de 400. * - `vector` devolvido é sempre normalizado para os 12 eixos (o perfil bruto pode ter menos). * - `IdeologyMatch.longDescription` / `description` usam uma geração de texto simplificada * (o Java faz `splitDescription` por "Politicamente:", ausente nos dados em inglês). * - `nearest` / `commonIdeology` percorrem o ranking completo em vez dos top-4/top-3: o * primeiro resultado é o mesmo, pois esses recortes já vêm do mesmo ranking ordenado. * - `percentile` (do Java) não existe no contrato de `types/quiz.ts`, então não é produzido. * - Idioma fixo em inglês: é o idioma dos arquivos de dados e o default do backend. */ import { getCatalog, type Catalog, type RawAxis, type RawCountry, type RawIdeology, type RawParty, type RawPersonality, type Vector } from './catalog'; import type { CompareDetail, CompareItem, CompareNearest, ComparePair, CompareProfile, CompareProfiles, CompareType, CountryMatch, IdeologyMatch, PartyMatch, PersonalityCategory, PersonalityMatch } from '../types/quiz'; // --------------------------------------------------------------------------- // ProfileMatchScorer.java — mesma fórmula, mesmas constantes, mesmo round1/clamp // --------------------------------------------------------------------------- export const CENTER = 50; const AXIS_SPREAD = 50; const AXIS_WEIGHT = 0.42; const DIRECTION_WEIGHT = 0.33; const MAGNITUDE_WEIGHT = 0.18; const OUTLIER_WEIGHT = 0.07; const OPPOSITE_SIDE_MAX_PENALTY = 0.45; const OPPOSITE_SIDE_SPREAD = 25; const OUTLIER_FULL_SPREAD = 100; const OUTLIER_EXPONENT = 2.5; const DIRECTION_AUGMENT_RADIUS = 8; export function round1(value: number): number { return Math.round(value * 10) / 10; } export function clamp(value: number): number { return Math.max(0, Math.min(100, value)); } /** Compatibilidade 0..100 entre dois vetores de eixos (leftPercent), com round1. */ export function compatibility(user: Vector, target: Vector, axisIds: string[]): number { const size = axisIds.length; if (size === 0) return 0; let axisTotal = 0; let dot = 0; let userNorm = 0; let targetNorm = 0; let userIntensity = 0; let targetIntensity = 0; let maxDiff = 0; for (const id of axisIds) { const u = user[id] ?? CENTER; const t = target[id] ?? CENTER; const diff = Math.abs(u - t); let similarity = Math.max(0, 1 - Math.pow(diff / AXIS_SPREAD, 2)); if ((u - CENTER) * (t - CENTER) < 0) { similarity *= 1 - OPPOSITE_SIDE_MAX_PENALTY * Math.tanh(Math.abs(u - CENTER) / OPPOSITE_SIDE_SPREAD) * Math.tanh(Math.abs(t - CENTER) / OPPOSITE_SIDE_SPREAD); } axisTotal += similarity; dot += (u - CENTER) * (t - CENTER); userNorm += Math.pow(u - CENTER, 2); targetNorm += Math.pow(t - CENTER, 2); userIntensity += Math.abs(u - CENTER); targetIntensity += Math.abs(t - CENTER); maxDiff = Math.max(maxDiff, diff); } const augment = size * DIRECTION_AUGMENT_RADIUS * DIRECTION_AUGMENT_RADIUS; const cosine = (dot + augment) / Math.sqrt((userNorm + augment) * (targetNorm + augment)); const axisSimilarity = (100 * axisTotal) / size; const directionSimilarity = CENTER + CENTER * cosine; const magnitudeSimilarity = 100 - 2 * Math.abs(userIntensity / size - targetIntensity / size); const outlierSimilarity = 100 * Math.max(0, 1 - Math.pow(maxDiff / OUTLIER_FULL_SPREAD, OUTLIER_EXPONENT)); return round1( clamp( AXIS_WEIGHT * axisSimilarity + DIRECTION_WEIGHT * directionSimilarity + MAGNITUDE_WEIGHT * magnitudeSimilarity + OUTLIER_WEIGHT * outlierSimilarity ) ); } // --------------------------------------------------------------------------- // ReligionFilter.java — normalização e regra "exclui, não exige" // --------------------------------------------------------------------------- const CHRISTIAN = ['catholic', 'protestant', 'orthodox']; const SELECTABLE = [...CHRISTIAN, 'judaism', 'islam', 'buddhism', 'hinduism']; const LEGACY_CHRISTIANITY = 'christianity'; const OTHER = 'other'; const ONLY = 'only'; export function normalizeReligion(raw?: string | null): string | null { if (raw == null) return null; const order = [...SELECTABLE, OTHER, LEGACY_CHRISTIANITY]; const kept: string[] = []; for (const part of raw.split(',')) { const value = part.trim().toLowerCase(); if (order.includes(value) && !kept.includes(value)) kept.push(value); } if (kept.length === 0) return null; kept.sort((a, b) => order.indexOf(a) - order.indexOf(b)); return kept.join(','); } function preferredReligions(preference: string | null): string[] { if (preference === null) return []; const result: string[] = []; for (const part of preference.split(',')) { const value = part.trim(); if (value === LEGACY_CHRISTIANITY) { for (const denomination of CHRISTIAN) { if (!result.includes(denomination)) result.push(denomination); } } else if (value !== '' && !result.includes(value)) { result.push(value); } } return result; } function allows(religions: readonly string[] | null | undefined, preference: string | null): boolean { if (!religions || religions.length === 0) return true; const hasSelectable = religions.some((value) => SELECTABLE.includes(value)); const preferred = preferredReligions(preference); if (preferred.includes(OTHER)) { if (!hasSelectable) return true; if (preferred.every((value) => value === OTHER)) return false; } const matches = religions.some((value) => preferred.includes(value)); if (religions.includes(ONLY)) { return hasSelectable ? matches : preference === null; } if (preference === null) return true; return matches || !hasSelectable; } // --------------------------------------------------------------------------- // Vetores derivados do catálogo // --------------------------------------------------------------------------- export function axisIdsOf(catalog: Catalog): string[] { return catalog.axes.map((axis) => axis.id); } /** `scoreFromLeftPercents`: um valor por eixo, na ordem de `axes.json`, clamp + round1. */ export function vectorFromLeftPercents(axes: RawAxis[], leftPercents: number[]): Vector { const vector: Vector = {}; axes.forEach((axis, index) => { const raw = leftPercents[index]; vector[axis.id] = round1(clamp(Number.isFinite(raw) ? raw : CENTER)); }); return vector; } /** Normaliza qualquer vetor para exatamente os 12 eixos (ausente = centro). */ export function fillVector(raw: Vector | null | undefined, axisIds: string[]): Vector { const vector: Vector = {}; for (const id of axisIds) { const value = raw?.[id]; vector[id] = typeof value === 'number' && Number.isFinite(value) ? value : CENTER; } return vector; } export function neutralVector(axisIds: string[]): Vector { return fillVector(null, axisIds); } export type EntityKind = 'ideology' | 'country' | 'personality' | 'party'; /** Vetor alvo de um perfil: profiles.json > `vector` embutido > vetor neutro. */ export function targetVector(catalog: Catalog, kind: EntityKind, id: string, axisIds: string[]): Vector { const map = kind === 'ideology' ? catalog.ideologyVectors : kind === 'country' ? catalog.countryVectors : kind === 'personality' ? catalog.personalityVectors : catalog.partyVectors; const fromProfile = map.get(id); if (fromProfile && Object.keys(fromProfile).length > 0) return fillVector(fromProfile, axisIds); const rows: Array<{ id: string; vector?: Vector | null }> = kind === 'ideology' ? catalog.ideologies : kind === 'country' ? catalog.countries : kind === 'personality' ? catalog.personalities : catalog.parties; const inline = rows.find((row) => row.id === id)?.vector; if (inline && Object.keys(inline).length > 0) return fillVector(inline, axisIds); return neutralVector(axisIds); } export interface CountryRef { name: string; flagPath: string; } /** Join dos países (nome + bandeira) para legendas de partidos e `PartyMatch`. */ export function countryIndex(catalog: Catalog): Map { return new Map(catalog.countries.map((country) => [country.id, { name: country.name, flagPath: country.flagPath }])); } // --------------------------------------------------------------------------- // Textos de ideologia (aproximação de IdeologyMatcherService) // --------------------------------------------------------------------------- function cleanDescription(raw: string | null | undefined): string { let description = (raw ?? '').trim().replace(/\s+/g, ' '); const note = description.indexOf('NOTA METODOLÓGICA'); if (note >= 0) description = description.slice(0, note).trim(); return description; } function abbreviate(value: string, maxLength: number): string { if (value.length <= maxLength) return value; let cut = value.lastIndexOf(' ', maxLength - 1); if (cut < maxLength / 2) cut = maxLength - 1; return value.slice(0, cut).trim() + '...'; } function shortDescription(raw: string | null | undefined): string { const clean = cleanDescription(raw); const sentences = clean.split(/(?<=[.!?])\s+/).filter(Boolean); let summary = sentences[0] ?? clean; if (sentences.length > 1 && summary.length < 140) summary += ' ' + sentences[1]; return abbreviate(summary, 230); } function longDescription(raw: string | null | undefined): string { const clean = cleanDescription(raw); let description = clean.endsWith('.') ? clean : clean + '.'; description += ' Compatibility indicates how close your answers are to this profile.'; // Os dados em inglês não trazem o bloco "Politicamente:" que o Java usa para // acrescentar "In practical terms: ..."; sem ele, o Java também omite o parágrafo. return description; } // --------------------------------------------------------------------------- // Construção dos matches do contrato de types/quiz.ts // --------------------------------------------------------------------------- type CountryExtra = RawCountry & { flagKind?: string; flagSourceName?: string; flagSourceUrl?: string; flagNote?: string; }; function toIdeologyMatch(row: RawIdeology, compat: number): IdeologyMatch { return { ideologyId: row.id, name: row.name, category: row.category, description: shortDescription(row.description), longDescription: longDescription(row.description), phrase: row.phrase, compatibility: compat }; } function toCountryMatch(row: RawCountry, compat: number, vector: Vector): CountryMatch { const extra = row as CountryExtra; return { countryId: row.id, name: row.name, category: row.category, description: row.description, flagPath: row.flagPath, flagKind: extra.flagKind, flagSourceName: extra.flagSourceName, flagSourceUrl: extra.flagSourceUrl, flagNote: extra.flagNote, historical: row.historical, period: row.period, compatibility: compat, vector }; } function toPersonalityMatch(row: RawPersonality, compat: number, vector: Vector): PersonalityMatch { return { personalityId: row.id, name: row.name, role: row.role, category: row.category as PersonalityCategory, lifespan: row.lifespan, description: row.description, imagePath: row.imagePath, imageSourceName: row.imageSourceName, imageSourceUrl: row.imageSourceUrl, imageNote: row.imageNote, compatibility: compat, vector }; } function toPartyMatch(row: RawParty, compat: number, vector: Vector, countries: Map): PartyMatch { const country = countries.get(row.countryId); return { partyId: row.id, name: row.name, category: row.category, description: row.description, logoPath: row.logoPath, logoSourceName: row.logoSourceName, logoSourceUrl: row.logoSourceUrl, logoNote: row.logoNote, countryId: row.countryId, countryName: country?.name ?? '', countryFlagPath: country?.flagPath ?? '', historical: row.historical, period: row.period, compatibility: compat, vector }; } interface Scored { row: T; compat: number; vector: Vector; } function cmpName(a: string, b: string): number { return a < b ? -1 : a > b ? 1 : 0; } function byScore(a: Scored, b: Scored): number { return b.compat - a.compat || cmpName(a.row.name, b.row.name); } /** Ranking completo de ideologias (do mais ao menos compatível), com filtro de religião. */ export function rankIdeologies( catalog: Catalog, user: Vector, religion?: string | null, axisIds: string[] = axisIdsOf(catalog) ): IdeologyMatch[] { const pref = normalizeReligion(religion ?? null); const scored: Scored[] = catalog.ideologies.map((row) => { const vector = targetVector(catalog, 'ideology', row.id, axisIds); return { row, compat: compatibility(user, vector, axisIds), vector }; }); scored.sort(byScore); return scored.filter((item) => allows(item.row.religions, pref)).map((item) => toIdeologyMatch(item.row, item.compat)); } /** Homepage preview: rank only modern countries, project only the top five. */ export function rankCurrentCountries(catalog: import('./catalog').CountryCatalog, user: Vector, axisIds: string[]): CountryMatch[] { return catalog.countries.filter(row => !row.historical && allows(row.religions, normalizeReligion(null))).map(row => { const profile = catalog.countryVectors.get(row.id); const vector = fillVector(profile && Object.keys(profile).length ? profile : row.vector, axisIds); return { row, vector, compat: compatibility(user, vector, axisIds) }; }).sort(byScore).slice(0, 5).map(item => toCountryMatch(item.row, item.compat, item.vector)); } export function rankCountries( catalog: Catalog, user: Vector, religion?: string | null, axisIds: string[] = axisIdsOf(catalog) ): CountryMatch[] { const pref = normalizeReligion(religion ?? null); const scored: Scored[] = catalog.countries.map((row) => { const vector = targetVector(catalog, 'country', row.id, axisIds); return { row, compat: compatibility(user, vector, axisIds), vector }; }); scored.sort(byScore); return scored .filter((item) => allows(item.row.religions, pref)) .map((item) => toCountryMatch(item.row, item.compat, item.vector)); } export function rankPersonalities( catalog: Catalog, user: Vector, religion?: string | null, axisIds: string[] = axisIdsOf(catalog) ): PersonalityMatch[] { const pref = normalizeReligion(religion ?? null); const scored: Scored[] = catalog.personalities.map((row) => { const vector = targetVector(catalog, 'personality', row.id, axisIds); return { row, compat: compatibility(user, vector, axisIds), vector }; }); scored.sort(byScore); return scored .filter((item) => allows(item.row.religions, pref)) .map((item) => toPersonalityMatch(item.row, item.compat, item.vector)); } export function rankParties( catalog: Catalog, user: Vector, religion?: string | null, axisIds: string[] = axisIdsOf(catalog) ): PartyMatch[] { const pref = normalizeReligion(religion ?? null); const countries = countryIndex(catalog); const scored: Scored[] = catalog.parties.map((row) => { const vector = targetVector(catalog, 'party', row.id, axisIds); return { row, compat: compatibility(user, vector, axisIds), vector }; }); scored.sort(byScore); return scored .filter((item) => allows(item.row.religions, pref)) .map((item) => toPartyMatch(item.row, item.compat, item.vector, countries)); } /** `ProfileSpectrumService.categoryOf`: categoria da ideologia mais próxima do vetor (sem filtro). */ export function spectrumOf(catalog: Catalog, vector: Vector, axisIds: string[] = axisIdsOf(catalog)): string { return rankIdeologies(catalog, vector, null, axisIds)[0]?.category ?? ''; } // --------------------------------------------------------------------------- // CompareItem (CompareService.buildCatalog) // --------------------------------------------------------------------------- function personalityItem(row: RawPersonality): CompareItem { return { type: 'personality', id: row.id, name: row.name, caption: row.role, imagePath: row.imagePath, category: row.category, historical: false }; } function countryItem(row: RawCountry): CompareItem { const caption = row.historical && row.period && row.period.trim() ? row.period : row.category; return { type: 'country', id: row.id, name: row.name, caption, imagePath: row.flagPath, category: row.category, historical: row.historical }; } function ideologyItem(row: RawIdeology): CompareItem { return { type: 'ideology', id: row.id, name: row.name, caption: row.category, imagePath: null, category: row.category, historical: false }; } function partyItem(row: RawParty, countries: Map): CompareItem { const country = countries.get(row.countryId)?.name ?? ''; const caption = row.historical && row.period && row.period.trim() ? `${country} · ${row.period}` : country; return { type: 'party', id: row.id, name: row.name, caption, imagePath: row.logoPath, category: row.category, historical: row.historical }; } // --------------------------------------------------------------------------- // Resolução de um perfil (CompareService.resolve) // --------------------------------------------------------------------------- interface Resolved { item: CompareItem; description: string; vector: Vector; religions: string[]; } const VALID_TYPES: readonly CompareType[] = ['personality', 'country', 'ideology', 'party']; function asType(raw: string): CompareType { if ((VALID_TYPES as readonly string[]).includes(raw)) return raw as CompareType; throw new Error(`Invalid comparison type: ${raw}`); } function cleanReligions(religions: readonly string[] | null | undefined): string[] { return (religions ?? []).filter((value) => value !== ONLY); } function resolveProfile(catalog: Catalog, type: CompareType, id: string, axisIds: string[]): Resolved { switch (type) { case 'personality': { const row = catalog.personalities.find((item) => item.id === id); if (!row) throw new Error(`Profile not found: ${type}/${id}`); return { item: personalityItem(row), description: row.description, vector: targetVector(catalog, 'personality', id, axisIds), religions: cleanReligions(row.religions) }; } case 'country': { const row = catalog.countries.find((item) => item.id === id); if (!row) throw new Error(`Profile not found: ${type}/${id}`); return { item: countryItem(row), description: row.description, vector: targetVector(catalog, 'country', id, axisIds), religions: cleanReligions(row.religions) }; } case 'ideology': { const row = catalog.ideologies.find((item) => item.id === id); if (!row) throw new Error(`Profile not found: ${type}/${id}`); return { item: ideologyItem(row), description: row.description, vector: targetVector(catalog, 'ideology', id, axisIds), religions: cleanReligions(row.religions) }; } case 'party': { const row = catalog.parties.find((item) => item.id === id); if (!row) throw new Error(`Profile not found: ${type}/${id}`); return { item: partyItem(row, countryIndex(catalog)), description: row.description, vector: targetVector(catalog, 'party', id, axisIds), religions: cleanReligions(row.religions) }; } default: throw new Error(`Invalid comparison type: ${String(type)}`); } } function isSelf(self: { type: CompareType; id: string }, type: CompareType, id: string): boolean { return self.type === type && self.id === id; } function nearest( catalog: Catalog, self: { type: CompareType; id: string }, vector: Vector, axisIds: string[] ): CompareNearest { const ideology = rankIdeologies(catalog, vector, null, axisIds).find( (match) => !isSelf(self, 'ideology', match.ideologyId) ); const country = rankCountries(catalog, vector, null, axisIds).find( (match) => !isSelf(self, 'country', match.countryId) ); const party = rankParties(catalog, vector, null, axisIds).find( (match) => !isSelf(self, 'party', match.partyId) ); return { ideology: ideology ?? null, country: country ?? null, party: party ?? null }; } function commonIdeology( catalog: Catalog, refs: Array<{ type: CompareType; id: string }>, resolved: Resolved[], axisIds: string[] ): IdeologyMatch | null { const mean: Vector = {}; for (const axis of catalog.axes) { mean[axis.id] = resolved.reduce((sum, item) => sum + (item.vector[axis.id] ?? CENTER), 0) / resolved.length; } const inComparison = new Set(refs.filter((ref) => ref.type === 'ideology').map((ref) => ref.id)); return rankIdeologies(catalog, mean, null, axisIds).find((match) => !inComparison.has(match.ideologyId)) ?? null; } // --------------------------------------------------------------------------- // API pública (assinaturas exigidas por services/quizApi.ts e premiumApi.ts) // --------------------------------------------------------------------------- /** `GET /api/compare/catalog`: catálogo inteiro, sem filtro de religião. */ export async function compareCatalog(): Promise { const catalog = await getCatalog(); const countries = countryIndex(catalog); return [ ...catalog.personalities.map(personalityItem), ...catalog.countries.map(countryItem), ...catalog.ideologies.map(ideologyItem), ...catalog.parties.map((row) => partyItem(row, countries)) ]; } /** `GET /api/compare`: usuário (12 leftPercents) × um perfil do catálogo. */ export async function compareDetail(type: CompareType, id: string, leftPercents: number[]): Promise { const catalog = await getCatalog(); const axisIds = axisIdsOf(catalog); const user = vectorFromLeftPercents(catalog.axes, leftPercents); const resolved = resolveProfile(catalog, type, id, axisIds); return { item: resolved.item, description: resolved.description, compatibility: compatibility(user, resolved.vector, axisIds), vector: resolved.vector, religions: resolved.religions, spectrum: spectrumOf(catalog, resolved.vector, axisIds) }; } /** `GET /api/compare/profiles`: 1 a 3 perfis, pares (i): Promise { const catalog = await getCatalog(); const axisIds = axisIdsOf(catalog); if (refs.length < 1 || refs.length > 3) { throw new Error('Informe de 1 a 3 perfis para comparar'); } const typed = refs.map((ref) => ({ type: asType(ref.type), id: ref.id })); const resolved = typed.map((ref) => resolveProfile(catalog, ref.type, ref.id, axisIds)); const profiles: CompareProfile[] = resolved.map((item, index) => ({ item: item.item, vector: item.vector, nearest: nearest(catalog, typed[index], item.vector, axisIds) })); const pairs: ComparePair[] = []; for (let i = 0; i < profiles.length; i += 1) { for (let j = i + 1; j < profiles.length; j += 1) { pairs.push({ first: i, second: j, compatibility: compatibility(profiles[i].vector, profiles[j].vector, axisIds) }); } } return { profiles, pairs, commonIdeology: commonIdeology(catalog, typed, resolved, axisIds) }; } // FILE: src/core/quiz.ts /** * Montagem do quiz 100% estática (sem backend). * * Porto de `QuizDataService.getQuiz` e dos resolvers que ele aplica às perguntas * (`GlossaryResolver`, `QuestionHelpResolver`) e de `ArchetypeQuestion.view`. * Todos os dados vêm de `getQuizCatalog()` (the five questionnaire JSON files in `public/data`); nenhum * endpoint REST é chamado e nenhum dado de negócio é hardcoded. As únicas constantes * locais são as do enum `AnswerValue` e os rótulos de `labelFor`, que no Java * também vivem no código (não existem em nenhum arquivo de dados). * * Diferenças em relação ao Java (documentadas no relatório final): * - `normalizeVariant` só recebe `QuizVariant` (a união do contrato), então os * apelidos "curta"/"extensa"/"240" etc. não aparecem; o resultado é o mesmo * para os três valores válidos. * - `ArchetypeQuestion` mantém `icon`/`layout`/`wide` quando existem no catálogo * (o `view()` do Java os descarta). O catálogo atual não traz nenhum deles, e * os `effects` usados no cálculo são exatamente os mesmos. * - Idioma fixo em inglês: é o idioma dos arquivos de dados e o default do backend. */ import { en, getQuizCatalog, type RawArchetypeQuestion, type RawGlossaryTerm } from './catalog'; import type { AnswerOption, AnswerValue, ArchetypeQuestion, Axis, Question, QuestionHelp, QuestionIcon, QuestionTerm, QuizPayload, QuizVariant } from '../types/quiz'; // --------------------------------------------------------------------------- // AnswerValue.java + QuizDataService.answerOptions/labelFor // --------------------------------------------------------------------------- /** `AnswerValue.scoreTowardAgreement()` na ordem de `AnswerValue.values()`. */ const SCORE_TOWARD_AGREEMENT: Record = { STRONGLY_AGREE: 1.0, AGREE: 0.75, NEUTRAL: 0.5, DISAGREE: 0.25, STRONGLY_DISAGREE: 0.0 }; const ANSWER_OPTIONS: AnswerOption[] = [ { id: 'STRONGLY_AGREE', label: 'Strongly agree', scoreTowardAgreement: 1.0 }, { id: 'AGREE', label: 'Agree', scoreTowardAgreement: 0.75 }, { id: 'NEUTRAL', label: 'Neutral or It depends', scoreTowardAgreement: 0.5 }, { id: 'DISAGREE', label: 'Disagree', scoreTowardAgreement: 0.25 }, { id: 'STRONGLY_DISAGREE', label: 'Strongly disagree', scoreTowardAgreement: 0.0 } ]; // --------------------------------------------------------------------------- // QuizDataService.normalizeVariant / getQuiz // --------------------------------------------------------------------------- function normalizeVariant(variant: QuizVariant): QuizVariant { if (variant === 'extended' || variant === 'extreme') return variant; return 'short'; } function questionsPerAxisFor(variant: QuizVariant): number { if (variant === 'extreme') return 0; if (variant === 'extended') return 5; return 3; } // --------------------------------------------------------------------------- // GlossaryResolver.java — termos do glossário no texto, maior trecho primeiro // --------------------------------------------------------------------------- interface GlossaryCandidate { pattern: RegExp; length: number; entryId: string; term: string; definition: string; } function escapeRegex(literal: string): string { return literal.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); } function glossaryCandidates(glossary: RawGlossaryTerm[]): GlossaryCandidate[] { const candidates: GlossaryCandidate[] = []; for (const entry of glossary) { for (const match of entry.match) { // Mesmo padrão do Java: palavra inteira, case-insensitive, Unicode. candidates.push({ pattern: new RegExp(`(? b.length - a.length); } function overlaps(found: QuestionTerm[], start: number, end: number): boolean { return found.some((term) => start < term.end && term.start < end); } function findGlossaryTerms(text: string, candidates: GlossaryCandidate[]): QuestionTerm[] { const found: QuestionTerm[] = []; const usedEntries = new Set(); for (const candidate of candidates) { if (usedEntries.has(candidate.entryId)) continue; // `Matcher.find()` percorre todas as ocorrências até achar uma que não // sobreponha um termo já escolhido; a primeira serve e a entrada sai da lista. const regex = new RegExp(candidate.pattern.source, 'giu'); let match: RegExpExecArray | null; while ((match = regex.exec(text)) !== null) { if (match[0].length === 0) { regex.lastIndex += 1; continue; } const start = match.index; const end = start + match[0].length; if (overlaps(found, start, end)) continue; found.push({ start, end, term: candidate.term, definition: candidate.definition }); usedEntries.add(candidate.entryId); break; } } return found.sort((a, b) => a.start - b.start); } // --------------------------------------------------------------------------- // QuestionHelpResolver.java — ajuda por id, campos em branco viram null // --------------------------------------------------------------------------- function orNull(value: string | null | undefined): string | null { if (value == null || value.trim() === '') return null; return value; } // --------------------------------------------------------------------------- // ArchetypeQuestion.view — textos em inglês, efeitos não vão para o payload // --------------------------------------------------------------------------- function toArchetypeQuestion(raw: RawArchetypeQuestion): ArchetypeQuestion { const question: ArchetypeQuestion = { id: raw.id, label: en(raw.label), text: en(raw.text), options: raw.options.map((option) => { const mapped: ArchetypeQuestion['options'][number] = { id: option.id, text: en(option.text) }; if (option.icon) mapped.icon = option.icon as QuestionIcon; if (option.wide) mapped.wide = true; return mapped; }) }; if (raw.icon) question.icon = raw.icon as QuestionIcon; if (raw.layout) question.layout = raw.layout; return question; } // --------------------------------------------------------------------------- // API pública // --------------------------------------------------------------------------- /** * Equivale ao endpoint de quiz do backend: devolve o pool COMPLETO de perguntas * (o front faz o recorte balanceado por variante), os 12 eixos, as opções de resposta e * as perguntas de arquétipo. `questionCount` é o número exibido, não o tamanho * do pool — exatamente como em `QuizDataService.getQuiz`. */ export async function buildQuiz(variant: QuizVariant): Promise { const catalog = await getQuizCatalog(); const normalizedVariant = normalizeVariant(variant); const questionsPerAxis = questionsPerAxisFor(normalizedVariant); const questionCount = normalizedVariant === 'extreme' ? catalog.questions.length : questionsPerAxis * catalog.axes.length; const description = `A quiz of ${questionCount} questions to estimate your position on the 12 political axes.`; const axes: Axis[] = catalog.axes.map((axis) => ({ id: axis.id, label: axis.label, leftPole: axis.leftPole, rightPole: axis.rightPole, leftColor: axis.leftColor, rightColor: axis.rightColor })); const candidates = glossaryCandidates(catalog.glossary); const helpById = new Map(catalog.help.map((entry) => [entry.id, entry])); const questions: Question[] = catalog.questions.map((raw) => { const helpEntry = helpById.get(raw.id); const help: QuestionHelp | null = helpEntry ? { agree: helpEntry.agree, disagree: helpEntry.disagree, note: orNull(helpEntry.note), agreeExample: orNull(helpEntry.agreeExample), disagreeExample: orNull(helpEntry.disagreeExample) } : null; return { id: raw.id, axisId: raw.axisId, text: raw.text, agreePole: raw.agreePole, weight: raw.weight, terms: findGlossaryTerms(raw.text, candidates), help }; }); return { title: '12 Axes', description, variant: normalizedVariant, questionCount, questionsPerAxis, axes, questions, answerOptions: ANSWER_OPTIONS.map((option) => ({ ...option })), archetypeQuestions: catalog.archetypeQuestions.map(toArchetypeQuestion) }; } /** Reexportado para `scoring.ts`: os valores de concordância do enum Java. */ export function scoreTowardAgreement(answer: AnswerValue): number { return SCORE_TOWARD_AGREEMENT[answer]; }