refactor: Refactor cv-matcher.js to use shared utilities (Step 3 of 6)

Refactored cv-matcher.js from 257 → 213 lines (17% reduction) by:
- Removing duplicate helper functions now in utils/form-helpers.js
- Removing duplicate i18n logic now in utils/i18n.js
- Removing API loading code now in utils/api.js

Kept CV matcher-specific logic:
- CV file input change handler
- Async CV upload and match flow with two captcha tokens
- Match result rendering with score badge and lists
- escapeHtml() XSS prevention utility
- $(window).on('load') to load reCaptcha

All function calls updated to use window.MyAi.* utilities for consistency.
Added detailed JSDoc comments explaining the two-step async flow.

Updated cv-matcher/index.html to load all utilities before cv-matcher.js.

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
This commit is contained in:
2026-05-29 09:13:22 +03:00
parent ce05426452
commit 0742694900
2 changed files with 60 additions and 99 deletions
+4
View File
@@ -221,6 +221,10 @@
<a href="#" id="cookieManage" class="cookie-manage btn btn-dark btn-sm shadow" data-i18n="cookies.settings">Cookie settings</a> <a href="#" id="cookieManage" class="cookie-manage btn btn-dark btn-sm shadow" data-i18n="cookies.settings">Cookie settings</a>
<script src="/js/vendor/jquery-4.0.0.min.js"></script> <script src="/js/vendor/jquery-4.0.0.min.js"></script>
<script src="/js/i18n.js"></script> <script src="/js/i18n.js"></script>
<script src="/js/utils/form-helpers.js"></script>
<script src="/js/utils/i18n.js"></script>
<script src="/js/utils/api.js"></script>
<script src="/js/modules/cookie-consent.js"></script>
<script src="/js/main.js"></script> <script src="/js/main.js"></script>
<script src="/js/cv-matcher.js"></script> <script src="/js/cv-matcher.js"></script>
</body> </body>
+56 -99
View File
@@ -2,70 +2,32 @@
* MyAi CV Matcher Form * MyAi CV Matcher Form
* *
* Handles CV upload, job description input, and match result rendering. * Handles CV upload, job description input, and match result rendering.
* Depends on: jQuery, i18n.js, main.js (for shared utilities) * Uses shared utilities from: utils/form-helpers.js, utils/i18n.js, utils/api.js
*
* Depends on: jQuery, i18n.js (translation dict), shared utility modules
*/ */
(function ($) { (function ($) {
"use strict"; "use strict";
var reCaptchaSiteKey = null; /* ============================================================
var LANG_KEY = "myai_lang"; CV FILE INPUT HANDLER
============================================================ */
/**
* Retrieve translation by key.
* Falls back to English if key not found in current language.
*/
function t(key) {
var lang = localStorage.getItem(LANG_KEY) || 'en';
return (window.MyAi.i18n[lang] && window.MyAi.i18n[lang][key]) ||
window.MyAi.i18n.en[key] || key;
}
/**
* Get current language from localStorage or detect from browser.
*/
function currentLang() {
return localStorage.getItem(LANG_KEY) ||
(((navigator.language || navigator.userLanguage || 'en').toLowerCase().indexOf('ro') === 0) ? 'ro' : 'en');
}
/**
* Display field error message and mark container with is-invalid class.
*/
function showFieldError(errorId, msg) {
var $el = $('#' + errorId);
$el.text(msg || '');
var $parent = $el.parent();
var $container = $parent.is('label, .consent-inline') ? $parent : $el.prev();
if (!$container.length || !$container.is('label, .consent-inline, .file-drop, .subscribe-row')) {
$container = $el.closest('form');
}
$container.toggleClass('is-invalid', !!msg);
}
/**
* Clear multiple field errors at once.
*/
function clearFieldErrors(errorIds) {
for (var i = 0; i < errorIds.length; i++) showFieldError(errorIds[i], '');
}
/**
* Validate email format with simple regex.
*/
function isValidEmail(value) {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(value || '').trim());
}
/** /**
* Update displayed CV filename when file is selected. * Update displayed CV filename when file is selected.
*/ */
$('#cvFile').on('change', function () { $('#cvFile').on('change', function () {
var file = this.files && this.files[0]; var file = this.files && this.files[0];
$('#cvFileName').text(file ? file.name : t('cv.fileHint')); $('#cvFileName').text(file ? file.name : window.MyAi.t('cv.fileHint'));
}); });
/* ============================================================
CV MATCHER FORM HANDLER
============================================================ */
/** /**
* Handle CV Matcher form submission. * Handle CV Matcher form submission with async upload and match flow.
* Requires reCaptcha verification for both CV upload and match actions.
*/ */
$('#cvMatcherForm').on('submit', async function (event) { $('#cvMatcherForm').on('submit', async function (event) {
event.preventDefault(); event.preventDefault();
@@ -78,38 +40,39 @@
$button = $('#matchSubmit'), $button = $('#matchSubmit'),
$result = $('#matchResult'); $result = $('#matchResult');
clearFieldErrors(['cvFileError', 'cvJobError', 'cvConsentError']); window.MyAi.clearFieldErrors(['cvFileError', 'cvJobError', 'cvConsentError']);
$msg.removeClass().addClass('form-message').text(''); $msg.removeClass().addClass('form-message').text('');
// Validate inputs // Validate inputs
var hasError = false; var hasError = false;
if (!file) { showFieldError('cvFileError', t('cv.noFile')); hasError = true; } if (!file) { window.MyAi.showFieldError('cvFileError', window.MyAi.t('cv.noFile')); hasError = true; }
if (!jobUrl && !jobDescription) { showFieldError('cvJobError', t('cv.noJob')); hasError = true; } if (!jobUrl && !jobDescription) { window.MyAi.showFieldError('cvJobError', window.MyAi.t('cv.noJob')); hasError = true; }
if (!consent) { showFieldError('cvConsentError', t('cv.noConsent')); hasError = true; } if (!consent) { window.MyAi.showFieldError('cvConsentError', window.MyAi.t('cv.noConsent')); hasError = true; }
if (hasError) return; if (hasError) return;
var $cvLoader = $('#cvLoader'); var $cvLoader = $('#cvLoader');
$button.prop('disabled', true).text(t('cv.processing')); $button.prop('disabled', true).text(window.MyAi.t('cv.processing'));
$msg.removeClass().addClass('form-message').text(t('cv.extracting')); $msg.removeClass().addClass('form-message').text(window.MyAi.t('cv.extracting'));
$result.html('<div class="empty-result">' + escapeHtml(t('cv.processingLong')) + '</div>'); $result.html('<div class="empty-result">' + escapeHtml(window.MyAi.t('cv.processingLong')) + '</div>');
$cvLoader.addClass('loader-visible'); $cvLoader.addClass('loader-visible');
// Require reCaptcha and get CV upload token // Require reCaptcha and get CV upload token
if (window.grecaptcha && reCaptchaSiteKey) { if (window.grecaptcha && window.MyAi.getReCaptchaSiteKey()) {
grecaptcha.ready(function () { grecaptcha.ready(function () {
grecaptcha.execute(reCaptchaSiteKey, { grecaptcha.execute(window.MyAi.getReCaptchaSiteKey(), {
action: 'cv_upload' action: 'cv_upload'
}).then(postCv); }).then(postCv);
}); });
} else { } else {
$cvLoader.removeClass('loader-visible'); $cvLoader.removeClass('loader-visible');
$msg.removeClass().addClass('form-message text-danger').text(t('form.captchaFailed')); $msg.removeClass().addClass('form-message text-danger').text(window.MyAi.t('form.captchaFailed'));
$button.prop('disabled', false).text(t('cv.submit')); $button.prop('disabled', false).text(window.MyAi.t('cv.submit'));
return; return;
} }
/** /**
* Upload CV and request match score. * Upload CV and request match score.
* Two-step process: upload CV PDF, then submit match request with fresh captcha token.
*/ */
async function postCv(token) { async function postCv(token) {
try { try {
@@ -125,18 +88,18 @@
if (!cvResponse.ok) { if (!cvResponse.ok) {
var cvErrBody = null; var cvErrBody = null;
try { cvErrBody = await cvResponse.json(); } catch (_) {} try { cvErrBody = await cvResponse.json(); } catch (_) {}
throw new Error(extractApiError(cvErrBody, cvResponse.status, 'cv.cvFailed', 'cv.rateLimited')); throw new Error(window.MyAi.extractApiError(cvErrBody, cvResponse.status, 'cv.cvFailed', 'cv.rateLimited'));
} }
var cvData = await cvResponse.json(); var cvData = await cvResponse.json();
// Get fresh captcha token for match action // Get fresh captcha token for match action
if (!(window.grecaptcha && reCaptchaSiteKey)) { if (!(window.grecaptcha && window.MyAi.getReCaptchaSiteKey())) {
throw new Error(t('form.captchaFailed')); throw new Error(window.MyAi.t('form.captchaFailed'));
} }
var matchToken = await new Promise(function (resolve, reject) { var matchToken = await new Promise(function (resolve, reject) {
try { try {
grecaptcha.ready(function () { grecaptcha.ready(function () {
grecaptcha.execute(reCaptchaSiteKey, { action: 'match_job' }).then(resolve).catch(reject); grecaptcha.execute(window.MyAi.getReCaptchaSiteKey(), { action: 'match_job' }).then(resolve).catch(reject);
}); });
} catch (e) { reject(e); } } catch (e) { reject(e); }
}); });
@@ -154,36 +117,41 @@
email: matchEmail, email: matchEmail,
gdprConsent: consent, gdprConsent: consent,
captchaToken: matchToken, captchaToken: matchToken,
language: currentLang() language: window.MyAi.currentLang()
}) })
}); });
if (!matchResponse.ok) { if (!matchResponse.ok) {
var matchErrBody = null; var matchErrBody = null;
try { matchErrBody = await matchResponse.json(); } catch (_) {} try { matchErrBody = await matchResponse.json(); } catch (_) {}
throw new Error(extractApiError(matchErrBody, matchResponse.status, 'cv.matchFailed', 'cv.rateLimited')); throw new Error(window.MyAi.extractApiError(matchErrBody, matchResponse.status, 'cv.matchFailed', 'cv.rateLimited'));
} }
var match = await matchResponse.json(); var match = await matchResponse.json();
renderMatchResult(match); renderMatchResult(match);
$msg.removeClass().addClass('form-message text-success').text(t('cv.completed')); $msg.removeClass().addClass('form-message text-success').text(window.MyAi.t('cv.completed'));
} catch (err) { } catch (err) {
console.error(err); console.error(err);
var isRateLimited = err && err.message === t('cv.rateLimited'); var isRateLimited = err && err.message === window.MyAi.t('cv.rateLimited');
var tone = isRateLimited ? 'text-warning' : 'text-danger'; var tone = isRateLimited ? 'text-warning' : 'text-danger';
$msg.removeClass().addClass('form-message ' + tone).text(err.message || t('cv.matchFailed')); $msg.removeClass().addClass('form-message ' + tone).text(err.message || window.MyAi.t('cv.matchFailed'));
$result.html('<div class="empty-result">' + escapeHtml(isRateLimited ? t('cv.rateLimited') : t('cv.backendMissing')) + '</div>'); $result.html('<div class="empty-result">' + escapeHtml(isRateLimited ? window.MyAi.t('cv.rateLimited') : window.MyAi.t('cv.backendMissing')) + '</div>');
} finally { } finally {
$cvLoader.removeClass('loader-visible'); $cvLoader.removeClass('loader-visible');
$button.prop('disabled', false).text(t('cv.submit')); $button.prop('disabled', false).text(window.MyAi.t('cv.submit'));
} }
} }
}); });
/* ============================================================
MATCH RESULT RENDERING
============================================================ */
/** /**
* Render CV match result into #matchResult panel. * Render CV match result into #matchResult panel.
* Displays match score percentage, summary, strengths, gaps, and evidence excerpts.
*/ */
function renderMatchResult(match) { function renderMatchResult(match) {
var score = match.score || match.matchScore || 0; var score = match.score || match.matchScore || 0;
var summary = match.summary || t('cv.noSummary'); var summary = match.summary || window.MyAi.t('cv.noSummary');
var strengths = match.strengths || []; var strengths = match.strengths || [];
var gaps = match.gaps || match.missingSkills || []; var gaps = match.gaps || match.missingSkills || [];
var evidence = match.evidence || match.retrievedChunks || []; var evidence = match.evidence || match.retrievedChunks || [];
@@ -193,7 +161,7 @@
*/ */
function list(items) { function list(items) {
if (!items || !items.length) { if (!items || !items.length) {
return '<p class="empty-result">' + escapeHtml(t('cv.noItems')) + '</p>'; return '<p class="empty-result">' + escapeHtml(window.MyAi.t('cv.noItems')) + '</p>';
} }
return '<ul class="result-list">' + items.map(function (x) { return '<ul class="result-list">' + items.map(function (x) {
var text = typeof x === 'string' ? x : (x.text || x.title || JSON.stringify(x)); var text = typeof x === 'string' ? x : (x.text || x.title || JSON.stringify(x));
@@ -204,14 +172,19 @@
$('#matchResult').html( $('#matchResult').html(
'<div class="score-badge">' + Number(score).toFixed(0) + '%</div>' + '<div class="score-badge">' + Number(score).toFixed(0) + '%</div>' +
'<p>' + escapeHtml(summary) + '</p>' + '<p>' + escapeHtml(summary) + '</p>' +
'<h3>' + t('cv.strengths') + '</h3>' + list(strengths) + '<h3>' + window.MyAi.t('cv.strengths') + '</h3>' + list(strengths) +
'<h3>' + t('cv.gaps') + '</h3>' + list(gaps) + '<h3>' + window.MyAi.t('cv.gaps') + '</h3>' + list(gaps) +
'<h3>' + t('cv.evidence') + '</h3>' + list(evidence) '<h3>' + window.MyAi.t('cv.evidence') + '</h3>' + list(evidence)
); );
} }
/* ============================================================
UTILITY FUNCTIONS
============================================================ */
/** /**
* Escape HTML special characters to prevent XSS. * Escape HTML special characters to prevent XSS.
* Replaces &, <, >, ", ' with their HTML entity equivalents.
*/ */
function escapeHtml(value) { function escapeHtml(value) {
return String(value).replace(/[&<>'"]/g, function (char) { return String(value).replace(/[&<>'"]/g, function (char) {
@@ -225,32 +198,16 @@
}); });
} }
/** /* ============================================================
* Extract user-facing error message from failed API response. API CONFIGURATION LOADING (from utils/api.js)
* For 4xx: show server's error field (intentional user feedback). ============================================================ */
* For 5xx or missing body: show generic i18n fallback.
*/
function extractApiError(body, status, fallbackKey, rateLimitKey) {
if (status === 429) return t(rateLimitKey || 'form.rateLimited');
var msg = body && (body.error || body.Error || body.title);
return (status >= 400 && status < 500 && msg) ? msg : t(fallbackKey);
}
/** /**
* Load reCaptcha site key on page load (needed for CV upload). * Load reCaptcha site key on page load (needed for CV upload).
* Uses shared utility: window.MyAi.getRecaptchaWebKey()
*/ */
$(window).on('load', function () { $(window).on('load', function () {
$.get('/api/captcha').done(function (res) { window.MyAi.getRecaptchaWebKey();
reCaptchaSiteKey = res;
if (reCaptchaSiteKey && !window.__recaptcha_loaded) {
window.__recaptcha_loaded = true;
var script = document.createElement('script');
script.setAttribute('src', 'https://www.google.com/recaptcha/api.js?render=' + reCaptchaSiteKey);
document.head.appendChild(script);
}
}).fail(function () {
console.warn('Could not load reCaptcha site key from /api/captcha');
});
}); });
})(jQuery); })(jQuery);