/** * Génère prisma/manual-migrations/2026-10-15-stats-demo.sql : un an de fausses statistiques pour le * magasin de démonstration App Review (« Café Démo », demo.apple@gmail.com) : clients, cartes, * passages, montants, récompenses, iPhones Apple Wallet. * * Les dates sont relatives au moment où le SQL est exécuté : les stats restent « fraîches ». * Tirage déterministe (graine fixe) : relancer le script donne le même fichier. * * Usage : node scripts/demo-stats-sql.js */ const fs = require('fs'); const path = require('path'); const DAYS = 365; const CUSTOMERS = 120; const REWARD_COST = 10; // « Un café offert » : 10 tampons const PREFIX = 'demostat'; // PRNG déterministe (mulberry32). let seed = 20261015; const rand = () => { seed |= 0; seed = (seed + 0x6d2b79f5) | 0; let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; const int = (a, b) => a + Math.floor(rand() * (b - a + 1)); const pick = (arr) => arr[Math.floor(rand() * arr.length)]; /** Tirage pondéré : [[valeur, poids], …]. */ const weighted = (pairs) => { let r = rand() * pairs.reduce((s, [, w]) => s + w, 0); for (const [v, w] of pairs) if ((r -= w) < 0) return v; return pairs[pairs.length - 1][0]; }; const FIRST_NAMES = [ 'Léa', 'Hugo', 'Chloé', 'Lucas', 'Manon', 'Louis', 'Emma', 'Gabriel', 'Inès', 'Arthur', 'Jade', 'Jules', 'Louise', 'Raphaël', 'Alice', 'Adam', 'Lina', 'Nathan', 'Rose', 'Paul', 'Anna', 'Tom', 'Zoé', 'Théo', 'Juliette', 'Maël', 'Sarah', 'Noah', 'Lou', 'Victor', 'Margaux', 'Antoine', 'Clara', 'Martin', 'Agathe', 'Baptiste', 'Romane', 'Simon', 'Eva', 'Maxime', 'Nina', 'Thomas', 'Pauline', 'Julien', 'Mathilde', 'Nicolas', 'Élise', 'Quentin', 'Céline', 'Damien', 'Sophie', 'Yann', 'Marie', 'Pierre', 'Claire', 'Guillaume', 'Laura', 'Benoît', 'Anaïs', 'Olivier', 'Charlotte', 'Florian', 'Léna', 'Erwan', 'Gwen', 'Maëlle', 'Kévin', 'Audrey', 'Sylvain', 'Nolwenn', 'Loïc', 'Morgane', 'Bastien', 'Solène', 'Thibault', 'Elsa', 'Mathis', 'Océane', 'Valentin', 'Capucine', ]; const SERIAL_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; const serial = () => 'MEP' + Array.from({ length: 8 }, () => pick([...SERIAL_ALPHABET])).join(''); const ascii = (s) => s.normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase(); const id = (kind, n) => `${PREFIX}${kind}${String(n).padStart(8, '0')}`; const q = (s) => `'${String(s).replace(/'/g, "''")}'`; /** Décalage Paris → UTC (heures) pour une date : +2 en été, +1 en hiver (approximation au jour près). */ function parisOffset(date) { const y = date.getUTCFullYear(); const lastSunday = (m) => { const d = new Date(Date.UTC(y, m + 1, 0)); d.setUTCDate(d.getUTCDate() - d.getUTCDay()); return d; }; return date >= lastSunday(2) && date < lastSunday(9) ? 2 : 1; } const today = new Date(); today.setUTCHours(0, 0, 0, 0); /** * Horodatage SQL relatif : `d` jours avant aujourd'hui, à l'heure locale de Paris h:m. * Exprimé en minutes avant aujourd'hui minuit UTC (@today), pour que le fichier reste valable plus tard. */ function at(d, h, m) { const day = new Date(today.getTime() - d * 86400_000); const minutes = d * 1440 - (h - parisOffset(day)) * 60 - m; return `@today - INTERVAL ${minutes} MINUTE`; } /** Jour de semaine (0 = lundi) d'un jour `d` avant aujourd'hui. */ const weekday = (d) => (new Date(today.getTime() - d * 86400_000).getUTCDay() + 6) % 7; /** Heure de passage d'un café : pics du petit-déjeuner, du midi et du goûter. */ function visitTime(wd) { const h = wd >= 5 ? weighted([[8, 3], [9, 6], [10, 8], [11, 6], [12, 4], [15, 4], [16, 5], [17, 3]]) : weighted([[7, 6], [8, 9], [9, 5], [10, 3], [11, 2], [12, 6], [13, 5], [14, 2], [16, 3], [17, 3], [18, 2]]); return [h, int(0, 59)]; } // Clients : quelques habitués, beaucoup d'occasionnels ; plus d'inscriptions récentes (le programme décolle). const customers = []; for (let i = 0; i < CUSTOMERS; i++) { const name = FIRST_NAMES[i % FIRST_NAMES.length]; // Ancienneté : biais vers le récent (≈ 15 % des cartes créées dans les 30 derniers jours). const created = Math.max(1, Math.min(DAYS - 1, Math.floor(Math.pow(rand(), 1.6) * DAYS))); const kind = weighted([['habitué', 2], ['régulier', 4], ['occasionnel', 6]]); const perWeek = kind === 'habitué' ? int(4, 6) : kind === 'régulier' ? int(1, 3) : rand() * 0.6 + 0.15; customers.push({ n: i + 1, name, email: `${ascii(name)}.${int(10, 99)}@example.com`, birth: rand() < 0.5 ? [int(1, 12), int(1, 28)] : null, created, createdTime: visitTime(weekday(created)), p: perWeek / 6, // 6 jours d'ouverture par semaine apple: rand() < 0.78, serial: serial(), }); } // Passages : fermé le lundi ; un peu moins de monde il y a un an (croissance douce). const txRows = []; let txN = 0; for (const c of customers) { let balance = 0; let last = null; const visits = []; for (let d = c.created; d >= 1; d--) { const wd = weekday(d); if (wd === 0) continue; const growth = 0.75 + 0.25 * (1 - d / DAYS); const weekend = wd >= 5 ? 1.25 : 1; const first = d === c.created; if (first || rand() < c.p * growth * weekend) visits.push({ d, time: first ? c.createdTime : visitTime(wd) }); } for (const v of visits) { const [h, m] = v.time; const amount = rand() < 0.75 ? weighted([[int(180, 450), 6], [int(450, 900), 3], [int(900, 1800), 1]]) : null; balance += 1; txRows.push({ id: id('tx', ++txN), card: id('card', c.n), type: 'CREDIT', amount, points: 1, after: balance, when: at(v.d, h, m), reward: null }); last = at(v.d, h, m); // Récompense prise juste après le 10e tampon dans 60 % des cas, sinon à un passage suivant. if (balance >= REWARD_COST && rand() < 0.6) { balance -= REWARD_COST; txRows.push({ id: id('tx', ++txN), card: id('card', c.n), type: 'REDEEM', amount: null, points: -REWARD_COST, after: balance, when: at(v.d, h, Math.min(59, m + 1)), reward: true }); } } c.balance = balance; c.lastCredit = last; } // SQL. const out = []; out.push(`-- Fausses statistiques pour le magasin de démonstration App Review (« Café Démo »). -- Généré par scripts/demo-stats-sql.js : ${CUSTOMERS} clients, ${txRows.length} opérations sur ${DAYS} jours. -- À exécuter APRÈS 2026-10-12-compte-demo-apple.sql (ou scripts/create-demo-store.ts) et 2026-10-09-annulation.sql. -- Dates relatives au moment de l'exécution. Ne touche pas à la carte « Camille ». -- Les iPhones Apple Wallet sont fictifs (jetons invalides) : Apple refuse simplement les envois vers eux. -- -- Pour tout retirer : -- DELETE FROM \`Customer\` WHERE \`id\` LIKE '${PREFIX}%'; -- cartes, opérations et inscriptions suivent (cascade) -- DELETE FROM \`AppleDevice\` WHERE \`id\` LIKE '${PREFIX}%'; START TRANSACTION; SET @staff := (SELECT \`id\` FROM \`StaffUser\` WHERE \`email\` = 'demo.apple@gmail.com'); SET @store := (SELECT \`storeId\` FROM \`StaffUser\` WHERE \`id\` = @staff); SET @reward := (SELECT r.\`id\` FROM \`Reward\` r JOIN \`CardDesign\` d ON d.\`id\` = r.\`cardDesignId\` WHERE d.\`storeId\` = @store ORDER BY r.\`cost\` LIMIT 1); SET @today := TIMESTAMP(DATE(UTC_TIMESTAMP())); -- Arrêt net si le compte de démonstration n'existe pas (colonne NOT NULL : l'insertion échoue). INSERT INTO \`Campaign\` (\`id\`, \`storeId\`, \`title\`, \`message\`, \`sentByName\`, \`cards\`, \`appleDevices\`, \`createdAt\`) VALUES (${q(id('camp', 1))}, @store, 'Café Démo', 'Nouveau : le cookie maison est arrivé ! Venez le goûter avec votre café.', 'Tony Averty', ${Math.round(CUSTOMERS * 0.7)}, ${Math.round(CUSTOMERS * 0.55)}, ${at(41, 9, 12)}), (${q(id('camp', 2))}, @store, 'Happy hour', '-20 % sur les boissons chaudes ce samedi de 15 h à 17 h.', 'Tony Averty', ${Math.round(CUSTOMERS * 0.85)}, ${Math.round(CUSTOMERS * 0.66)}, ${at(12, 10, 3)}); `); out.push('INSERT INTO `Customer` (`id`, `firstName`, `email`, `consentAt`, `birthMonth`, `birthDay`, `createdAt`) VALUES'); out.push( customers .map((c) => { const t = at(c.created, ...c.createdTime); return ` (${q(id('cust', c.n))}, ${q(c.name)}, ${q(c.email)}, ${t}, ${c.birth ? c.birth[0] : 'NULL'}, ${c.birth ? c.birth[1] : 'NULL'}, ${t})`; }) .join(',\n') + ';\n', ); out.push('INSERT INTO `LoyaltyCard` (`id`, `storeId`, `customerId`, `serial`, `authToken`, `accessKey`, `balance`, `passUpdatedAt`, `lastCreditAt`, `createdAt`, `updatedAt`) VALUES'); out.push( customers .map((c) => { const t = at(c.created, ...c.createdTime); return ` (${q(id('card', c.n))}, @store, ${q(id('cust', c.n))}, ${q(c.serial)}, REPLACE(UUID(), '-', ''), CONCAT(REPLACE(UUID(), '-', ''), REPLACE(UUID(), '-', '')), ${c.balance}, ${c.lastCredit ?? t}, ${c.lastCredit ?? 'NULL'}, ${t}, ${c.lastCredit ?? t})`; }) .join(',\n') + ';\n', ); const apple = customers.filter((c) => c.apple); out.push('INSERT INTO `AppleDevice` (`id`, `deviceLibraryId`, `pushToken`) VALUES'); out.push(apple.map((c) => ` (${q(id('dev', c.n))}, ${q(id('lib', c.n))}, ${q('0'.repeat(56) + String(c.n).padStart(8, '0'))})`).join(',\n') + ';\n'); out.push('INSERT INTO `AppleRegistration` (`deviceId`, `cardId`, `createdAt`) VALUES'); out.push(apple.map((c) => ` (${q(id('dev', c.n))}, ${q(id('card', c.n))}, ${at(c.created, ...c.createdTime)})`).join(',\n') + ';\n'); const CHUNK = 500; for (let i = 0; i < txRows.length; i += CHUNK) { out.push('INSERT INTO `Transaction` (`id`, `storeId`, `cardId`, `staffId`, `type`, `amountCents`, `points`, `balanceAfter`, `rewardId`, `createdAt`) VALUES'); out.push( txRows .slice(i, i + CHUNK) .map((t) => ` (${q(t.id)}, @store, ${q(t.card)}, @staff, '${t.type}', ${t.amount ?? 'NULL'}, ${t.points}, ${t.after}, ${t.reward ? '@reward' : 'NULL'}, ${t.when})`) .join(',\n') + ';\n', ); } out.push('COMMIT;\n'); const file = path.join(__dirname, '..', 'prisma', 'manual-migrations', '2026-10-15-stats-demo.sql'); fs.writeFileSync(file, out.join('\n')); const redeems = txRows.filter((t) => t.type === 'REDEEM').length; console.log(`${path.relative(process.cwd(), file)} : ${CUSTOMERS} clients, ${txRows.length - redeems} passages, ${redeems} récompenses, ${apple.length} iPhones.`);