chore: post-review cleanup (3 Important + dead code purge -116 lines) (#10)
Some checks are pending
Deploy site to GitHub Pages / deploy (push) Waiting to run

This commit is contained in:
serge 2026-05-07 18:37:10 +03:00
parent e14b0ff01a
commit 2774c25a61
5 changed files with 93 additions and 209 deletions

View File

@ -55,7 +55,7 @@ Dans **Paramètres → Stockage et bases de données → Bindings KV** :
3. Namespace : **Créer** un nouveau namespace nommé `mva-welcome-tracker`
4. Sauvegarder
Si déployé via `wrangler` : mettre à jour `wrangler.toml` avec l'ID du namespace KV créé (remplacer `REPLACE_AT_DEPLOY_TIME`).
Si déployé via `wrangler` : `wrangler.toml` contient déjà l'ID du namespace KV (`c02656ba22064923ab1c6db06b0f4a56` sur le compte CF `sergemind4s@gmail.com`). Pour un autre compte, recréer le namespace via `wrangler kv namespace create WELCOME_KV` puis remplacer l'ID dans `wrangler.toml`.
### 4. Vérifier le scope HubSpot

View File

@ -35,8 +35,6 @@
// ============================================================
const HUBSPOT_API = 'https://api.hubapi.com';
const HUBSPOT_PORTAL_ID = '148163754';
const HUBSPOT_FORM_GUID = '1d9b75c9-8b60-4966-aa18-4bf503452e9a';
const corsHeaders = {
'Access-Control-Allow-Origin' : '*',
@ -271,43 +269,6 @@ export default {
}
}
// ── action: listSubscriptions (debug : trouver les IDs) ──
if (action === 'listSubscriptions') {
// Endpoint legacy email/public/v1 nécessite scope content au lieu de
// communication_preferences (que notre token n'a pas)
const r = await fetch(`${HUBSPOT_API}/email/public/v1/subscriptions`, {
headers: { 'Authorization': `Bearer ${token}` },
});
return jsonResponse(await r.json());
}
// ── action: subscribe ────────────────────────────────────
// Inscrit un contact à un type d'abonnement marketing (déclenche
// l'envoi du mail de double opt-in si DOI activé au niveau compte).
if (action === 'subscribe') {
if (!email || typeof email !== 'string') {
return jsonResponse({ error: 'Email requis' }, 400);
}
const subId = body.subscriptionId;
if (!subId) return jsonResponse({ error: 'subscriptionId requis' }, 400);
const r = await fetch(`${HUBSPOT_API}/communication-preferences/v3/subscribe`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`,
},
body: JSON.stringify({
emailAddress: email.toLowerCase().trim(),
subscriptionId: subId,
legalBasis: 'LEGITIMATE_INTEREST_CLIENT',
legalBasisExplanation: 'Soumission du formulaire MVA Global Fret',
}),
});
const data = await r.text();
return jsonResponse({ status: r.status, body: data });
}
// ── action par défaut : vérification doublon par email ──
if (!email || typeof email !== 'string') {
return jsonResponse({ error: 'Email requis' }, 400);
@ -348,32 +309,46 @@ async function searchContactByEmail(token, email) {
}
async function getNextRef(token) {
const res = await fetch(`${HUBSPOT_API}/crm/v3/objects/contacts/search`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`,
},
body: JSON.stringify({
// Paginate through ALL HubSpot contacts with `reference_client` property to
// find the true numeric maximum. Previous version used `limit: 100` without
// pagination — produced collisions once the contact count exceeded 100
// because HubSpot search results don't guarantee ordering by ref. With
// pagination, we walk the full set: 100 per page × N pages until no more.
// For ~1000 contacts = 10 API calls. Acceptable cost given that this runs
// once per signup confirmation (= rare path).
let maxNum = 0;
let after; // undefined on first iteration
do {
const body = {
filterGroups: [{
filters: [{ propertyName: 'reference_client', operator: 'HAS_PROPERTY' }],
}],
properties: ['reference_client'],
limit: 100,
}),
});
if (!res.ok) {
throw new Error(`HubSpot search failed: ${res.status}`);
}
const data = await res.json();
let maxNum = 0;
(data.results || []).forEach(c => {
const m = (c.properties?.reference_client || '').match(/^MVA-(\d+)$/);
if (m) {
const n = parseInt(m[1], 10);
if (n > maxNum) maxNum = n;
};
if (after) body.after = after;
const res = await fetch(`${HUBSPOT_API}/crm/v3/objects/contacts/search`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`,
},
body: JSON.stringify(body),
});
if (!res.ok) {
throw new Error(`HubSpot search failed: ${res.status}`);
}
});
const data = await res.json();
(data.results || []).forEach(c => {
const m = (c.properties?.reference_client || '').match(/^MVA-(\d+)$/);
if (m) {
const n = parseInt(m[1], 10);
if (n > maxNum) maxNum = n;
}
});
after = data.paging?.next?.after;
} while (after);
return 'MVA-' + String(maxNum + 1).padStart(3, '0');
}

View File

@ -13,9 +13,6 @@
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<link rel="stylesheet" href="css/style.css">
<!-- EmailJS -->
<script src="https://cdn.jsdelivr.net/npm/@emailjs/browser@4/dist/email.min.js"></script>
<style>
.confirmation-shell {
min-height: 100vh;

View File

@ -305,7 +305,6 @@
</div>
</footer>
<script src="https://cdn.jsdelivr.net/npm/@emailjs/browser@4/dist/email.min.js"></script>
<script src="js/translations.js"></script>
<script src="js/main.js"></script>
<script src="js/form-handler.js"></script>

View File

@ -1,33 +1,24 @@
// ============================================
// MVA Global Fret — Form Handler
// HubSpot Portal ID : 148163754
// HubSpot Form GUID : 1d9b75c9-8b60-4966-aa18-4bf503452e9a
// ============================================
// Frontend logic for contact.html (= inscription form):
// - validate inputs + Cloudflare Turnstile token
// - call Cloudflare Worker mva-hubspot-proxy for HubSpot dedup +
// sending verification email (= action requestVerification) or
// "Ravis de vous revoir" email for returning customers (=
// action sendWelcomeBack)
// - reset Turnstile widget after each Worker call (= tokens are
// single-use server-side; without reset, a re-submit silently
// 403s from Cloudflare's siteverify endpoint)
//
// All HubSpot/Resend transactions go through the Worker. No direct
// EmailJS / Formspree / HubSpot Forms API calls from the browser.
// ============================================
const HUBSPOT_PORTAL_ID = '148163754';
const HUBSPOT_FORM_GUID = '1d9b75c9-8b60-4966-aa18-4bf503452e9a';
const FORMSPREE_ID = 'mojrvokp';
// ── EMAILJS (email de bienvenue au client) ────────────────────────────────────
const EMAILJS_PUBLIC_KEY = '8KUlaQ7BDVIbkZRyP';
const EMAILJS_SERVICE_ID = 'service_aeamo3x';
const EMAILJS_TEMPLATE_ID = 'template_s1kr2et';
// Template pour les clients déjà inscrits ("Ravis de te revoir")
// ⚠️ À créer dans EmailJS puis remplacer la valeur ci-dessous
const EMAILJS_TEMPLATE_WELCOME_BACK = 'template_welcome_back';
// Initialisation EmailJS (une seule fois au chargement)
if (typeof emailjs !== 'undefined') {
emailjs.init({ publicKey: EMAILJS_PUBLIC_KEY });
}
// ── PROXY CLOUDFLARE WORKER ───────────────────────────────────────────────────
// URL du Worker qui proxifie l'API HubSpot CRM (contourne le CORS).
// Après déploiement du Worker (voir cloudflare-worker/hubspot-proxy.js),
// remplacer la chaîne vide par l'URL obtenue, ex :
// 'https://mva-hubspot-proxy.moncompte.workers.dev'
// Tant que cette constante est vide, la vérification doublon est désactivée
// (le formulaire s'envoie normalement — aucun blocage).
// ── PROXY CLOUDFLARE WORKER ──────────────────────────────────────
// Worker URL (= deployed via wrangler from cloudflare-worker/).
// CORS Access-Control-Allow-Origin: * so the browser can call it
// directly.
const WORKER_PROXY_URL = 'https://mva-hubspot-proxy.sergemind4s.workers.dev';
document.addEventListener('DOMContentLoaded', () => {
@ -35,33 +26,24 @@ document.addEventListener('DOMContentLoaded', () => {
if (form) setupContactForm(form);
});
// Génération séquentielle via le Worker HubSpot : MVA-001, MVA-002, etc.
// Fallback sur un timestamp court si le Worker est indisponible.
async function generateRefNumber() {
if (WORKER_PROXY_URL) {
try {
const res = await fetch(WORKER_PROXY_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ action: 'nextRef' }),
});
if (res.ok) {
const data = await res.json();
if (data.nextRef) return data.nextRef;
}
} catch { /* fallback ci-dessous */ }
// ── TURNSTILE TOKEN MANAGEMENT ───────────────────────────────────
// Reset the Turnstile widget + global token after each Worker call.
// Cloudflare Turnstile tokens are single-use server-side: a token
// already submitted to siteverify cannot be re-used. Without an
// explicit reset, a re-submit (= same form, same widget) would send
// the now-consumed token and Cloudflare would 403 silently.
function resetTurnstile() {
window.turnstileToken = null;
if (window.turnstile && typeof window.turnstile.reset === 'function') {
try { window.turnstile.reset(); } catch (_) { /* widget absent */ }
}
// Fallback : numéro aléatoire court pour éviter les doublons en cas d'indisponibilité
const rand = String(Math.floor(Math.random() * 900) + 100);
return `MVA-F${rand}`;
}
// Vérifie si l'email existe déjà dans HubSpot via le proxy Cloudflare Worker.
// Retourne les propriétés du contact existant, ou null si nouveau client / proxy non configuré.
// Vérifie si l'email existe déjà dans HubSpot via le proxy Worker.
// Retourne les propriétés du contact existant, ou null si nouveau
// client / Worker indisponible.
async function checkExistingContact(email) {
// Si le proxy n'est pas encore déployé, on laisse passer sans bloquer
if (!WORKER_PROXY_URL) return null;
try {
const res = await fetch(WORKER_PROXY_URL, {
method: 'POST',
@ -72,7 +54,6 @@ async function checkExistingContact(email) {
const data = await res.json();
return data.total > 0 ? data.results[0].properties : null;
} catch {
// Erreur réseau ou Worker indisponible : on laisse passer
return null;
}
}
@ -82,7 +63,7 @@ function setupContactForm(form) {
e.preventDefault();
if (!validateForm(form)) return;
// ── VÉRIFICATION TURNSTILE (CAPTCHA anti-bot) ────────────────────────────
// ── VÉRIFICATION TURNSTILE (CAPTCHA anti-bot) ────────────────
if (!window.turnstileToken) {
const errEl = document.getElementById('formErrorGlobal');
if (errEl) {
@ -91,23 +72,20 @@ function setupContactForm(form) {
}
return;
}
// ─────────────────────────────────────────────────────────────────────────
setLoading(true);
const email = form.email.value.trim();
// ── VÉRIFICATION DOUBLON ──────────────────────────────────────────────────
// Vérifie HubSpot. Comme les contacts ne sont créés QU'APRÈS confirmation
// email, ce check ne retourne que les vrais clients déjà inscrits (pas
// les inscriptions en attente de confirmation).
// ── VÉRIFICATION DOUBLON ─────────────────────────────────────
// Comme les contacts ne sont créés QU'APRÈS confirmation email,
// ce check ne retourne que les vrais clients déjà inscrits.
const existing = await checkExistingContact(email);
if (existing) {
setLoading(false);
showAlreadyRegistered(existing);
return;
}
// ─────────────────────────────────────────────────────────────────────────
const data = {
firstname: form.firstname.value.trim(),
@ -117,10 +95,11 @@ function setupContactForm(form) {
address: form.address.value.trim(),
};
// ── ENVOI VERS LE WORKER ──────────────────────────────────────────────────
// Le Worker stocke les données en KV (24h), envoie un email de validation
// via Brevo. Le contact n'est créé dans HubSpot QUE quand l'utilisateur
// clique sur le lien de confirmation (anti-pollution du CRM).
// ── ENVOI VERS LE WORKER ─────────────────────────────────────
// Le Worker stocke les données en KV (24h) et envoie un email de
// validation via Resend. Le contact n'est créé dans HubSpot QUE
// quand l'utilisateur clique sur le lien de confirmation
// (anti-pollution du CRM).
let ok = false;
try {
const res = await fetch(WORKER_PROXY_URL, {
@ -138,6 +117,8 @@ function setupContactForm(form) {
console.warn('[requestVerification]', err);
}
// Reset Turnstile after the Worker call (= regardless of result)
resetTurnstile();
setLoading(false);
if (ok) {
@ -148,73 +129,7 @@ function setupContactForm(form) {
});
}
// ── SOUMISSION HUBSPOT ────────────────────────────────────────────────────────
async function submitToHubSpot(data) {
const payload = {
fields: [
{ name: 'firstname', value: data.firstname },
{ name: 'lastname', value: data.lastname },
{ name: 'phone', value: data.phone },
{ name: 'email', value: data.email },
{ name: 'address', value: data.address },
{ name: 'reference_client', value: data.reference_client },
],
context: {
pageUri: window.location.href,
pageName: document.title,
},
};
const res = await fetch(
`https://api.hsforms.com/submissions/v3/integration/submit/${HUBSPOT_PORTAL_ID}/${HUBSPOT_FORM_GUID}`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
}
);
if (!res.ok) throw new Error(`HubSpot error: ${res.status}`);
return res.json();
}
// ── SOUMISSION FORMSPREE (email de backup) ────────────────────────────────────
async function submitToFormspree(data) {
if (FORMSPREE_ID === 'YOUR_FORMSPREE_ID') return;
const res = await fetch(`https://formspree.io/f/${FORMSPREE_ID}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify({
nom: data.lastname,
prenom: data.firstname,
telephone: data.phone,
email: data.email,
adresse_livraison: data.address,
reference_client: data.reference_client,
}),
});
if (!res.ok) throw new Error(`Formspree error: ${res.status}`);
return res.json();
}
// ── NOTIFICATION DOUBLON (email interne seulement, sans toucher aux données) ──
async function notifyDuplicateViaFormspree(contact) {
if (FORMSPREE_ID === 'YOUR_FORMSPREE_ID') return;
try {
await fetch(`https://formspree.io/f/${FORMSPREE_ID}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify({
_subject: `[MVA] Tentative double inscription — ${contact.firstname || ''} ${contact.lastname || ''}`,
message: `Le client ${contact.firstname || ''} ${contact.lastname || ''} (${contact.email}) a tenté de s'inscrire à nouveau. Référence existante : ${contact.reference_client || 'non définie'}.`,
}),
});
} catch { /* Ne pas bloquer l'interface si la notification échoue */ }
}
// ── VALIDATION ────────────────────────────────────────────────────────────────
// ── VALIDATION ───────────────────────────────────────────────────
function validateForm(form) {
let valid = true;
const lang = localStorage.getItem('mva-lang') || 'fr';
@ -263,7 +178,7 @@ function isValidPhone(phone) {
return /^[+\d][\d\s\-().]{6,20}$/.test(phone);
}
// ── AFFICHAGE ─────────────────────────────────────────────────────────────────
// ── AFFICHAGE ────────────────────────────────────────────────────
function showFieldError(name, msg) {
const el = document.getElementById(`error-${name}`);
const input = document.getElementById(name) || document.querySelector(`[name="${name}"]`);
@ -296,11 +211,8 @@ function setLoading(isLoading) {
}
function showSuccess(_refNumber, _clientData) {
// L'envoi de l'email de validation est déjà fait dans setupContactForm
// via l'appel Worker requestVerification — on n'a plus rien à faire ici
// sauf afficher la confirmation à l'écran.
const successEl = document.getElementById('formSuccess');
const form = document.getElementById('contactForm');
const successEl = document.getElementById('formSuccess');
const form = document.getElementById('contactForm');
if (successEl) {
successEl.classList.add('show');
successEl.scrollIntoView({ behavior: 'smooth', block: 'center' });
@ -308,11 +220,11 @@ function showSuccess(_refNumber, _clientData) {
if (form) form.style.display = 'none';
}
// ── EMAIL "RAVIS DE TE REVOIR" (client déjà inscrit) ──────────────────────────
// Rappelle au client son numéro de référence existant — n'écrit RIEN dans HubSpot.
// Passe par le Cloudflare Worker (action: sendWelcomeBack) qui délègue à Resend
// — footer 2026 cohérent avec les autres emails transactionnels. Anti-bot via
// Turnstile : on transmet le token déjà validé au moment du submit du formulaire.
// ── EMAIL "RAVIS DE VOUS REVOIR" (client déjà inscrit) ───────────
// Rappelle au client son numéro de référence existant — n'écrit
// RIEN dans HubSpot. Passe par le Cloudflare Worker (action:
// sendWelcomeBack) qui délègue à Resend. Anti-bot via Turnstile :
// transmet le token déjà validé au moment du submit du formulaire.
async function sendWelcomeBackEmail(contact) {
if (!WORKER_PROXY_URL) return;
if (!contact || !contact.email) return;
@ -329,13 +241,14 @@ async function sendWelcomeBackEmail(contact) {
}),
});
} catch (err) {
// Erreur réseau : on n'interrompt pas l'UX (le client voit déjà sa ref dans le UI)
// Erreur réseau : on n'interrompt pas l'UX (le client voit
// déjà sa référence dans le UI).
console.warn('Worker sendWelcomeBack failed:', err);
}
}
// Affiche le message "déjà client" — ne modifie AUCUNE donnée HubSpot
function showAlreadyRegistered(contact) {
async function showAlreadyRegistered(contact) {
const lang = localStorage.getItem('mva-lang') || 'fr';
const t = translations?.[lang]?.contact || {};
@ -357,11 +270,11 @@ function showAlreadyRegistered(contact) {
if (form) form.style.display = 'none';
// Envoi d'une notification interne à MVA (sans modifier les données du client)
notifyDuplicateViaFormspree(contact);
// Email "Ravis de te revoir" via Worker + Resend (= footer 2026 cohérent)
sendWelcomeBackEmail(contact);
// Email "Ravis de vous revoir" via Worker + Resend (= footer 2026
// cohérent avec les autres emails transactionnels).
await sendWelcomeBackEmail(contact);
// Reset Turnstile after the Worker call (= prevent reuse).
resetTurnstile();
}
function showError() {