MonEspacePro/backend/src/enrollment/pages.ts
Tony AVERTY b75e396bde Parrainage (formule Pro)
- Code personnel par carte, lien d'inscription ?parrain=CODE (page de la carte, dos Apple, liens Google)
- Bandeau « X vous invite » à l'inscription ; bouton Partager (partage natif ou copie)
- Récompense au premier passage du filleul : parrain et filleul (réglables), une fois,
  au plus 10 récompenses par parrain sur 30 jours
- Notifications via la rubrique Actualité (message personnel)
- Admin : carte Parrainage ; app Pro : écran dans Fidélisation
- Migration manuelle 2026-10-07-parrainage.sql

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 10:42:55 +02:00

449 lines
27 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import type { CardDesign, Plan, Reward, Store, SubscriptionStatus } from '@prisma/client';
import { hasFeature } from '../billing/plans';
import { nextRewardText, reviewOffered, type CardWithContext } from '../wallet/wallet.types';
/** Pages publiques (clients finaux), rendues côté serveur aux couleurs du magasin. */
export type StoreWithDesign = Store & {
cardDesign: (CardDesign & { rewards: Reward[] }) | null;
subscription?: { plan: Plan; status: SubscriptionStatus } | null;
};
/** Formule Pro et plus : la mention « Propulsé par MonEspacePro » disparaît. */
const whiteLabel = (s: StoreWithDesign) => s.subscription?.status === 'ACTIVE' && hasFeature(s.subscription.plan, 'whiteLabel');
export type Platform = 'apple' | 'google' | 'other';
/** Offre d'anniversaire active (formule Pro) : on propose alors au client d'indiquer son anniversaire. */
export const birthdayOffered = (s: StoreWithDesign) =>
s.birthdayEnabled && s.subscription?.status === 'ACTIVE' && hasFeature(s.subscription.plan, 'birthday');
const MONTHS = ['janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'];
function birthdaySelects() {
const days = Array.from({ length: 31 }, (_, i) => `<option value="${i + 1}">${i + 1}</option>`).join('');
const months = MONTHS.map((m, i) => `<option value="${i + 1}">${m}</option>`).join('');
return `<div style="display:flex;gap:10px">
<select id="bday" aria-label="Jour" style="width:96px;flex:none"><option value="">Jour</option>${days}</select>
<select id="bmonth" aria-label="Mois" style="flex:1;min-width:0"><option value="">Mois</option>${months}</select>
</div>`;
}
/** Lecture des listes jour / mois côté navigateur : null si vide, false si incomplet ou impossible. */
const BIRTHDAY_JS = `function readBirthday(){var d=+document.getElementById('bday').value,m=+document.getElementById('bmonth').value;if(!d&&!m)return null;if(!d||!m||d>[31,29,31,30,31,30,31,31,30,31,30,31][m-1])return false;return {day:d,month:m}}`;
function birthdayGiftLine(store: StoreWithDesign) {
const n = store.birthdayPoints;
const unit = store.cardDesign?.pointsMode === 'STAMP' ? 'tampon' : 'point';
return n > 0 ? `${n} ${unit}${n > 1 ? 's' : ''} offert${n > 1 ? 's' : ''} le jour de votre anniversaire.` : 'Une surprise le jour de votre anniversaire.';
}
export function escapeHtml(value: unknown) {
return String(value ?? '')
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}
const e = escapeHtml;
export function detectPlatform(userAgent = ''): Platform {
if (/iPhone|iPad|iPod|Macintosh/i.test(userAgent)) return 'apple';
if (/Android/i.test(userAgent)) return 'google';
return 'other';
}
/** « Boulangerie Le Fournil » → « de Boulangerie Le Fournil », « Atelier » → « d'Atelier ». */
function de(name: string) {
return /^[aeiouyhàâéèêîôû]/i.test(name) ? `d’${name}` : `de ${name}`;
}
const SYMBOL = (size: number) =>
`<svg width="${size}" height="${size}" viewBox="0.5 -2 64 64" aria-hidden="true"><path d="M12 54V32a9 9 0 0 1 18 0v22M30 32a9 9 0 0 1 18 0v22" fill="none" stroke="currentColor" stroke-width="9"/><circle cx="51" cy="12" r="7" fill="currentColor"/></svg>`;
function theme(store: StoreWithDesign) {
const d = store.cardDesign;
return {
bg: d?.backgroundColor ?? '#1F2937',
fg: d?.foregroundColor ?? '#FFFFFF',
label: d?.labelColor ?? '#D1D5DB',
logo: d?.logoPath ? `/uploads/${d.logoPath}` : null,
strip: d?.stripPath ? `/uploads/${d.stripPath}` : null,
};
}
function layout(store: StoreWithDesign, title: string, body: string, script = '') {
const t = theme(store);
return `<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex">
<meta name="theme-color" content="${e(t.bg)}">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-title" content="${e(store.name)}">
${t.logo ? `<link rel="apple-touch-icon" href="${e(t.logo)}">` : ''}
<title>${e(title)}</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Figtree:wght@400;500;600;700&display=swap" rel="stylesheet">
<style>
:root{--brand:${e(t.bg)};--on-brand:${e(t.fg)};--brand-label:${e(t.label)};--bg:#F6F6F3;--surface:#fff;--text:#1C1C19;--muted:#5F5E56;--border:#DEDDD6;--err:#B8322A;--ok:#1E7A3C}
@media (prefers-color-scheme:dark){:root{--bg:#121211;--surface:#1D1D1A;--text:#F2F1EC;--muted:#A5A49B;--border:#34342F;--err:#F08A80;--ok:#6FCF8F}}
*{box-sizing:border-box}
body{margin:0;background:var(--bg);color:var(--text);font:400 16px/1.5 'Figtree',system-ui,sans-serif}
a{color:inherit}
.wrap{max-width:480px;margin:0 auto;min-height:100vh;display:flex;flex-direction:column}
header{position:relative;background:var(--brand);color:var(--on-brand)}
header .strip{display:block;width:100%;aspect-ratio:1125/432;object-fit:cover}
header .nostrip{height:96px}
header .logo{position:absolute;left:20px;bottom:-32px;width:72px;height:72px;border-radius:16px;object-fit:contain;background:var(--surface);border:3px solid var(--surface);box-shadow:0 4px 12px rgb(0 0 0/.15)}
main{flex:1;padding:48px 20px 24px;display:flex;flex-direction:column;gap:20px}
.eyebrow{font-size:14px;font-weight:600;color:var(--muted)}
h1{margin:0;font-size:28px;line-height:1.2;font-weight:700;letter-spacing:-.01em}
p{margin:0}
.promises{display:flex;flex-direction:column;gap:10px;background:var(--surface);border:1px solid var(--border);border-radius:14px;padding:14px 16px}
.promises div{display:flex;gap:10px;align-items:center;font-weight:500}
.dot{width:10px;height:10px;border-radius:50%;background:var(--brand);flex:none;outline:2px solid var(--border)}
form{display:flex;flex-direction:column;gap:16px}
.field{display:flex;flex-direction:column;gap:6px}
label{font-weight:600}
.hint{font-size:14px;color:var(--muted)}
.error{font-size:14px;color:var(--err);font-weight:500}
input[type=text],input[type=email],select{height:52px;padding:0 14px;border:1px solid #8A897F;border-radius:12px;background:var(--surface);color:var(--text);font:400 17px 'Figtree',sans-serif;width:100%}
input:focus{outline:2px solid var(--brand);outline-offset:1px}
.consent{display:flex;gap:12px;align-items:flex-start;font-weight:400;font-size:15px}
.consent input{width:22px;height:22px;margin-top:2px;flex:none;accent-color:var(--brand)}
.btn{display:flex;align-items:center;justify-content:center;gap:10px;min-height:54px;padding:0 20px;border-radius:14px;border:0;background:var(--brand);color:var(--on-brand);font:700 17px 'Figtree',sans-serif;text-decoration:none;cursor:pointer;width:100%}
.btn:disabled{opacity:.6}
.btn.ghost{background:transparent;color:var(--text);border:1px solid var(--border)}
.btn.wallet{background:#000;color:#fff;border:1px solid #A6A6A6}
.small{font-size:14px;color:var(--muted);text-align:center}
.notice{padding:14px 16px;border-radius:12px;background:var(--surface);border:1px solid var(--border)}
.icon-ok{width:44px;height:44px;border-radius:50%;background:var(--brand);color:var(--on-brand);display:flex;align-items:center;justify-content:center}
.pass{border-radius:16px;overflow:hidden;background:var(--brand);color:var(--on-brand);box-shadow:0 8px 24px rgb(0 0 0/.18)}
.pass .top{display:flex;align-items:center;gap:10px;padding:12px 14px;font-weight:600}
.pass .top img{max-height:30px;max-width:110px;object-fit:contain}
.pass .band{position:relative;min-height:90px;background:rgb(255 255 255/.08)}
.pass .band img{display:block;width:100%;aspect-ratio:1125/432;object-fit:cover}
.pass .bal{position:absolute;left:14px;bottom:8px}
.pass .lbl{font-size:11px;font-weight:600;color:var(--brand-label);text-transform:uppercase}
.pass .big{font-size:34px;line-height:1}
.pass .row{display:flex;justify-content:space-between;padding:10px 14px 14px}
.pass .qr{background:#fff;margin:0 auto 18px;width:200px;padding:12px;border-radius:12px}
.pass .qr svg{display:block;width:100%;height:auto}
.rws{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:10px}
.rw{background:var(--surface);border:1px solid var(--border);border-radius:14px;padding:12px 14px;display:flex;flex-direction:column;gap:6px}
.rw.ok{border-color:var(--brand);border-width:2px}
.rw-h{display:flex;justify-content:space-between;gap:12px;align-items:baseline}
.rw-h span{font-size:14px;color:var(--muted);white-space:nowrap}
.rw.ok .rw-h span{color:var(--ok);font-weight:700}
.rw-bar{height:8px;border-radius:999px;background:var(--border);overflow:hidden}
.rw-bar i{display:block;height:100%;background:var(--brand);border-radius:999px}
.rw small{font-size:13px;color:var(--muted)}
footer{padding:20px;display:flex;flex-direction:column;align-items:center;gap:10px;font-size:13px;color:var(--muted)}
footer nav{display:flex;gap:16px}
footer .powered{display:inline-flex;align-items:center;gap:6px;font-size:12px;text-decoration:none}
[hidden]{display:none!important}
</style>
</head>
<body>
<div class="wrap">
<header>
${t.strip ? `<img class="strip" src="${e(t.strip)}" alt="">` : '<div class="nostrip"></div>'}
${t.logo ? `<img class="logo" src="${e(t.logo)}" alt="${e(store.name)}">` : ''}
</header>
<main>
${body}
</main>
<footer>
<nav><a href="/c/${e(store.slug)}/confidentialite">Confidentialité</a></nav>
${whiteLabel(store) ? "" : `<span class="powered">${SYMBOL(14)}<span>Propulsé par <strong>MonEspacePro</strong></span></span>`}
</footer>
</div>
${script ? `<script>${script}</script>` : ''}
</body>
</html>`;
}
function promises(store: StoreWithDesign) {
const d = store.cardDesign!;
const rule =
d.pointsMode === 'STAMP'
? 'Un tampon à chaque passage'
: Number(d.pointsPerEuro) === 1
? 'Gagnez 1 point par euro dépensé'
: `Gagnez ${Number(d.pointsPerEuro).toLocaleString('fr-FR')} points par euro dépensé`;
const unit = d.pointsMode === 'STAMP' ? 'tampons' : 'points';
const shown = d.rewards.slice(0, 4);
const more = d.rewards.length - shown.length;
return `<div class="promises">
<div><span class="dot"></span><span>${e(rule)}</span></div>
${shown.map((r) => `<div><span class="dot"></span><span>${e(r.label)} à ${r.cost} ${unit}</span></div>`).join('\n')}
${more > 0 ? `<div class="hint">et ${more} autre${more > 1 ? 's' : ''} récompense${more > 1 ? 's' : ''} à découvrir</div>` : ''}
</div>`;
}
export function enrollPage(store: StoreWithDesign, referrer: { code: string; firstName: string } | null = null) {
const program = store.cardDesign!.programName;
const unitLower = store.cardDesign!.pointsMode === 'STAMP' ? 'tampons' : 'points';
const body = `
<section id="v-form">
<div style="display:flex;flex-direction:column;gap:4px;margin-bottom:20px">
<span class="eyebrow">${e(store.name)} · ${e(store.city)}</span>
<h1>${e(program)}</h1>
</div>
${
referrer
? `<div class="notice" style="margin-bottom:16px"><strong>${e(referrer.firstName)} vous invite !</strong> ${
store.referralFriendPoints > 0
? `${store.referralFriendPoints} ${unitLower.replace(/s$/, '')}${store.referralFriendPoints > 1 ? 's' : ''} offert${store.referralFriendPoints > 1 ? 's' : ''} à votre premier passage en magasin.`
: 'Créez votre carte et passez en magasin.'
}</div>`
: ''
}
${promises(store)}
<form id="f" novalidate style="margin-top:20px">
<div class="field">
<label for="firstName">Prénom</label>
<input id="firstName" name="firstName" type="text" autocomplete="given-name" maxlength="40" required>
<span class="error" id="e-firstName" hidden>Indiquez votre prénom.</span>
</div>
<div class="field">
<label for="email">E-mail</label>
<input id="email" name="email" type="email" inputmode="email" autocomplete="email" placeholder="vous@exemple.fr" required>
<span class="hint" id="h-email">Pour retrouver votre carte si vous changez de téléphone.</span>
<span class="error" id="e-email" hidden>Vérifiez votre adresse e-mail.</span>
</div>${
birthdayOffered(store)
? `<div class="field">
<label for="bday">Anniversaire <span class="hint">(facultatif)</span></label>
${birthdaySelects()}
<span class="hint">${e(birthdayGiftLine(store))}</span>
<span class="error" id="e-birthday" hidden>Choisissez le jour et le mois, ou laissez les deux vides.</span>
</div>`
: ''
}
<div class="field">
<label class="consent"><input id="consent" type="checkbox" required>
<span>J'accepte que ${e(store.name)} utilise mon prénom${birthdayOffered(store) ? ', mon e-mail et mon anniversaire (si je l’indique)' : ' et mon e-mail'} pour gérer ma carte de fidélité. <a href="/c/${e(store.slug)}/confidentialite">Politique de confidentialité</a></span>
</label>
<span class="error" id="e-consent" hidden>Cochez la case pour créer votre carte.</span>
</div>
<span class="error" id="e-global" role="alert" hidden></span>
<button class="btn" id="submit">Créer ma carte</button>
<span class="small">Gratuit, sans application à télécharger.<br>Désinscription possible à tout moment.</span>
</form>
</section>
<section id="v-exists" hidden style="display:flex;flex-direction:column;gap:20px">
<h1>Vous avez déjà une carte</h1>
<p>Une carte ${e(program)} est déjà associée à <strong id="masked"></strong>. Vos ${unitLower} sont bien conservés.</p>
<button class="btn" id="resend" type="button">Renvoyer le lien par e-mail</button>
<div class="notice" id="resent" role="status" hidden><strong>C'est envoyé.</strong> Ouvrez l'e-mail sur ce téléphone pour ajouter votre carte. Pensez à regarder dans les courriers indésirables.</div>
<button class="btn ghost" id="back" type="button">Utiliser une autre adresse</button>
</section>`;
const script = `
(function(){
var slug=${JSON.stringify(store.slug)};
var $=function(id){return document.getElementById(id)};
var lastEmail='';
var referralCode=${JSON.stringify(referrer?.code ?? null)};
var hasBirthday=${birthdayOffered(store) ? 'true' : 'false'};
${BIRTHDAY_JS}
function show(id,on){$(id).hidden=!on}
$('f').addEventListener('submit',async function(ev){
ev.preventDefault();
var firstName=$('firstName').value.trim(),email=$('email').value.trim(),consent=$('consent').checked;
var okName=firstName.length>0,okMail=/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email);
show('e-firstName',!okName);show('e-email',!okMail);show('h-email',okMail);show('e-consent',!consent);show('e-global',false);
var bd=hasBirthday?readBirthday():null;
if(hasBirthday)show('e-birthday',bd===false);
if(!okName||!okMail||!consent||bd===false)return;
$('submit').disabled=true;
try{
var r=await fetch('/api/public/stores/'+slug+'/enroll',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(Object.assign({firstName:firstName,email:email,consent:true},bd?{birthMonth:bd.month,birthDay:bd.day}:{},referralCode?{referralCode:referralCode}:{}))});
var data=await r.json().catch(function(){return {}});
if(!r.ok){throw new Error(r.status===409?'Le programme est momentanément indisponible.':r.status===429?'Trop de tentatives, réessayez dans une minute.':'Une erreur est survenue, réessayez.')}
if(data.status==='created'){location.href=data.cardUrl+'&nouveau=1';return}
lastEmail=email;$('masked').textContent=data.maskedEmail;show('v-form',false);show('v-exists',true);show('resent',false);show('resend',true);
}catch(err){$('e-global').textContent=err.message;show('e-global',true)}
finally{$('submit').disabled=false}
});
$('resend').addEventListener('click',async function(){
this.disabled=true;
await fetch('/api/public/stores/'+slug+'/resend',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({email:lastEmail})}).catch(function(){});
show('resend',false);show('resent',true);this.disabled=false;
});
$('back').addEventListener('click',function(){show('v-exists',false);show('v-form',true);$('email').focus()});
})();`;
return layout(store, program, body, script);
}
export function unavailablePage(store: StoreWithDesign) {
const unitLower = store.cardDesign?.pointsMode === 'STAMP' ? 'tampons' : 'points';
return layout(
store,
store.name,
`<span class="eyebrow">${e(store.name)} · ${e(store.city)}</span>
<h1>Programme momentanément indisponible</h1>
<p>L'inscription au programme de fidélité ${e(de(store.name))} n'est pas possible pour le moment. Si vous avez déjà une carte, vos ${unitLower} sont conservés.</p>
<p>N'hésitez pas à vous renseigner au comptoir. Merci de votre fidélité !</p>`,
);
}
/** Liste des récompenses avec la progression du client (barre + « encore N »). */
function rewardsList(rewards: Reward[], balance: number, stamp: boolean) {
if (!rewards.length) return '';
const unit = (n: number) => (stamp ? (n > 1 ? 'tampons' : 'tampon') : n > 1 ? 'points' : 'point');
const items = rewards
.map((r) => {
const ok = balance >= r.cost;
const pct = Math.min(100, Math.round((balance / r.cost) * 100));
return `<li class="rw${ok ? ' ok' : ''}">
<div class="rw-h"><strong>${e(r.label)}</strong><span>${ok ? 'Disponible' : `encore ${r.cost - balance} ${unit(r.cost - balance)}`}</span></div>
<div class="rw-bar" role="progressbar" aria-valuemin="0" aria-valuemax="${r.cost}" aria-valuenow="${Math.min(balance, r.cost)}" aria-label="${e(r.label)}"><i style="width:${pct}%"></i></div>
<small>${r.cost} ${unit(r.cost)}</small>
</li>`;
})
.join('');
return `<section aria-labelledby="rw-title" style="display:flex;flex-direction:column;gap:10px">
<h2 id="rw-title" style="margin:0;font-size:20px">Vos récompenses</h2>
<ul class="rws">${items}</ul>
</section>`;
}
export function cardPage(
card: CardWithContext,
opts: { platform: Platform; isNew: boolean; apple: boolean; google: boolean; qrSvg: string; referred?: number; referralUrl?: string | null },
) {
const store = card.store as StoreWithDesign;
const d = store.cardDesign!;
const t = theme(store);
const unit = d.pointsMode === 'STAMP' ? 'Tampons' : 'Points';
const q = `?k=${encodeURIComponent(card.accessKey)}`;
const appleBtn = opts.apple
? `<a class="btn wallet" href="/api/public/cards/${e(card.serial)}/apple${e(q)}">Ajouter à Apple Wallet</a>`
: '';
const googleBtn = opts.google
? `<a class="btn wallet" href="/api/public/cards/${e(card.serial)}/google${e(q)}">Ajouter à Google Wallet</a>`
: '';
// Le bouton de la plateforme détectée en premier, l'autre en lien secondaire.
const buttons =
opts.platform === 'google'
? googleBtn + (appleBtn && `<a class="small" href="/api/public/cards/${e(card.serial)}/apple${e(q)}">Vous avez un iPhone ? Apple Wallet</a>`)
: opts.platform === 'apple'
? appleBtn + (googleBtn && `<a class="small" href="/api/public/cards/${e(card.serial)}/google${e(q)}">Vous avez un Android ? Google Wallet</a>`)
: appleBtn + googleBtn;
const none = !opts.apple && !opts.google;
const askBirthday = birthdayOffered(store) && card.customer.birthMonth === null;
const body = `
<div style="display:flex;flex-direction:column;gap:8px">
${opts.isNew ? `<span class="icon-ok"><svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12.5l4.5 4.5L19 7.5"/></svg></span>` : ''}
<h1>${opts.isNew ? `Votre carte est prête, ${e(card.customer.firstName)} !` : `Votre carte ${e(d.programName)}`}</h1>
<p class="hint">Ajoutez-la à votre téléphone et présentez-la au comptoir à chaque passage.</p>
</div>
<div class="pass" aria-label="Aperçu de votre carte">
<div class="top">${t.logo ? `<img src="${e(t.logo)}" alt="">` : ''}<span>${e(d.programName)}</span></div>
<div class="band">${t.strip ? `<img src="${e(t.strip)}" alt="">` : ''}<div class="bal"><div class="lbl">${unit}</div><div class="big">${card.balance}</div></div></div>
<div class="row"><div><div class="lbl">Membre</div>${e(card.customer.firstName)}</div><div style="text-align:right;max-width:60%"><div class="lbl">Prochaine récompense</div>${e(nextRewardText(card) ?? '—')}</div></div>
<div class="qr" role="img" aria-label="QR code de votre carte, à présenter au comptoir">${opts.qrSvg}</div>
</div>
<p class="hint" style="text-align:center">Présentez ce QR code au comptoir à chaque passage.</p>
${rewardsList(d.rewards, card.balance, d.pointsMode === 'STAMP')}
${askBirthday ? `<form id="bform" class="notice" style="display:flex;flex-direction:column;gap:10px" novalidate>
<strong>Un cadeau pour votre anniversaire ?</strong>
<span>${e(birthdayGiftLine(store))} Indiquez le jour et le mois (l’année n’est pas demandée).</span>
${birthdaySelects()}
<span class="error" id="e-birthday" hidden>Choisissez un jour et un mois valides.</span>
<button class="btn" id="bsave">Enregistrer</button>
</form>` : ''}
<div style="display:flex;flex-direction:column;gap:12px;align-items:stretch">
${buttons}
${
none || opts.platform === 'other'
? `<div class="notice"><strong>Gardez votre carte à portée de main :</strong> ${
opts.platform === 'google'
? 'menu ⋮ de Chrome → « Ajouter à l’écran d’accueil ».'
: opts.platform === 'apple'
? 'bouton Partager de Safari → « Sur l’écran d’accueil ».'
: 'ajoutez cette page à vos favoris ou à l’écran d’accueil de votre téléphone.'
} Le lien est aussi dans l’e-mail reçu.</div>`
: ''
}
</div>
${reviewOffered(card.store) && !opts.isNew ? `<a class="btn ghost" href="/api/public/cards/${e(card.serial)}/review${e(q)}" rel="noopener">Laisser un avis Google</a>` : ''}
${opts.isNew ? '<p class="small">Un e-mail de confirmation vous a été envoyé avec le lien de votre carte.</p>' : ''}
${
opts.referralUrl
? `<section class="notice" style="display:flex;flex-direction:column;gap:10px">
<strong>Parrainez vos proches</strong>
<span>${
store.referralPoints > 0
? `Gagnez ${store.referralPoints} ${unit.toLowerCase().replace(/s$/, '')}${store.referralPoints > 1 ? 's' : ''} pour chaque ami qui s’inscrit avec votre lien et passe en magasin.`
: 'Partagez votre lien avec vos proches.'
}${store.referralFriendPoints > 0 ? ` Votre ami reçoit ${store.referralFriendPoints} ${unit.toLowerCase().replace(/s$/, '')}${store.referralFriendPoints > 1 ? 's' : ''} lui aussi.` : ''}</span>
<input type="text" id="reflink" readonly value="${e(opts.referralUrl)}" aria-label="Votre lien de parrainage" onclick="this.select()">
<button class="btn" id="share" type="button">Partager mon lien</button>
${opts.referred ? `<span class="small">${opts.referred} ami${opts.referred > 1 ? 's' : ''} inscrit${opts.referred > 1 ? 's' : ''} grâce à vous.</span>` : ''}
</section>`
: ''
}
<details style="margin-top:12px">
<summary class="small" style="cursor:pointer">Supprimer ma carte</summary>
<div style="display:flex;flex-direction:column;gap:12px;margin-top:12px">
<p class="hint">Votre carte, votre solde et vos données personnelles seront définitivement effacés. Pensez aussi à retirer la carte de votre Wallet.</p>
<button class="btn ghost" id="delete" type="button" style="color:var(--err)">Supprimer définitivement</button>
</div>
</details>`;
const script = `
${
opts.referralUrl
? `document.getElementById('share').addEventListener('click',async function(){
var url=document.getElementById('reflink').value;
var text=${JSON.stringify(`Rejoignez le programme de fidélité ${d.programName} de ${store.name} :`)};
if(navigator.share){try{await navigator.share({title:${JSON.stringify(store.name)},text:text,url:url});return}catch(e){if(e.name==='AbortError')return}}
try{await navigator.clipboard.writeText(url);this.textContent='Lien copié !'}catch(e){document.getElementById('reflink').select()}
});`
: ''
}
${askBirthday ? `${BIRTHDAY_JS}
document.getElementById('bform').addEventListener('submit',async function(ev){
ev.preventDefault();var bd=readBirthday();var err=document.getElementById('e-birthday');err.hidden=!!bd;if(!bd)return;
document.getElementById('bsave').disabled=true;
var r=await fetch('/api/public/cards/${card.serial}/birthday${q}',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(bd)}).catch(function(){return null});
if(r&&r.ok){this.innerHTML='<strong>C’est noté, merci !</strong><span>Rendez-vous le jour de votre anniversaire.</span>'}else{err.textContent='Enregistrement impossible, réessayez.';err.hidden=false;document.getElementById('bsave').disabled=false}
});` : ''}
document.getElementById('delete').addEventListener('click',async function(){
if(!confirm('Supprimer définitivement votre carte et votre solde ?'))return;
this.disabled=true;
var r=await fetch('/api/public/cards/${card.serial}${q}',{method:'DELETE'});
document.querySelector('main').innerHTML=r.ok?'<h1>Carte supprimée</h1><p>Vos données ont été effacées. Vous pouvez retirer la carte de votre Wallet.</p>':'<h1>Suppression impossible</h1><p>Réessayez plus tard.</p>';
});`;
return layout(store, d.programName, body, script);
}
export function privacyPage(store: StoreWithDesign) {
return layout(
store,
`Confidentialité — ${store.name}`,
`<h1>Confidentialité</h1>
<p><strong>Responsable du traitement :</strong> ${e(store.name)}, ${e(store.addressLine)}, ${e(store.postalCode)} ${e(store.city)} (SIRET ${e(store.siret)}). Contact : <a href="mailto:${e(store.contactEmail)}">${e(store.contactEmail)}</a>.</p>
<p><strong>Données collectées :</strong> votre prénom, votre adresse e-mail, votre jour et mois d'anniversaire si vous les indiquez (facultatif), votre solde et l'historique de vos passages (date, montant, points).</p>
<p><strong>Finalité :</strong> gérer votre carte de fidélité. Vos données ne sont ni vendues ni utilisées à des fins publicitaires.</p>
<p><strong>Base légale :</strong> votre consentement, que vous pouvez retirer à tout moment en supprimant votre carte depuis le lien reçu par e-mail.</p>
<p><strong>Sous-traitant :</strong> la plateforme MonEspacePro (EI Tony Averty) héberge les données pour le compte du commerce, en France / Union européenne.</p>
<p><strong>Durée de conservation :</strong> tant que votre carte est active, puis suppression.</p>
<p><strong>Vos droits :</strong> accès, rectification, effacement, portabilité, en écrivant au commerce. Vous pouvez aussi saisir la CNIL (cnil.fr).</p>
<a class="btn ghost" href="/c/${e(store.slug)}">Retour</a>`,
);
}
export function notFoundPage() {
return `<!doctype html><html lang="fr"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="robots" content="noindex"><title>Introuvable</title>
<style>body{margin:0;min-height:100vh;display:grid;place-items:center;font:16px/1.5 system-ui,sans-serif;background:#F6F6F3;color:#1C1C19;padding:20px;text-align:center}</style></head>
<body><div><h1 style="font-size:24px">Lien introuvable</h1><p>Ce lien n'existe pas ou n'est plus valide. Renseignez-vous au comptoir.</p></div></body></html>`;
}