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:
@@ -2,70 +2,32 @@
|
||||
* MyAi CV Matcher Form
|
||||
*
|
||||
* 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 ($) {
|
||||
"use strict";
|
||||
|
||||
var reCaptchaSiteKey = null;
|
||||
var LANG_KEY = "myai_lang";
|
||||
|
||||
/**
|
||||
* 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());
|
||||
}
|
||||
/* ============================================================
|
||||
CV FILE INPUT HANDLER
|
||||
============================================================ */
|
||||
|
||||
/**
|
||||
* Update displayed CV filename when file is selected.
|
||||
*/
|
||||
$('#cvFile').on('change', function () {
|
||||
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) {
|
||||
event.preventDefault();
|
||||
@@ -78,38 +40,39 @@
|
||||
$button = $('#matchSubmit'),
|
||||
$result = $('#matchResult');
|
||||
|
||||
clearFieldErrors(['cvFileError', 'cvJobError', 'cvConsentError']);
|
||||
window.MyAi.clearFieldErrors(['cvFileError', 'cvJobError', 'cvConsentError']);
|
||||
$msg.removeClass().addClass('form-message').text('');
|
||||
|
||||
// Validate inputs
|
||||
var hasError = false;
|
||||
if (!file) { showFieldError('cvFileError', t('cv.noFile')); hasError = true; }
|
||||
if (!jobUrl && !jobDescription) { showFieldError('cvJobError', t('cv.noJob')); hasError = true; }
|
||||
if (!consent) { showFieldError('cvConsentError', t('cv.noConsent')); hasError = true; }
|
||||
if (!file) { window.MyAi.showFieldError('cvFileError', window.MyAi.t('cv.noFile')); hasError = true; }
|
||||
if (!jobUrl && !jobDescription) { window.MyAi.showFieldError('cvJobError', window.MyAi.t('cv.noJob')); hasError = true; }
|
||||
if (!consent) { window.MyAi.showFieldError('cvConsentError', window.MyAi.t('cv.noConsent')); hasError = true; }
|
||||
if (hasError) return;
|
||||
|
||||
var $cvLoader = $('#cvLoader');
|
||||
$button.prop('disabled', true).text(t('cv.processing'));
|
||||
$msg.removeClass().addClass('form-message').text(t('cv.extracting'));
|
||||
$result.html('<div class="empty-result">' + escapeHtml(t('cv.processingLong')) + '</div>');
|
||||
$button.prop('disabled', true).text(window.MyAi.t('cv.processing'));
|
||||
$msg.removeClass().addClass('form-message').text(window.MyAi.t('cv.extracting'));
|
||||
$result.html('<div class="empty-result">' + escapeHtml(window.MyAi.t('cv.processingLong')) + '</div>');
|
||||
$cvLoader.addClass('loader-visible');
|
||||
|
||||
// Require reCaptcha and get CV upload token
|
||||
if (window.grecaptcha && reCaptchaSiteKey) {
|
||||
if (window.grecaptcha && window.MyAi.getReCaptchaSiteKey()) {
|
||||
grecaptcha.ready(function () {
|
||||
grecaptcha.execute(reCaptchaSiteKey, {
|
||||
grecaptcha.execute(window.MyAi.getReCaptchaSiteKey(), {
|
||||
action: 'cv_upload'
|
||||
}).then(postCv);
|
||||
});
|
||||
} else {
|
||||
$cvLoader.removeClass('loader-visible');
|
||||
$msg.removeClass().addClass('form-message text-danger').text(t('form.captchaFailed'));
|
||||
$button.prop('disabled', false).text(t('cv.submit'));
|
||||
$msg.removeClass().addClass('form-message text-danger').text(window.MyAi.t('form.captchaFailed'));
|
||||
$button.prop('disabled', false).text(window.MyAi.t('cv.submit'));
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload CV and request match score.
|
||||
* Two-step process: upload CV PDF, then submit match request with fresh captcha token.
|
||||
*/
|
||||
async function postCv(token) {
|
||||
try {
|
||||
@@ -125,18 +88,18 @@
|
||||
if (!cvResponse.ok) {
|
||||
var cvErrBody = null;
|
||||
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();
|
||||
|
||||
// Get fresh captcha token for match action
|
||||
if (!(window.grecaptcha && reCaptchaSiteKey)) {
|
||||
throw new Error(t('form.captchaFailed'));
|
||||
if (!(window.grecaptcha && window.MyAi.getReCaptchaSiteKey())) {
|
||||
throw new Error(window.MyAi.t('form.captchaFailed'));
|
||||
}
|
||||
var matchToken = await new Promise(function (resolve, reject) {
|
||||
try {
|
||||
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); }
|
||||
});
|
||||
@@ -154,36 +117,41 @@
|
||||
email: matchEmail,
|
||||
gdprConsent: consent,
|
||||
captchaToken: matchToken,
|
||||
language: currentLang()
|
||||
language: window.MyAi.currentLang()
|
||||
})
|
||||
});
|
||||
if (!matchResponse.ok) {
|
||||
var matchErrBody = null;
|
||||
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();
|
||||
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) {
|
||||
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';
|
||||
$msg.removeClass().addClass('form-message ' + tone).text(err.message || t('cv.matchFailed'));
|
||||
$result.html('<div class="empty-result">' + escapeHtml(isRateLimited ? t('cv.rateLimited') : t('cv.backendMissing')) + '</div>');
|
||||
$msg.removeClass().addClass('form-message ' + tone).text(err.message || window.MyAi.t('cv.matchFailed'));
|
||||
$result.html('<div class="empty-result">' + escapeHtml(isRateLimited ? window.MyAi.t('cv.rateLimited') : window.MyAi.t('cv.backendMissing')) + '</div>');
|
||||
} finally {
|
||||
$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.
|
||||
* Displays match score percentage, summary, strengths, gaps, and evidence excerpts.
|
||||
*/
|
||||
function renderMatchResult(match) {
|
||||
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 gaps = match.gaps || match.missingSkills || [];
|
||||
var evidence = match.evidence || match.retrievedChunks || [];
|
||||
@@ -193,7 +161,7 @@
|
||||
*/
|
||||
function list(items) {
|
||||
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) {
|
||||
var text = typeof x === 'string' ? x : (x.text || x.title || JSON.stringify(x));
|
||||
@@ -204,14 +172,19 @@
|
||||
$('#matchResult').html(
|
||||
'<div class="score-badge">' + Number(score).toFixed(0) + '%</div>' +
|
||||
'<p>' + escapeHtml(summary) + '</p>' +
|
||||
'<h3>' + t('cv.strengths') + '</h3>' + list(strengths) +
|
||||
'<h3>' + t('cv.gaps') + '</h3>' + list(gaps) +
|
||||
'<h3>' + t('cv.evidence') + '</h3>' + list(evidence)
|
||||
'<h3>' + window.MyAi.t('cv.strengths') + '</h3>' + list(strengths) +
|
||||
'<h3>' + window.MyAi.t('cv.gaps') + '</h3>' + list(gaps) +
|
||||
'<h3>' + window.MyAi.t('cv.evidence') + '</h3>' + list(evidence)
|
||||
);
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
UTILITY FUNCTIONS
|
||||
============================================================ */
|
||||
|
||||
/**
|
||||
* Escape HTML special characters to prevent XSS.
|
||||
* Replaces &, <, >, ", ' with their HTML entity equivalents.
|
||||
*/
|
||||
function escapeHtml(value) {
|
||||
return String(value).replace(/[&<>'"]/g, function (char) {
|
||||
@@ -225,32 +198,16 @@
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract user-facing error message from failed API response.
|
||||
* 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);
|
||||
}
|
||||
/* ============================================================
|
||||
API CONFIGURATION LOADING (from utils/api.js)
|
||||
============================================================ */
|
||||
|
||||
/**
|
||||
* Load reCaptcha site key on page load (needed for CV upload).
|
||||
* Uses shared utility: window.MyAi.getRecaptchaWebKey()
|
||||
*/
|
||||
$(window).on('load', function () {
|
||||
$.get('/api/captcha').done(function (res) {
|
||||
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');
|
||||
});
|
||||
window.MyAi.getRecaptchaWebKey();
|
||||
});
|
||||
|
||||
})(jQuery);
|
||||
|
||||
Reference in New Issue
Block a user