Merge pull request #2 from MVA-Global-Fret/migration-brevo

Worker: use Forms API for contact creation (no scope required)
This commit is contained in:
Melissa 2026-05-06 15:57:21 +02:00 committed by GitHub
commit c12f273e24
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -61,6 +61,8 @@ const FALLBACK_EMAILJS_SERVICE_ID = 'service_aeamo3x';
const FALLBACK_EMAILJS_TEMPLATE_ID= 'template_s1kr2et';
const HUBSPOT_API = 'https://api.hubapi.com';
const HUBSPOT_PORTAL_ID = '148163754';
const HUBSPOT_FORM_GUID = '1d9b75c9-8b60-4966-aa18-4bf503452e9a';
const EMAILJS_API = 'https://api.emailjs.com/api/v1.0/email/send';
const corsHeaders = {
@ -197,36 +199,47 @@ export default {
}
try {
// 1) Génère la prochaine référence client (MVA-XXX)
const refNumber = await getNextRef(token);
// 1) Récupère la ref existante si le contact est déjà dans HubSpot
// (réinscription après suppression d'un test, ou création via
// l'ancien flow Forms API). Sinon génère la prochaine ref.
let refNumber;
try {
const existing = await searchContactByEmail(token, tokenData.email);
const existingResult = (existing.results || [])[0];
const existingRef = existingResult?.properties?.reference_client;
refNumber = existingRef || await getNextRef(token);
} catch (_) {
// Si la search échoue (scope manquant, etc.), fallback : génère
// une nouvelle ref. Le Forms API gérera la dédup côté HubSpot.
refNumber = await getNextRef(token);
}
// 2) Crée le contact dans HubSpot avec toutes les propriétés
const createRes = await fetch(`${HUBSPOT_API}/crm/v3/objects/contacts`, {
// 2) Soumet via Forms API HubSpot (sans auth, pas besoin de scope
// write). Forms API crée le contact OU met à jour s'il existe.
const formRes = await fetch(
`https://api.hsforms.com/submissions/v3/integration/submit/${HUBSPOT_PORTAL_ID}/${HUBSPOT_FORM_GUID}`,
{
method: 'POST',
headers: {
'Content-Type' : 'application/json',
'Authorization': `Bearer ${token}`,
},
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
properties: {
firstname : tokenData.firstname,
lastname : tokenData.lastname,
phone : tokenData.phone,
email : tokenData.email,
address : tokenData.address,
reference_client : refNumber,
fields: [
{ name: 'firstname', value: tokenData.firstname || '' },
{ name: 'lastname', value: tokenData.lastname || '' },
{ name: 'phone', value: tokenData.phone || '' },
{ name: 'email', value: tokenData.email },
{ name: 'address', value: tokenData.address || '' },
{ name: 'reference_client', value: refNumber },
],
context: {
pageUri : 'https://mva-global-fret.github.io/site-mva-global-fret/contact.html',
pageName: 'Verified signup (MVA Global Fret)',
},
}),
});
if (!createRes.ok) {
const errTxt = await createRes.text();
// Si l'email existe déjà (409 conflict), on récupère le contact
// existant et on lui envoie quand même son welcome (cas très rare :
// doublon créé via une autre source pendant la fenêtre de 24h)
if (createRes.status === 409) {
throw new Error(`Contact existe déjà dans HubSpot (409). Contactez l'admin.`);
}
throw new Error(`HubSpot create failed ${createRes.status}: ${errTxt}`);
);
if (!formRes.ok) {
const errTxt = await formRes.text();
throw new Error(`HubSpot Forms API failed ${formRes.status}: ${errTxt}`);
}
// 3) Envoie le welcome email avec ref + adresse Paris
@ -637,9 +650,13 @@ async function sendWelcomeViaBrevo(env, contact) {
${parisAddr}
</div>
<div style="background:#fff3cd;border:1px solid #ffc107;padding:14px 18px;border-radius:6px;margin:16px 0;">
<p style="margin:0;color:#856404;font-size:14px;">
📌 <strong>Sur le colis</strong>, indiquez votre numéro de référence <strong>${ref}</strong>
juste après le nom du destinataire entre parenthèses.
<p style="margin:0 0 8px;color:#856404;font-size:14px;font-weight:bold;">
Important : ne modifiez rien à ces informations.
</p>
<p style="margin:0;color:#856404;font-size:14px;line-height:1.5;">
Recopiez l'adresse <strong>exactement telle qu'elle est indiquée ci-dessus</strong>,
sans rien retirer ni ajouter. Votre numéro de référence <strong>${ref}</strong>
fait partie intégrante de l'adresse — c'est ce qui garantit que votre colis nous arrive bien.
</p>
</div>
<p style="color:#333;line-height:1.6;">