From 59039ea4116455f08f8ec191ae5b4019ce7c2a60 Mon Sep 17 00:00:00 2001 From: Tony AVERTY Date: Thu, 22 Oct 2026 14:44:48 +0200 Subject: [PATCH] =?UTF-8?q?feat(plans):=20plafonds=20du=20plan=20gratuit?= =?UTF-8?q?=20appliqu=C3=A9s=20c=C3=B4t=C3=A9=20serveur?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1 projet, 50 prospects, 100 mails et 5 jobs IA par mois (mois calendaire, heure de Paris), réunis dans src/limits.js. L'usage se recalcule depuis les tables, avec un journal d'usage (migration 3) qui survit à la suppression d'un projet. Dépassement : refus explicite (403, code plan_limit, lien /tarifs) sans perte de données ; un administrateur n'a pas de limite. Barres d'usage dans Mon compte et sur le tableau de bord, page Tarifs mise à jour. --- public/app.css | 26 +++++ src/handlers.js | 18 ++- src/migrations.js | 26 +++++ src/projects.js | 11 +- src/routes.js | 26 +++-- src/services/csv.js | 4 +- src/services/jobs.js | 14 ++- src/services/plans.js | 127 +++++++++++++++++++++ src/site/pages.js | 2 +- src/views.js | 18 ++- test/plans.test.js | 251 ++++++++++++++++++++++++++++++++++++++++++ test/site.test.js | 3 +- 12 files changed, 506 insertions(+), 20 deletions(-) create mode 100644 src/services/plans.js create mode 100644 test/plans.test.js diff --git a/public/app.css b/public/app.css index 17115e4..dd48fe6 100644 --- a/public/app.css +++ b/public/app.css @@ -340,3 +340,29 @@ form.send { margin-top: 6px; padding-top: 0; border-top: 0; } animation-duration: .01ms !important; animation-iteration-count: 1 !important; transition-duration: .01ms !important; } } + +/* ---------- Usage du mois (largeurs par classes : la CSP interdit le style en ligne) ---------- */ +.usage-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 12px; } +.bar.usage > span::after { content: none; } +.bar.usage.full > span { background: var(--err); } +.bar > span.w-0 { width: 0%; } +.bar > span.w-5 { width: 5%; } +.bar > span.w-10 { width: 10%; } +.bar > span.w-15 { width: 15%; } +.bar > span.w-20 { width: 20%; } +.bar > span.w-25 { width: 25%; } +.bar > span.w-30 { width: 30%; } +.bar > span.w-35 { width: 35%; } +.bar > span.w-40 { width: 40%; } +.bar > span.w-45 { width: 45%; } +.bar > span.w-50 { width: 50%; } +.bar > span.w-55 { width: 55%; } +.bar > span.w-60 { width: 60%; } +.bar > span.w-65 { width: 65%; } +.bar > span.w-70 { width: 70%; } +.bar > span.w-75 { width: 75%; } +.bar > span.w-80 { width: 80%; } +.bar > span.w-85 { width: 85%; } +.bar > span.w-90 { width: 90%; } +.bar > span.w-95 { width: 95%; } +.bar > span.w-100 { width: 100%; } diff --git a/src/handlers.js b/src/handlers.js index d0b15a7..a94e3e9 100644 --- a/src/handlers.js +++ b/src/handlers.js @@ -11,6 +11,8 @@ import { resolveCredentials } from './claudelink.js'; import { userRepoRoot } from './users.js'; import { quotaAlerts } from './services/budget.js'; import { notify } from './services/notify.js'; +import { quotaFor, recordUsage, planLimitMessage } from './services/plans.js'; +import { getUser } from './users.js'; import { evolutionMail } from './services/mailhtml.js'; import { getProject, repoDir, forgejoToken, globalSmtp, sentSince, getTemplate, saveTemplate, pickVariant } from './projects.js'; @@ -105,7 +107,11 @@ export function makeHandlers(app) { ? await followupCandidates(db, project) : await db.prepare(`SELECT * FROM prospects WHERE project_id = ? AND status = 'new' AND email NOT IN (SELECT email FROM blacklist) ORDER BY score DESC, id LIMIT 100`).all(project.id); - const n = allowedToSend({ + // Plafond mensuel du plan : on n'envoie que ce qui reste (le reste attend, rien n'est perdu) + const user = await getUser(db, userId); + const mq = await quotaFor(db, user, 'mails'); + if (!mq.unlimited && mq.remaining <= 0) throw new Error(planLimitMessage(user, mq)); + const n0 = allowedToSend({ requested: ctx.params.count, available: candidates.length, projectCap: project.dailyMailCap, @@ -113,6 +119,7 @@ export function makeHandlers(app) { globalCap: Number(await getSetting(db, userId, 'global_daily_cap', '100')), sentTodayGlobal: await sentSince(db, day, userId), }); + const n = mq.unlimited ? n0 : Math.min(n0, mq.remaining); if (n === 0) throw new Error(kind === 'followup' ? 'Plafond quotidien atteint ou aucune relance due' : 'Plafond quotidien atteint ou aucun prospect à contacter'); const transport = (app.createTransport || createTransport)(project.smtp); @@ -155,6 +162,7 @@ export function makeHandlers(app) { try { await transport.sendMail(mail); await log.run(project.id, p.id, p.email, now(), null, kind, variant, mail.subject, mail.messageId); + await recordUsage(db, userId, 'mail'); if (kind === 'initial') await markInitial.run('sent', now(), variant, p.id); else await markFollowup.run(now(), p.id); sent++; @@ -206,6 +214,10 @@ export function makeHandlers(app) { // Domaines déjà connus de ce projet : Claude ne les recherche pas une 2e fois. La liste d'opposition, // commune à tous les comptes, n'entre pas dans le prompt (elle est appliquée à l'insertion, ci-dessous). + const user = await getUser(db, userId); + const pq = await quotaFor(db, user, 'prospects'); + let room = pq.unlimited ? Infinity : pq.remaining; + let capped = false; const exclude = (await db.prepare(` SELECT DISTINCT substr(email, instr(email, '@') + 1) d FROM prospects WHERE project_id = ? LIMIT 300`).all(project.id)).map((r) => r.d); @@ -234,8 +246,10 @@ export function makeHandlers(app) { sink.push(async () => { for (const p of parsed) { if (await optedOut.get(p.email)) continue; + if (room <= 0) { capped = true; continue; } const res = await insert.run(project.id, p.company, p.email, p.website, p.city, p.sector, p.hook, p.source, p.score, now()); if (res.changes) { + room--; found++; message = `${found}/${count} — ${p.company}`; await report(); @@ -254,7 +268,7 @@ export function makeHandlers(app) { onText('\n'); await sink.flush(); addUsage(ctx, r); - return { found, requested: count, stoppedBy: r.subtype }; + return { found, requested: count, stoppedBy: r.subtype, ...(capped ? { capped: true } : {}) }; }, async template(ctx) { diff --git a/src/migrations.js b/src/migrations.js index ac4d8ba..42b1654 100644 --- a/src/migrations.js +++ b/src/migrations.js @@ -362,6 +362,32 @@ export const MIGRATIONS = [ ) ${T}`, ], }, + { + // J5 : journal d'usage. Les envois et les jobs IA du mois se comptent ici (et non dans mail_log / jobs) pour qu'un projet + // supprimé n'efface pas la consommation du mois. Pas de compteur : on additionne les lignes, rien ne peut dériver. + name: 'journal_usage', + sqlite: [ + `CREATE TABLE usage_events ( + id INTEGER PRIMARY KEY, + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + kind TEXT NOT NULL, -- mail | ai_job + ref INTEGER, -- ai_job : id du job (il peut disparaître avec son projet, l'événement reste) + at INTEGER NOT NULL + )`, + 'CREATE INDEX usage_events_user ON usage_events(user_id, kind, at)', + ], + mysql: [ + `CREATE TABLE IF NOT EXISTS usage_events ( + id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY, + user_id BIGINT NOT NULL, + kind VARCHAR(20) NOT NULL, -- mail | ai_job + ref BIGINT NULL, -- ai_job : id du job (il peut disparaître avec son projet, l'événement reste) + at BIGINT NOT NULL, + KEY usage_events_user (user_id, kind, at), + CONSTRAINT usage_events_user_fk FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE + ) ${T}`, + ], + }, ]; // ---------- Aides de la migration 2 ---------- diff --git a/src/projects.js b/src/projects.js index b144250..497e95f 100644 --- a/src/projects.js +++ b/src/projects.js @@ -2,6 +2,8 @@ import { join } from 'node:path'; import { now, getSetting } from './db.js'; import { encryptJson, decryptJson, decrypt } from './crypto.js'; import { HttpError } from './http.js'; +import { getUser } from './users.js'; +import { assertRoom, withUserLock } from './services/plans.js'; // Un dossier de clones par utilisateur : data/repos// export const repoDir = (cfg, userId, id) => join(cfg.dataDir, 'repos', String(Number(userId)), String(Number(id))); @@ -47,8 +49,13 @@ export async function listProjects(app, userId) { } export async function createProject(app, { userId, name, gitUrl }) { - const r = await app.db.prepare('INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, ?, ?, ?)').run(Number(userId), name, gitUrl, now()); - return Number(r.lastInsertRowid); + const user = await getUser(app.db, userId); + if (!user) throw new HttpError(404, 'Compte introuvable'); + return withUserLock(user.id, async () => { + await assertRoom(app.db, user, 'projects', 1, { note: 'Supprime un projet pour en créer un autre.' }); + const r = await app.db.prepare('INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, ?, ?, ?)').run(user.id, name, gitUrl, now()); + return Number(r.lastInsertRowid); + }); } // Les secrets vides dans le formulaire = on garde l'ancien (le formulaire ne les réaffiche jamais) diff --git a/src/routes.js b/src/routes.js index dc04b2a..9bb9307 100644 --- a/src/routes.js +++ b/src/routes.js @@ -3,7 +3,7 @@ import { encrypt, encryptJson, decryptJson, verifyUnsubToken } from './crypto.js import { html, json, redirect, readBody, HttpError } from './http.js'; import { startLogin, finishLogin, destroySession, getSession, checkOrigin } from './auth.js'; import { verifyCaptcha } from './captcha.js'; -import { deleteUser, normalizeEmail } from './users.js'; +import { deleteUser, normalizeEmail, getUser } from './users.js'; import { assertCanRunAi, getLinkState, linkApiKey, linkSubscriptionToken, linkServer, unlink, testLink, lastConsent, MODES, @@ -23,6 +23,7 @@ import { notify, notifyConfig, EVENTS, WEBHOOK_RE } from './services/notify.js'; import { budgetState, AI_JOBS } from './services/budget.js'; import { sendWeeklyReport } from './services/report.js'; import { exportProspects, importProspects } from './services/csv.js'; +import { quotaFor, planLimitError, withUserLock, assertRoom, usageView } from './services/plans.js'; import { history, saveSnapshot } from './services/metrics.js'; import { evolutionHtml } from './services/markdown.js'; import { @@ -113,7 +114,7 @@ export function registerRoutes(router, app) { projects.push({ project: p, smtp: publicConfig(full.smtp, 'pass'), dbCfg: publicConfig(full.dbCfg, 'password'), imap: publicConfig(full.imapCfg, 'pass') }); } html(res, dashboardPage({ - email: session.email, projects, forgejoHost: await getSetting(db, userId, 'forgejo_host'), + email: session.email, projects, forgejoHost: await getSetting(db, userId, 'forgejo_host'), usage: await usageView(db, await getUser(db, userId)), })); }); @@ -216,7 +217,7 @@ export function registerRoutes(router, app) { const t = url.searchParams.get('t'); html(res, accountPage({ user: session.user, error: url.searchParams.get('e'), link: await getLinkState(db, session.userId), - consent: await lastConsent(db, session.userId), cliModeEnabled, + consent: await lastConsent(db, session.userId), cliModeEnabled, usage: await usageView(db, await getUser(db, session.userId)), notice: t === 'unlinked' ? { ok: true, text: 'Liaison supprimée : le secret a été effacé et tes jobs IA en attente ont été annulés.' } : t === 'ok' || t === 'ko' ? { ok: t === 'ok', text: String(url.searchParams.get('m') || '').slice(0, 300) } : null, })); @@ -288,8 +289,11 @@ export function registerRoutes(router, app) { let id; try { id = await createProject(app, { userId, name, gitUrl }); } catch (e) { if (await exists()) throw new HttpError(409, 'Ce dépôt est déjà un projet'); throw e; } - await enqueue(db, { userId, projectId: id, type: 'analyze' }, aiOpts); - json(res, { id }); + // Plafond de jobs IA atteint : le projet est créé quand même (rien n'est perdu), seule l'analyse attend + let notice = null; + try { await enqueue(db, { userId, projectId: id, type: 'analyze' }, aiOpts); } + catch (e) { if (e.code !== 'plan_limit') throw e; notice = e.message; } + json(res, { id, ...(notice ? { notice } : {}) }); }, { limit: 'project_create' }); router.post('/api/projects/:id/delete', async (ctx) => { @@ -370,7 +374,8 @@ export function registerRoutes(router, app) { await db.prepare('UPDATE projects SET followup_enabled = ?, followup_days = ? WHERE id = ?').run(enabled ? 1 : 0, int(b.days, 2, 30, 7), p.id); json(res, { ok: true }); }); - router.post('/api/projects/:id/prospect', jobRoute('prospect', (b) => ({ count: int(b.count, 1, 50, 10) }), (p) => { + router.post('/api/projects/:id/prospect', jobRoute('prospect', (b) => ({ count: int(b.count, 1, 50, 10) }), async (p) => { + await assertRoom(db, await getUser(db, p.userId), 'prospects'); if (!p.targetValidated) throw new HttpError(400, 'Valide la cible avant de prospecter'); })); router.post('/api/projects/:id/evolution', jobRoute('evolution', (b) => ({ @@ -482,8 +487,13 @@ export function registerRoutes(router, app) { const { req, res } = ctx; const p = await project(ctx); const b = await readBody(req, { max: 1024 * 1024 }); - try { json(res, await importProspects(db, p.id, String(b.csv || ''))); } - catch (e) { throw new HttpError(400, e.message); } + try { + json(res, await withUserLock(ctx.session.userId, async () => { + const u = await getUser(db, ctx.session.userId); + const q = await quotaFor(db, u, 'prospects'); + return importProspects(db, p.id, String(b.csv || ''), { limit: q.remaining, limitError: q.unlimited ? null : planLimitError(u, q, { wanted: q.remaining + 1, note: "Rien n'a été importé." }) }); + })); + } catch (e) { throw e instanceof HttpError ? e : new HttpError(400, e.message); } }, { limit: 'csv' }); router.get('/api/projects/:id/history', async (ctx) => { diff --git a/src/services/csv.js b/src/services/csv.js index 330360f..4865c70 100644 --- a/src/services/csv.js +++ b/src/services/csv.js @@ -75,7 +75,8 @@ const MAX_ROWS = 2000; // Notre propre export préfixe les formules par ' : on l'enlève à la relecture const unformula = (s) => (/^'[=+\-@]/.test(s) ? s.slice(1) : s); -export async function importProspects(db, projectId, text, { at = now() } = {}) { +// `limit` : places restantes dans le plan (null = illimité) ; au-delà, l'import entier est annulé avec `limitError` +export async function importProspects(db, projectId, text, { at = now(), limit = null, limitError = null } = {}) { const rows = parseCsv(text); if (rows.length < 2) throw new Error('Fichier vide ou sans en-tête'); const header = rows[0].map(norm); @@ -106,6 +107,7 @@ export async function importProspects(db, projectId, text, { at = now() } = {}) if (seen.has(email) || await exists.get(projectId, email)) { res.duplicates++; continue; } seen.add(email); if (await optOut.get(email)) { res.blacklisted++; continue; } + if (limit != null && res.imported >= limit) throw limitError || new Error('Plafond de prospects atteint'); const s = Number(get(r, 'score')); await insert.run( projectId, get(r, 'company') || email.split('@')[1], email, httpUrl(get(r, 'website', 300)), get(r, 'city', 100) || null, diff --git a/src/services/jobs.js b/src/services/jobs.js index 546acbe..bde4b6c 100644 --- a/src/services/jobs.js +++ b/src/services/jobs.js @@ -5,6 +5,7 @@ import { AI_JOBS } from './budget.js'; import { getUser } from '../users.js'; import { aiRefusal, assertCanRunAi } from '../claudelink.js'; import { waitCool } from './thermal.js'; +import { assertRoom, recordUsage, withUserLock, MAIL_JOBS } from './plans.js'; /** * Met un job en file pour un utilisateur. Point de passage obligé de toutes les routes et tâches de fond : @@ -28,9 +29,16 @@ export async function enqueue(db, { userId, projectId, type, params = {}, runAft ? await db.prepare("SELECT id FROM jobs WHERE user_id = ? AND project_id IS NULL AND type = ? AND status IN ('queued','running')").get(user.id, type) : await db.prepare("SELECT id FROM jobs WHERE project_id = ? AND type = ? AND status IN ('queued','running')").get(projectId, type); if (running) return { id: running.id, existing: true }; - const r = await db.prepare('INSERT INTO jobs(user_id, project_id, type, params_json, created_at, run_after) VALUES(?, ?, ?, ?, ?, ?)') - .run(user.id, projectId ?? null, type, JSON.stringify(params), now(), runAfter); - return { id: Number(r.lastInsertRowid), existing: false }; + // Plafonds du plan : compter puis écrire dans la même section critique (deux requêtes simultanées ne passent pas toutes deux) + return withUserLock(user.id, async () => { + if (AI_JOBS.has(type)) await assertRoom(db, user, 'aiJobs'); + if (MAIL_JOBS.has(type)) await assertRoom(db, user, 'mails'); + const r = await db.prepare('INSERT INTO jobs(user_id, project_id, type, params_json, created_at, run_after) VALUES(?, ?, ?, ?, ?, ?)') + .run(user.id, projectId ?? null, type, JSON.stringify(params), now(), runAfter); + const id = Number(r.lastInsertRowid); + if (AI_JOBS.has(type)) await recordUsage(db, user.id, 'ai_job', { ref: id }); + return { id, existing: false }; + }); } /** diff --git a/src/services/plans.js b/src/services/plans.js new file mode 100644 index 0000000..5b7e66f --- /dev/null +++ b/src/services/plans.js @@ -0,0 +1,127 @@ +// Plafonds des plans, appliqués côté serveur. Les valeurs vivent dans src/limits.js (PLAN_LIMITS). +// +// - projets et prospects : totaux du compte, recomptés dans leurs tables ; +// - mails et jobs IA : par mois calendaire (heure de Paris), recomptés depuis le journal d'usage (usage_events). +// Aucun compteur n'est stocké : chaque consommation est une ligne, et l'usage est une somme. Le journal d'usage survit à la +// suppression d'un projet (sinon supprimer puis recréer le projet remettrait le mois à zéro). +// Un dépassement refuse l'action avec un message clair et un lien vers /tarifs ; il ne supprime ni ne tronque jamais de données. +import { now } from '../db.js'; +import { HttpError } from '../http.js'; +import { PLAN_LIMITS, PLAN_LABELS } from '../limits.js'; +import { parisParts, parisTime } from './paris-time.js'; + +export const USAGE_KINDS = ['projects', 'prospects', 'mails', 'aiJobs']; + +const NOUNS = { projects: ['projet', 'projets'], prospects: ['prospect', 'prospects'], mails: ['mail', 'mails'], aiJobs: ['job IA', 'jobs IA'] }; +export const KIND_LABELS = { projects: 'Projets', prospects: 'Prospects', mails: 'Mails ce mois-ci', aiJobs: 'Jobs IA ce mois-ci' }; +const MONTHLY = new Set(['mails', 'aiJobs']); + +/** Clé du plan appliqué : un administrateur n'a aucune limite ; un plan inconnu retombe sur « gratuit » (jamais sur illimité). */ +export function planOf(user) { + if (user?.isAdmin || user?.plan === 'admin') return 'admin'; + return PLAN_LIMITS[user?.plan] ? user.plan : 'free'; +} +export const limitsFor = (user) => PLAN_LIMITS[planOf(user)]; + +/** Bornes [début, fin[ du mois calendaire à Paris, en secondes. */ +export function monthBounds(at = now()) { + const p = parisParts(new Date(at * 1000)); + const [ny, nm] = p.month === 12 ? [p.year + 1, 1] : [p.year, p.month + 1]; + return { + start: Math.floor(parisTime(p.year, p.month, 1, 0).getTime() / 1000), + end: Math.floor(parisTime(ny, nm, 1, 0).getTime() / 1000), + }; +} + +/** + * Usage d'un compte, recalculé depuis les tables. + * Un job IA compte dès sa mise en file, sauf s'il a été annulé ou refusé sans jamais démarrer. + */ +export async function usageOf(db, userId, { at = now() } = {}) { + const { start, end } = monthBounds(at); + const n = async (sql, ...p) => Number((await db.prepare(sql).get(...p)).n); + const id = Number(userId); + return { + projects: await n('SELECT COUNT(*) n FROM projects WHERE user_id = ?', id), + prospects: await n('SELECT COUNT(*) n FROM prospects x JOIN projects p ON p.id = x.project_id WHERE p.user_id = ?', id), + mails: await n("SELECT COUNT(*) n FROM usage_events WHERE user_id = ? AND kind = 'mail' AND at >= ? AND at < ?", id, start, end), + aiJobs: await n(`SELECT COUNT(*) n FROM usage_events e LEFT JOIN jobs j ON j.id = e.ref + WHERE e.user_id = ? AND e.kind = 'ai_job' AND e.at >= ? AND e.at < ? + AND NOT (j.id IS NOT NULL AND j.started_at IS NULL AND j.status IN ('cancelled', 'error'))`, id, start, end), + period: { start, end }, + }; +} + +/** Une consommation du mois : un mail parti, un job IA mis en file. */ +export async function recordUsage(db, userId, kind, { ref = null, at = now() } = {}) { + if (kind !== 'mail' && kind !== 'ai_job') throw new Error(`Type d'usage inconnu : ${kind}`); + await db.prepare('INSERT INTO usage_events(user_id, kind, ref, at) VALUES(?, ?, ?, ?)').run(Number(userId), kind, ref, at); +} + +/** @returns {{kind: string, used: number, limit: number|null, remaining: number|null, unlimited: boolean}} */ +export async function quotaFor(db, user, kind, { at = now() } = {}) { + if (!USAGE_KINDS.includes(kind)) throw new Error(`Plafond inconnu : ${kind}`); + const limit = limitsFor(user)[kind]; + const used = (await usageOf(db, user.id, { at }))[kind]; + return { kind, used, limit, remaining: limit == null ? null : Math.max(0, limit - used), unlimited: limit == null }; +} + +const plural = (n, kind) => NOUNS[kind][n > 1 ? 1 : 0]; + +/** Message destiné à l'écran quand un plafond bloque une action. Toujours : ce qui est atteint, ce qui reste intact, où voir les offres. */ +export function planLimitMessage(user, quota, { wanted = 1, note = '' } = {}) { + const { kind, used, limit, remaining } = quota; + const period = MONTHLY.has(kind) ? ' ce mois-ci' : ''; + const where = remaining > 0 && wanted > remaining + ? `Il te reste ${remaining} ${plural(remaining, kind)}${period} sur ${limit}.` + : `Tu as atteint le plafond du plan ${PLAN_LABELS[planOf(user)]} : ${used} ${plural(used, kind)}${period} sur ${limit}.`; + return `${where}${note ? ` ${note}` : ''} Rien n'est supprimé ni perdu. Voir les tarifs : /tarifs`; +} + +export function planLimitError(user, quota, opts) { + return new HttpError(403, planLimitMessage(user, quota, opts), { + expose: true, code: 'plan_limit', + data: { kind: quota.kind, used: quota.used, limit: quota.limit, upgradeUrl: '/tarifs' }, + }); +} + +/** Refuse (403, code plan_limit) si `wanted` unités ne tiennent pas dans le plafond. Renvoie le quota sinon. */ +export async function assertRoom(db, user, kind, wanted = 1, { at = now(), note = '' } = {}) { + const q = await quotaFor(db, user, kind, { at }); + if (!q.unlimited && q.remaining < wanted) throw planLimitError(user, q, { wanted, note }); + return q; +} + +/** Types de jobs qui envoient des mails de prospection (comptés dans le plafond mensuel de mails). */ +export const MAIL_JOBS = new Set(['send', 'followup']); + +// Section critique par compte : « compter puis écrire » ne doit pas être entrelacé par deux requêtes simultanées du même +// compte (sinon deux créations de projet passeraient toutes deux sous le plafond). Un seul processus : le verrou est en mémoire. +const chains = new Map(); +export async function withUserLock(userId, fn) { + const key = Number(userId); + const prev = chains.get(key) || Promise.resolve(); + let release; + const gate = new Promise((r) => { release = r; }); + const tail = prev.then(() => gate); + chains.set(key, tail); + await prev; + try { return await fn(); } finally { + release(); + if (chains.get(key) === tail) chains.delete(key); + } +} + +/** Données d'affichage de l'usage du mois (barres de Mon compte et du tableau de bord). */ +export async function usageView(db, user, { at = now() } = {}) { + const usage = await usageOf(db, user.id, { at }); + const limits = limitsFor(user); + return { + plan: planOf(user), planLabel: PLAN_LABELS[planOf(user)], + items: USAGE_KINDS.map((kind) => { + const used = usage[kind], limit = limits[kind]; + return { kind, label: KIND_LABELS[kind], used, limit, pct: limit == null ? 0 : Math.min(100, Math.round((used / limit) * 100)), full: limit != null && used >= limit }; + }), + period: usage.period, + }; +} diff --git a/src/site/pages.js b/src/site/pages.js index d9173cd..45e81dc 100644 --- a/src/site/pages.js +++ b/src/site/pages.js @@ -317,7 +317,7 @@ export function pricingPage({ appUrl }) {
  • Mails par mois100
  • Jobs IA par mois5
  • -

    Ces plafonds sont annoncés dès maintenant. L'outil ne les applique pas encore automatiquement : cette vérification technique arrive prochainement.

    +

    Ces plafonds sont appliqués par le serveur. Les mails et les jobs IA se comptent par mois calendaire (heure de Paris) et repartent à zéro le 1er. Un plafond atteint refuse la nouvelle action sans rien supprimer.

    Créer mon compte
    diff --git a/src/views.js b/src/views.js index 0d6e510..018c7c4 100644 --- a/src/views.js +++ b/src/views.js @@ -57,6 +57,18 @@ ${email ? `
    `; } +// Usage du mois : une barre par plafond du plan (largeurs par classes w-N, la CSP interdit le style en ligne) +export function usagePanel(u) { + if (!u) return ''; + const rows = u.items.map((i) => `
  • ${esc(i.label)}${i.used}${i.limit == null ? '' : ` / ${i.limit}`}
    ${i.limit == null ? '' : `
    `}
  • `).join(''); + const full = u.items.filter((i) => i.full); + return `
    +

    Usage du mois plan ${esc(u.planLabel)}

    +
      ${rows}
    + ${full.length ? `

    Plafond atteint : ${full.map((i) => esc(i.label.toLowerCase())).join(', ')}. Rien n'est perdu. Voir les tarifs

    ` : u.plan === 'free' ? '

    Les plafonds se renouvellent le 1er du mois (heure de Paris). Voir les tarifs

    ' : ''} +
    `; +} + const PROVIDER_NAMES = { google: 'Google', apple: 'Apple' }; // Section « Liaison Claude » de Mon compte : état, test, changement de mode, déliaison. Jamais le secret, ni même un masque @@ -88,7 +100,7 @@ function linkSection(link, consent) { `; } -export function accountPage({ user, error, link = null, consent = null, notice = null }) { +export function accountPage({ user, error, link = null, consent = null, notice = null, usage = null }) { return layout({ title: 'Mon compte', email: user.email, body: `

    Mon compte

    @@ -99,6 +111,7 @@ export function accountPage({ user, error, link = null, consent = null, notice = ${notice ? `

    ${esc(notice.text)}

    ` : ''} +${usagePanel(usage)} ${linkSection(link, consent)}

    Supprimer mon compte

    @@ -339,12 +352,13 @@ function projectItem(p, smtp, dbCfg, imap) { `; } -export function dashboardPage({ email, projects, forgejoHost }) { +export function dashboardPage({ email, projects, forgejoHost, usage = null }) { return layout({ title: 'Projets', email, body: `

    Projets

    +${usagePanel(usage)}
    + Nouveau projet
    diff --git a/test/plans.test.js b/test/plans.test.js new file mode 100644 index 0000000..7027850 --- /dev/null +++ b/test/plans.test.js @@ -0,0 +1,251 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { randomBytes } from 'node:crypto'; +import { setSetting, now } from '../src/db.js'; +import { testDb } from './helpers/db.js'; +import { addUser } from './helpers/users.js'; +import { Worker, enqueue, cancelJob } from '../src/services/jobs.js'; +import { makeHandlers } from '../src/handlers.js'; +import { createProject, saveSecretConfig } from '../src/projects.js'; +import { getUser } from '../src/users.js'; +import { PLAN_LIMITS } from '../src/limits.js'; +import { monthBounds, usageOf, quotaFor, assertRoom, recordUsage, planOf, usageView } from '../src/services/plans.js'; +import { encrypt } from '../src/crypto.js'; +import { importProspects } from '../src/services/csv.js'; +import { startApp } from './helpers/server.js'; + +// Plafonds du plan gratuit appliqués côté serveur : à la limite exacte, sans compteur qui dérive, sans perte de données. + +const LINK = { v: 1, mode: 'api_key', valid: true }; +const free = (db, extra = {}) => addUser(db, { admin: false, link: LINK, ...extra }); + +async function world() { + const db = await testDb(); + const sent = []; + const app = { + db, cfg: { dataDir: '/tmp/x', appUrl: 'https://ai.test', secretKey: randomBytes(32), sandbox: { enabled: false } }, + createTransport: () => ({ verify: async () => true, sendMail: async (m) => { sent.push(m); }, close() {} }), + }; + return { db, app, sent }; +} +const proj = async (w, userId, n = 1) => Number((await w.db.prepare('INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, ?, ?, ?)').run(userId, `p${n}`, `https://git.test/u${userId}/r${n}.git`, now())).lastInsertRowid); + +test('les limites viennent d\'un seul module et reprennent le cadrage', () => { + assert.deepEqual(PLAN_LIMITS.free, { projects: 1, prospects: 50, mails: 100, aiJobs: 5 }); +}); + +test('mois calendaire à l\'heure de Paris, changement d\'heure compris', () => { + const iso = (t) => new Date(t * 1000).toISOString(); + // 31 oct. 2026 23:30 UTC = 1er nov. 00:30 à Paris (heure d'hiver depuis le 25 oct.) : c'est déjà novembre + let b = monthBounds(Date.parse('2026-10-31T23:30:00Z') / 1000); + assert.equal(iso(b.start), '2026-10-31T23:00:00.000Z'); + assert.equal(iso(b.end), '2026-11-30T23:00:00.000Z'); + // 31 oct. 22:30 UTC = 23:30 à Paris : encore octobre (heure d'été jusqu'au 25 oct. : décalage +1 h seulement après) + b = monthBounds(Date.parse('2026-10-31T22:30:00Z') / 1000); + assert.equal(iso(b.start), '2026-09-30T22:00:00.000Z'); + assert.equal(iso(b.end), '2026-10-31T23:00:00.000Z'); + b = monthBounds(Date.parse('2026-12-15T12:00:00Z') / 1000); + assert.equal(iso(b.end), '2026-12-31T23:00:00.000Z'); +}); + +test('plan : un administrateur n\'a pas de limite, un plan inconnu retombe sur gratuit', async () => { + const w = await world(); + const a = await getUser(w.db, await addUser(w.db, { admin: true })); + const f = await getUser(w.db, await free(w.db)); + assert.equal(planOf(a), 'admin'); + assert.equal(planOf(f), 'free'); + assert.equal(planOf({ ...f, plan: 'invente' }), 'free'); + assert.equal(planOf({ ...f, plan: 'admin' }), 'admin', 'plan « admin » explicite'); + assert.equal((await quotaFor(w.db, a, 'mails')).unlimited, true); + await assert.doesNotReject(assertRoom(w.db, a, 'projects', 1000)); +}); + +test('projets : le 2e est refusé (403 plan_limit, lien /tarifs), un admin crée sans limite, créations simultanées bornées', async () => { + const w = await world(); + const u = await free(w.db); + await createProject(w.app, { userId: u, name: 'A', gitUrl: 'https://git.test/a/a.git' }); + await assert.rejects(createProject(w.app, { userId: u, name: 'B', gitUrl: 'https://git.test/a/b.git' }), (e) => { + assert.equal(e.status, 403); + assert.equal(e.code, 'plan_limit'); + assert.equal(e.data.upgradeUrl, '/tarifs'); + assert.match(e.message, /plafond du plan gratuit/); + assert.match(e.message, /Rien n'est supprimé ni perdu/); + assert.match(e.message, /\/tarifs/); + return true; + }); + assert.equal((await w.db.prepare('SELECT COUNT(*) n FROM projects WHERE user_id = ?').get(u)).n, 1, 'aucun projet supprimé'); + const admin = await addUser(w.db, { admin: true }); + for (let i = 0; i < 3; i++) await createProject(w.app, { userId: admin, name: `P${i}`, gitUrl: `https://git.test/z/${i}.git` }); + const u2 = await free(w.db); + const res = await Promise.allSettled([1, 2, 3, 4].map((i) => createProject(w.app, { userId: u2, name: `C${i}`, gitUrl: `https://git.test/c/${i}.git` }))); + assert.equal(res.filter((r) => r.status === 'fulfilled').length, 1, 'une seule création passe malgré la simultanéité'); +}); + +test('jobs IA : 5 par mois, le 6e est refusé ; annulé sans démarrer = rendu ; projet supprimé = toujours compté', async () => { + const w = await world(); + const u = await free(w.db); + const p = await proj(w, u); + const types = ['analyze', 'prospect', 'template', 'followup_template', 'evolution']; + const ids = []; + for (const type of types) ids.push((await enqueue(w.db, { userId: u, projectId: p, type })).id); + assert.equal((await usageOf(w.db, u)).aiJobs, 5); + await assert.rejects(enqueue(w.db, { userId: u, projectId: p, type: 'analyze' }).then(() => enqueue(w.db, { userId: u, projectId: null, type: 'analyze' })), { status: 403, code: 'plan_limit' }); + // Le même job déjà en file n'est pas recompté (dédoublonnage) + assert.equal((await enqueue(w.db, { userId: u, projectId: p, type: 'template' })).existing, true); + // Annulé avant de démarrer : rendu + await cancelJob(w.db, u, ids[0]); + assert.equal((await usageOf(w.db, u)).aiJobs, 4); + await enqueue(w.db, { userId: u, projectId: p, type: 'analyze' }); + await assert.rejects(enqueue(w.db, { userId: u, projectId: null, type: 'template' }), { code: 'plan_limit' }, 'à la limite exacte'); + // Supprimer le projet efface ses jobs, pas la consommation du mois + await w.db.prepare('DELETE FROM projects WHERE id = ?').run(p); + assert.equal((await w.db.prepare('SELECT COUNT(*) n FROM jobs WHERE user_id = ?').get(u)).n, 0); + assert.ok((await usageOf(w.db, u)).aiJobs >= 5, 'pas de contournement par suppression du projet (le job annulé, disparu avec le projet, compte par prudence)'); + const p2 = await proj(w, u, 2); + await assert.rejects(enqueue(w.db, { userId: u, projectId: p2, type: 'evolution' }), { code: 'plan_limit' }); + // Le mois suivant, tout repart de zéro + const next = monthBounds().end + 3600; + assert.equal((await usageOf(w.db, u, { at: next })).aiJobs, 0); + // Les jobs sans IA (envoi) ne consomment pas de job IA + const admin = await addUser(w.db, { admin: true }); + for (let i = 0; i < 8; i++) await recordUsage(w.db, admin, 'ai_job', { ref: null }); + await assert.doesNotReject(assertRoom(w.db, await getUser(w.db, admin), 'aiJobs')); +}); + +test('jobs IA : le plafond d\'un compte ne touche pas un autre compte', async () => { + const w = await world(); + const a = await free(w.db), b = await free(w.db); + const pa = await proj(w, a), pb = await proj(w, b); + for (const type of ['analyze', 'prospect', 'template', 'followup_template', 'evolution']) await enqueue(w.db, { userId: a, projectId: pa, type }); + await assert.doesNotReject(enqueue(w.db, { userId: b, projectId: pb, type: 'analyze' })); +}); + +test('mails : 100 par mois, le 101e refusé à la limite exacte ; un lot est tronqué à ce qui reste, sans perte', async () => { + const w = await world(); + const u = await free(w.db); + const user = await getUser(w.db, u); + for (let i = 0; i < 99; i++) await recordUsage(w.db, u, 'mail'); + assert.equal((await quotaFor(w.db, user, 'mails')).remaining, 1); + await assert.doesNotReject(assertRoom(w.db, user, 'mails', 1)); + await assert.rejects(assertRoom(w.db, user, 'mails', 2), (e) => /Il te reste 1 mail ce mois-ci sur 100/.test(e.message)); + await recordUsage(w.db, u, 'mail'); + await assert.rejects(assertRoom(w.db, user, 'mails', 1), (e) => e.code === 'plan_limit' && /100 mails ce mois-ci sur 100/.test(e.message)); + + // Lot réel : 98 déjà envoyés, 5 demandés → 2 partent, 3 prospects restent à contacter, le suivant est refusé + const w2 = await world(); + const v = await free(w2.db); + await setSetting(w2.db, v, 'send_delay_min', '0'); await setSetting(w2.db, v, 'send_delay_max', '0'); + const p = await proj(w2, v); + await saveSecretConfig(w2.app, p, 'smtp_enc', { host: 'smtp.test', port: 587, user: 'u', pass: 'p', fromEmail: 'a@b.fr' }, 'pass'); + await w2.db.prepare("INSERT INTO templates(project_id, kind, subject, body, status, updated_at) VALUES(?, 'initial', 's', 'b {{entreprise}}', 'validated', ?)").run(p, now()); + for (let i = 0; i < 5; i++) await w2.db.prepare("INSERT INTO prospects(project_id, company, email, created_at) VALUES(?, ?, ?, ?)").run(p, `E${i}`, `e${i}@x${i}.fr`, now()); + for (let i = 0; i < 98; i++) await recordUsage(w2.db, v, 'mail'); + const worker = new Worker(w2.db, makeHandlers(w2.app), { log: { error() {} } }); + const { id } = await enqueue(w2.db, { userId: v, projectId: p, type: 'send', params: { count: 5 } }); + await worker.tick(); + const job = await w2.db.prepare('SELECT status, result_json FROM jobs WHERE id = ?').get(id); + assert.equal(job.status, 'done'); + assert.equal(JSON.parse(job.result_json).sent, 2); + assert.equal(w2.sent.length, 2); + assert.equal((await w2.db.prepare("SELECT COUNT(*) n FROM prospects WHERE project_id = ? AND status = 'new'").get(p)).n, 3, 'rien de perdu'); + await assert.rejects(enqueue(w2.db, { userId: v, projectId: p, type: 'send', params: { count: 1 } }), { code: 'plan_limit' }); + await assert.rejects(enqueue(w2.db, { userId: v, projectId: p, type: 'followup', params: { count: 1 } }), { code: 'plan_limit' }); +}); + +test('prospects : 50 au total, l\'import est refusé en entier (rien importé) au-delà, accepté à la limite exacte', async () => { + const w = await world(); + const u = await free(w.db); + const user = await getUser(w.db, u); + const p = await proj(w, u); + const csv = (from, n) => 'email,entreprise\n' + Array.from({ length: n }, (_, i) => `c${from + i}@dom${from + i}.fr,E${from + i}`).join('\n'); + const q = () => quotaFor(w.db, user, 'prospects'); + const imp = async (text) => { + const quota = await q(); + return importProspects(w.db, p, text, { limit: quota.remaining, limitError: new Error(`plafond : il reste ${quota.remaining}`) }); + }; + assert.equal((await imp(csv(0, 49))).imported, 49); + await assert.rejects(imp(csv(100, 2)), /il reste 1/); + assert.equal((await q()).used, 49, 'l\'import refusé n\'a rien écrit (tout ou rien)'); + assert.equal((await imp(csv(200, 1))).imported, 1, '50e prospect : accepté'); + await assert.rejects(imp(csv(300, 1)), /il reste 0/); + assert.equal((await q()).used, 50); +}); + +test('prospection : les prospects trouvés au-delà du plafond ne sont pas enregistrés, le job signale le plafond', async () => { + const w = await world(); + const u = await free(w.db, { link: { v: 1, mode: 'api_key', valid: true, secret_enc: encrypt(w.app.cfg.secretKey, 'sk-ant-' + 'a'.repeat(30)) } }); + const p = await proj(w, u); + await w.db.prepare('UPDATE projects SET profile_json = ?, target_json = ?, target_validated = 1 WHERE id = ?').run(JSON.stringify({ resume: 'r', proposition_valeur: 'v' }), JSON.stringify({ description: 'd', secteurs: ['s'] }), p); + for (let i = 0; i < 49; i++) await w.db.prepare('INSERT INTO prospects(project_id, company, email, created_at) VALUES(?, ?, ?, ?)').run(p, `E${i}`, `e${i}@d${i}.fr`, now()); + const { resolve } = await import('node:path'); + w.app.cfg.claudeBin = resolve('test/fixtures/fake-claude.js'); + const worker = new Worker(w.db, makeHandlers(w.app), { log: { error() {} } }); + const { id } = await enqueue(w.db, { userId: u, projectId: p, type: 'prospect', params: { count: 3 } }); + await worker.tick(); + const job = await w.db.prepare('SELECT status, error, result_json FROM jobs WHERE id = ?').get(id); + assert.equal(job.status, 'done', job.error); + const r = JSON.parse(job.result_json); + assert.equal(r.found, 1); + assert.equal(r.capped, true); + assert.equal((await w.db.prepare('SELECT COUNT(*) n FROM prospects WHERE project_id = ?').get(p)).n, 50); +}); + +test('HTTP : refus explicite avec code plan_limit et lien /tarifs ; le projet est créé même si l\'analyse est refusée', async () => { + const s = await startApp(); + try { + const u = await s.newUser({ admin: false, link: LINK }); + await s.db.prepare("INSERT INTO user_settings(user_id, `key`, value) VALUES(?, 'forgejo_host', 'git.test')").run(u.id); + for (let i = 0; i < 5; i++) await recordUsage(s.db, u.id, 'ai_job'); + const ok = await u.post('/api/projects', { name: 'Un', gitUrl: 'https://git.test/a/un.git' }); + assert.equal(ok.status, 200); + const body = await ok.json(); + assert.ok(body.id); + assert.match(body.notice, /plafond du plan gratuit/, 'le projet existe, seule l\'analyse attend'); + const second = await u.post('/api/projects', { name: 'Deux', gitUrl: 'https://git.test/a/deux.git' }); + assert.equal(second.status, 403); + const e = await second.json(); + assert.equal(e.code, 'plan_limit'); + assert.equal(e.upgradeUrl, '/tarifs'); + assert.match(e.error, /\/tarifs/); + const analyze = await u.post(`/api/projects/${body.id}/analyze`, {}); + assert.equal(analyze.status, 403); + assert.equal((await analyze.json()).code, 'plan_limit'); + } finally { await s.close(); } +}); + +test('Mon compte et tableau de bord : barres d\'usage du mois, plafond atteint signalé ; admin sans barre de plafond', async () => { + const s = await startApp(); + try { + const u = await s.newUser({ admin: false, link: LINK }); + const pid = await proj({ db: s.db }, u.id); + for (let i = 0; i < 100; i++) await recordUsage(s.db, u.id, 'mail'); + for (const page of ['/account', '/']) { + const h = await (await u.get(page, { headers: { accept: 'text/html' } })).text(); + assert.match(h, /Usage du mois/, page); + assert.match(h, /plan gratuit/, page); + assert.match(h, /Mails ce mois-ci<\/span>100 \/ 100/, page); + assert.match(h, /
    /, page); + assert.match(h, //); + assert.match(h, /Plafond atteint : .*mails ce mois-ci/, page); + assert.match(h, /Projets<\/span>1 \/ 1/, page); + assert.doesNotMatch(h, /style="/, 'pas de style en ligne (CSP)'); + } + assert.ok(pid); + const a = await s.newUser({ admin: true }); + const h = await (await a.get('/account', { headers: { accept: 'text/html' } })).text(); + assert.match(h, /plan administrateur/); + assert.doesNotMatch(h, /class="bar usage/); + const view = await usageView(s.db, await getUser(s.db, u.id)); + assert.deepEqual(view.items.map((i) => i.limit), [1, 50, 100, 5]); + } finally { await s.close(); } +}); + +test('Tarifs : plus de « pas encore appliqués », chiffres identiques à la configuration', async () => { + const s = await startApp(); + try { + const h = await (await s.anon.get('/tarifs', { headers: { accept: 'text/html' } })).text(); + assert.doesNotMatch(h, /pas encore appliqu/); + assert.match(h, /appliqués par le serveur/); + for (const n of Object.values(PLAN_LIMITS.free)) assert.ok(h.includes(`${n}`), String(n)); + } finally { await s.close(); } +}); diff --git a/test/site.test.js b/test/site.test.js index 803b902..a2fd766 100644 --- a/test/site.test.js +++ b/test/site.test.js @@ -201,7 +201,8 @@ test('textes : faits réels du statut, tarifs sans prix inventé, aucun terme in assert.match(tarifs, /Bientôt/); for (const n of ['>1<', '>50<', '>100<', '>5<']) assert.ok(tarifs.includes(`${n.slice(1, -1)}`), n); assert.doesNotMatch(tarifs.replace(/0 €/g, ''), /\d\s?€|€\s?\d/, 'aucun prix inventé'); - assert.match(tarifs, /pas encore automatiquement/); + assert.match(tarifs, /appliqués par le serveur/); + assert.doesNotMatch(tarifs, /pas encore appliqu/); assert.match(tarifs, /suspendu ou fermé/); const cgu = await text('/cgu');