diff --git a/admin/src/pages/ModulesTab.tsx b/admin/src/pages/ModulesTab.tsx index 4abbbf9..93b73ac 100644 --- a/admin/src/pages/ModulesTab.tsx +++ b/admin/src/pages/ModulesTab.tsx @@ -214,7 +214,7 @@ export function ModulesTab({ storeId, storeName }: { storeId: string; storeName: <>

{active} module(s) actif(s) sur {list.length}. Chaque module est inclus ou non dans la formule ; vous pouvez l'ajouter ou le retirer sur mesure, - et tous ses textes et réglages sont personnalisables. Le gérant peut aussi les régler depuis l'app Pro. + et tous ses textes et réglages sont personnalisables. Le dirigeant peut aussi les régler depuis l'app Pro.

{list.map((m) => ( diff --git a/admin/src/pages/StaffTab.tsx b/admin/src/pages/StaffTab.tsx index d59d055..8c7ca2d 100644 --- a/admin/src/pages/StaffTab.tsx +++ b/admin/src/pages/StaffTab.tsx @@ -1,7 +1,7 @@ import { FormEvent, useCallback, useEffect, useRef, useState } from 'react'; import { api, StaffRole, StaffUser } from '../api'; -const ROLE_LABEL: Record = { MANAGER: 'Gérant', EMPLOYEE: 'Employé' }; +const ROLE_LABEL: Record = { MANAGER: 'Dirigeant', EMPLOYEE: 'Employé' }; export function StaffTab({ storeId }: { storeId: string }) { const base = `/api/admin/stores/${storeId}/staff`; @@ -78,7 +78,7 @@ export function StaffTab({ storeId }: { storeId: string }) { {staff.length === 0 && (

- Aucun employé. Créez au moins un gérant pour que le magasin puisse utiliser l'app Pro. + Aucun employé. Créez au moins un dirigeant pour que le magasin puisse utiliser l'app Pro.

)} diff --git a/backend/prisma/manual-migrations/2026-10-09-inscription-cadeaux.sql b/backend/prisma/manual-migrations/2026-10-09-inscription-cadeaux.sql new file mode 100644 index 0000000..034e42c --- /dev/null +++ b/backend/prisma/manual-migrations/2026-10-09-inscription-cadeaux.sql @@ -0,0 +1,30 @@ +-- Inscription en ligne, titre des campagnes, cadeaux en nature (anniversaire, parrainage). +-- À exécuter APRÈS 2026-10-08-modules.sql. +ALTER TABLE `Campaign` ADD COLUMN `title` VARCHAR(40) NULL; + +CREATE TABLE `Gift` ( + `id` VARCHAR(191) NOT NULL, + `cardId` VARCHAR(191) NOT NULL, + `label` VARCHAR(80) NOT NULL, + `source` ENUM('BIRTHDAY', 'REFERRAL', 'REFERRAL_FRIEND') NOT NULL, + `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), + `usedAt` DATETIME(3) NULL, + `usedByName` VARCHAR(191) NULL, + INDEX `Gift_cardId_usedAt_idx`(`cardId`, `usedAt`), + PRIMARY KEY (`id`), + CONSTRAINT `Gift_cardId_fkey` FOREIGN KEY (`cardId`) REFERENCES `LoyaltyCard`(`id`) ON DELETE CASCADE ON UPDATE CASCADE +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +CREATE TABLE `PendingSignup` ( + `id` VARCHAR(191) NOT NULL, + `email` VARCHAR(191) NOT NULL, + `data` JSON NOT NULL, + `passwordHash` VARCHAR(191) NOT NULL, + `plan` ENUM('ESSENTIEL', 'PRO', 'RESEAU') NOT NULL, + `interval` ENUM('MONTH', 'YEAR') NOT NULL, + `storeId` VARCHAR(191) NULL, + `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), + UNIQUE INDEX `PendingSignup_storeId_key`(`storeId`), + INDEX `PendingSignup_email_idx`(`email`), + PRIMARY KEY (`id`) +) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index 570be21..51a055c 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -169,6 +169,7 @@ model LoyaltyCard { updatedAt DateTime @updatedAt transactions Transaction[] devices AppleRegistration[] + gifts Gift[] @@unique([storeId, customerId]) } @@ -294,6 +295,8 @@ model Campaign { id String @id @default(cuid()) storeId String store Store @relation(fields: [storeId], references: [id], onDelete: Cascade) + /// Titre de la notification (Google Wallet) ; vide : réglage du module. + title String? @db.VarChar(40) message String @db.VarChar(160) /// « MonEspacePro » (admin) ou nom du gérant qui l'a envoyée. sentByName String @@ -304,3 +307,41 @@ model Campaign { @@index([storeId, createdAt]) } + +/// Cadeau en nature (« Un café offert ») gagné par un client : présenté en caisse, puis marqué remis. +enum GiftSource { + BIRTHDAY + REFERRAL /// parrain + REFERRAL_FRIEND /// filleul +} + +model Gift { + id String @id @default(cuid()) + cardId String + card LoyaltyCard @relation(fields: [cardId], references: [id], onDelete: Cascade) + label String @db.VarChar(80) + source GiftSource + createdAt DateTime @default(now()) + usedAt DateTime? + /// Employé qui a remis le cadeau. + usedByName String? + + @@index([cardId, usedAt]) +} + +/// Inscription en ligne en attente du paiement Stripe : le magasin et le compte +/// Dirigeant ne sont créés qu'au paiement réussi (webhook). +model PendingSignup { + id String @id @default(cuid()) + email String + /// Champs du magasin (nom, adresse, SIRET, contact…). + data Json + passwordHash String + plan Plan + interval BillingInterval + /// Magasin créé (inscription terminée). + storeId String? @unique + createdAt DateTime @default(now()) + + @@index([email]) +} diff --git a/backend/src/admin.module.ts b/backend/src/admin.module.ts index 150fc46..24546c3 100644 --- a/backend/src/admin.module.ts +++ b/backend/src/admin.module.ts @@ -1,14 +1,18 @@ import { Module } from '@nestjs/common'; +import { BillingModule } from './billing/billing.controller'; import { StoresController } from './stores/stores.controller'; import { StoresService } from './stores/stores.service'; import { CardDesignController } from './card-design/card-design.controller'; import { CardDesignService } from './card-design/card-design.service'; import { StaffController } from './staff/staff.controller'; import { StaffService } from './staff/staff.service'; +import { StaffPasswordController, StaffSpaceController } from './staff/staff-space.controller'; /** Back-office : magasins, design des cartes, comptes du personnel. */ @Module({ - controllers: [StoresController, CardDesignController, StaffController], + imports: [BillingModule], + controllers: [StoresController, CardDesignController, StaffController, StaffSpaceController, StaffPasswordController], providers: [StoresService, CardDesignService, StaffService], + exports: [CardDesignService, StaffService], }) export class AdminModule {} diff --git a/backend/src/billing/billing.controller.ts b/backend/src/billing/billing.controller.ts index 5e0fa93..061d416 100644 --- a/backend/src/billing/billing.controller.ts +++ b/backend/src/billing/billing.controller.ts @@ -1,4 +1,5 @@ -import { Body, Controller, Get, Headers, HttpCode, Logger, Module, Param, Post, Req, Res, UseGuards } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import { Body, Controller, Get, Headers, HttpCode, Logger, Module, NotFoundException, Param, Post, Req, Res, UseGuards } from '@nestjs/common'; import type { RawBodyRequest } from '@nestjs/common'; import { SkipThrottle } from '@nestjs/throttler'; import { BillingInterval, Plan } from '@prisma/client'; @@ -6,6 +7,8 @@ import { IsBoolean, IsEnum, IsOptional } from 'class-validator'; import type { Request, Response } from 'express'; import { AdminGuard, JwtAuthGuard } from '../common/guards'; import { BillingService } from './billing.service'; +import { SignupModule } from '../signup/signup.module'; +import { SignupController } from '../signup/signup.controller'; class CheckoutLinkDto { @IsEnum(Plan) @@ -14,10 +17,6 @@ class CheckoutLinkDto { @IsEnum(BillingInterval) interval!: BillingInterval; - /** Proposer l'essai gratuit (une seule fois par magasin). */ - @IsOptional() @IsBoolean() - trial?: boolean; - /** Envoyer le lien par e-mail au contact du magasin. */ @IsOptional() @IsBoolean() sendEmail?: boolean; @@ -44,7 +43,6 @@ export class BillingAdminController { return this.billing.checkoutLink(storeId, { plan: dto.plan, interval: dto.interval, - trial: dto.trial ?? false, sendEmail: dto.sendEmail ?? true, }); } @@ -66,6 +64,23 @@ export class BillingAdminController { } } +/** Lien d'abonnement permanent envoyé au commerçant : redirige vers une session Stripe neuve. */ +@Controller('public/subscribe') +export class SubscribeController { + constructor( + private billing: BillingService, + private config: ConfigService, + ) {} + + @Get(':storeId/:sig') + async go(@Param('storeId') storeId: string, @Param('sig') sig: string, @Res() res: Response) { + if (!this.billing.checkSubscribeSignature(storeId, sig)) throw new NotFoundException('Lien invalide'); + const session = await this.billing.checkoutSession(storeId); + // Déjà abonné : page de remerciement plutôt qu'un second abonnement. + res.redirect(303, session?.url ?? `${this.config.get('webUrl')}/abonnement/merci/`); + } +} + /** Notifications Stripe : signature vérifiée sur le corps brut. */ @Controller('stripe') @SkipThrottle() @@ -90,7 +105,9 @@ export class StripeWebhookController { } @Module({ - controllers: [BillingAdminController, StripeWebhookController], + imports: [SignupModule], + controllers: [BillingAdminController, SubscribeController, SignupController, StripeWebhookController], providers: [BillingService], + exports: [BillingService], }) export class BillingModule {} diff --git a/backend/src/billing/billing.service.ts b/backend/src/billing/billing.service.ts index 33898ae..b42cce3 100644 --- a/backend/src/billing/billing.service.ts +++ b/backend/src/billing/billing.service.ts @@ -3,12 +3,15 @@ import { ConfigService } from '@nestjs/config'; import { BillingInterval, Plan, Prisma, SubscriptionStatus } from '@prisma/client'; import { mkdir, readFile, writeFile } from 'fs/promises'; import { join } from 'path'; +import { createHmac, timingSafeEqual } from 'crypto'; import Stripe from 'stripe'; import { PrismaService } from '../prisma/prisma.service'; import { MailService } from '../mail/mail.service'; import { emailLayout, esc } from '../mail/email-layout'; import { renderInvoicePdf } from './invoice-pdf'; -import { PLANS, TRIAL_DAYS, planFromLookupKey, publicCatalog } from './plans'; +import { PLANS, planFromLookupKey, publicCatalog } from './plans'; +import { activateIfReady } from '../stores/activation'; +import { SignupService } from '../signup/signup.service'; /** Factures PDF : hors des dossiers servis publiquement. */ export const INVOICES_DIR = join(process.cwd(), 'storage', 'invoices'); @@ -39,6 +42,7 @@ export class BillingService { private prisma: PrismaService, private config: ConfigService, private mail: MailService, + private signup: SignupService, ) {} get stripe(): Stripe { @@ -59,13 +63,12 @@ export class BillingService { return { testMode: (this.config.get('stripe.secretKey') ?? '').startsWith('sk_test_'), catalog: publicCatalog(), - trialDays: TRIAL_DAYS, + subscribeUrl: this.subscribeUrl(store.id), subscription: sub && { status: sub.status, plan: sub.plan, interval: sub.interval, legacyPrice: sub.legacyPrice, - trialEndsAt: sub.trialEndsAt, cancelAtPeriodEnd: sub.cancelAtPeriodEnd, currentPeriodEnd: sub.currentPeriodEnd, hasCustomer: !!sub.stripeCustomerId, @@ -106,7 +109,7 @@ export class BillingService { return { store, customerId: customer.id }; } - private async priceFor(plan: Plan, interval: BillingInterval) { + async priceFor(plan: Plan, interval: BillingInterval) { const key = PLANS[plan].lookupKey[interval]; const price = (await this.stripe.prices.list({ lookup_keys: [key], active: true, limit: 1 })).data[0]; if (!price) throw new ServiceUnavailableException(`Prix Stripe « ${key} » introuvable : lancer scripts/stripe-setup.ts`); @@ -114,21 +117,41 @@ export class BillingService { } /** - * Lien Checkout pour souscrire une formule (mensuelle ou annuelle), avec - * essai gratuit éventuel et codes promo ; envoyé par e-mail si demandé. + * Lien d'abonnement permanent du magasin : chaque clic crée une session + * Stripe Checkout neuve pour la formule choisie (une session Stripe expire + * au bout de 24 h, ce lien jamais). Signé : impossible à deviner. */ - async checkoutLink(storeId: string, opts: { plan: Plan; interval: BillingInterval; trial: boolean; sendEmail: boolean }) { - const { store, customerId } = await this.ensureCustomer(storeId); - if (store.subscription?.stripeSubscriptionId && store.subscription.status !== 'CANCELED') { + subscribeUrl(storeId: string) { + const sig = createHmac('sha256', this.config.get('jwt.accessSecret')!).update(`subscribe:${storeId}`).digest('base64url').slice(0, 24); + return `${this.config.get('publicUrl')}/api/public/subscribe/${storeId}/${sig}`; + } + + checkSubscribeSignature(storeId: string, sig: string) { + const expected = this.subscribeUrl(storeId).split('/').pop()!; + return sig.length === expected.length && timingSafeEqual(Buffer.from(sig), Buffer.from(expected)); + } + + /** Formule choisie (création du magasin, ou admin) : elle sera proposée au paiement. */ + async choosePlan(storeId: string, plan: Plan, interval: BillingInterval) { + const sub = await this.prisma.subscription.findUnique({ where: { storeId } }); + if (sub?.stripeSubscriptionId && sub.status !== 'CANCELED') { throw new BadRequestException('Ce magasin a déjà un abonnement : changez de formule depuis le portail client'); } - // Un seul essai par magasin, même après résiliation. - const trialAllowed = opts.trial && !store.subscription?.trialEndsAt; - const price = await this.priceFor(opts.plan, opts.interval); - const def = PLANS[opts.plan]; + await this.prisma.subscription.upsert({ + where: { storeId }, + create: { storeId, plan, interval }, + update: { plan, interval, ...(sub?.status === 'CANCELED' && { status: 'INCOMPLETE', stripeSubscriptionId: null }) }, + }); + } + /** Session Stripe Checkout pour la formule enregistrée du magasin (lien permanent). */ + async checkoutSession(storeId: string) { + const { store, customerId } = await this.ensureCustomer(storeId); + const sub = store.subscription; + if (sub?.stripeSubscriptionId && sub.status !== 'CANCELED') return null; // déjà abonné + const price = await this.priceFor(sub?.plan ?? 'ESSENTIEL', sub?.interval ?? 'MONTH'); const webUrl: string = this.config.get('webUrl')!; - const session = await this.stripe.checkout.sessions.create({ + return this.stripe.checkout.sessions.create({ mode: 'subscription', customer: customerId, line_items: [{ price: price.id, quantity: 1 }], @@ -136,19 +159,30 @@ export class BillingService { allow_promotion_codes: true, locale: 'fr', client_reference_id: store.id, - subscription_data: { - metadata: { storeId: store.id }, - ...(trialAllowed && { trial_period_days: TRIAL_DAYS }), - }, + subscription_data: { metadata: { storeId: store.id } }, metadata: { storeId: store.id }, success_url: `${webUrl}/abonnement/merci/`, cancel_url: `${webUrl}/tarif/`, - expires_at: Math.floor(Date.now() / 1000) + 24 * 3600, // 24 h, maximum autorisé par Stripe }); + } + /** + * Enregistre la formule et envoie (ou renvoie) au commerçant le lien + * d'abonnement permanent. + */ + async checkoutLink(storeId: string, opts: { plan: Plan; interval: BillingInterval; sendEmail: boolean; credentials?: { email: string; password: string } }) { + await this.choosePlan(storeId, opts.plan, opts.interval); + const store = await this.prisma.store.findUniqueOrThrow({ where: { id: storeId } }); + const def = PLANS[opts.plan]; + const url = this.subscribeUrl(storeId); + const webUrl: string = this.config.get('webUrl')!; const priceText = `${euros(def.priceCents[opts.interval])} ${opts.interval === 'YEAR' ? 'par an (2 mois offerts)' : 'par mois'}`; if (opts.sendEmail) { - const text = `Bonjour ${store.contactName},\n\nVoici le lien pour activer la formule ${def.name} de MonEspacePro pour ${store.name} (${priceText}${trialAllowed ? `, ${TRIAL_DAYS} jours d'essai gratuit` : ''}, sans engagement) :\n${session.url}\n\nCe lien est valable 24 heures.\n\nMonEspacePro`; + const espace = `${this.config.get('adminUrl')}/espace`; + const c = opts.credentials; + const text = `Bonjour ${store.contactName},\n\nVoici le lien pour activer la formule ${def.name} de MonEspacePro pour ${store.name} (${priceText}, sans engagement) :\n${url}\n${ + c ? `\nVotre compte Dirigeant (app MonEspacePro Pro et espace web ${espace}) :\nE-mail : ${c.email}\nMot de passe provisoire : ${c.password}\n` : '' + }\nMonEspacePro`; const html = emailLayout({ webUrl, preheader: `Activez la formule ${def.name} de MonEspacePro pour ${store.name}.`, @@ -156,26 +190,27 @@ export class BillingService { title: `Activez MonEspacePro pour ${store.name}`, paragraphs: [ `Bonjour ${esc(store.contactName)},`, - `Votre carte de fidélité est prête. Il ne reste qu'à activer la formule ${esc(def.name)} de ${esc(store.name)} pour l'ouvrir à vos clients.`, + `Il ne reste qu'à activer la formule ${esc(def.name)} de ${esc(store.name)}. Dès le paiement validé, votre programme de fidélité s'ouvre automatiquement à vos clients.`, ], - cta: { label: trialAllowed ? `Commencer l'essai gratuit de ${TRIAL_DAYS} jours` : 'Activer mon abonnement', url: session.url! }, + cta: { label: 'Activer mon abonnement', url }, details: [ ['Formule', `${esc(def.name)} — ${esc(def.tagline)}`], ['Prix', `${priceText} — TVA non applicable, art. 293 B du CGI`], - ...(trialAllowed ? ([['Essai', `${TRIAL_DAYS} jours gratuits, aucun prélèvement avant la fin de l'essai`]] as [string, string][]) : []), ['Engagement', 'Aucun, résiliable à tout moment'], ['Paiement', 'Carte bancaire ou prélèvement SEPA, factures automatiques'], + ...(c + ? ([ + ['Votre identifiant', esc(c.email)], + ['Mot de passe provisoire', `${esc(c.password)}`], + ['Espace web', `${esc(espace)} (conception de la carte)`], + ] as [string, string][]) + : []), ], - note: 'Ce lien est valable 24 heures. Passé ce délai, demandez-nous simplement un nouveau lien.', + note: 'Vos identifiants ouvrent aussi l’app MonEspacePro Pro, pour scanner les cartes de vos clients.', }); await this.mail.send(store.contactEmail, `Activez la formule ${def.name} de MonEspacePro`, text, html); } - return { - url: session.url, - expiresAt: new Date(session.expires_at * 1000), - emailedTo: opts.sendEmail ? store.contactEmail : null, - trial: trialAllowed, - }; + return { url, emailedTo: opts.sendEmail ? store.contactEmail : null }; } /** @@ -227,7 +262,10 @@ export class BillingService { switch (event.type) { case 'checkout.session.completed': { const s = event.data.object; - if (s.mode === 'subscription' && s.subscription) await this.syncSubscription(String(s.subscription)); + if (s.mode !== 'subscription' || !s.subscription) break; + // Inscription en ligne : le magasin et le compte Dirigeant naissent ici. + const storeId = s.metadata?.signupId ? await this.signup.complete(s, this.stripe) : undefined; + await this.syncSubscription(String(s.subscription), storeId); break; } case 'customer.subscription.created': @@ -238,9 +276,6 @@ export class BillingService { case 'invoice.paid': await this.onInvoicePaid(event.data.object); break; - case 'customer.subscription.trial_will_end': - await this.onTrialWillEnd(event.data.object); - break; case 'invoice.payment_failed': await this.onPaymentFailed(event.data.object); break; @@ -250,9 +285,9 @@ export class BillingService { } /** Recopie l'état de l'abonnement Stripe et applique suspension / réactivation. */ - private async syncSubscription(subscriptionId: string) { + private async syncSubscription(subscriptionId: string, knownStoreId?: string) { const sub = await this.stripe.subscriptions.retrieve(subscriptionId); - const storeId = sub.metadata.storeId; + const storeId = knownStoreId ?? sub.metadata.storeId; if (!storeId) return; const status = STATUS[sub.status] ?? 'INCOMPLETE'; const periodEnd = sub.current_period_end; @@ -273,42 +308,13 @@ export class BillingService { currentPeriodEnd: periodEnd ? new Date(periodEnd * 1000) : null, } satisfies Prisma.SubscriptionUncheckedUpdateInput; await this.prisma.subscription.upsert({ where: { storeId }, create: { storeId, ...data }, update: data }); - if (status === 'ACTIVE') await this.reactivate(storeId); + if (status === 'ACTIVE') { + await this.reactivate(storeId); + await activateIfReady(this.prisma, storeId); + } if (status === 'PAST_DUE' || status === 'CANCELED') await this.suspend(storeId, `abonnement ${sub.status}`); } - /** Stripe prévient 3 jours avant la fin de l'essai : on rappelle au commerçant ce qui va se passer. */ - private async onTrialWillEnd(sub: Stripe.Subscription) { - const storeId = sub.metadata.storeId; - if (!storeId || !sub.trial_end) return; - const store = await this.prisma.store.findUnique({ where: { id: storeId } }); - if (!store) return; - const found = planFromLookupKey(sub.items.data[0]?.price?.lookup_key); - const def = PLANS[found?.plan ?? 'ESSENTIEL']; - const interval = found?.interval ?? 'MONTH'; - const end = new Date(sub.trial_end * 1000).toLocaleDateString('fr-FR', { day: 'numeric', month: 'long', timeZone: 'Europe/Paris' }); - const webUrl: string = this.config.get('webUrl')!; - const portal = await this.portalLink(storeId, false); - const text = `Bonjour ${store.contactName},\n\nVotre essai gratuit de MonEspacePro se termine le ${end}. L'abonnement ${def.name} démarrera alors automatiquement (${euros(def.priceCents[interval])} ${interval === 'YEAR' ? 'par an' : 'par mois'}). Rien à faire si vous souhaitez continuer.\n\nChanger de formule ou résilier : ${portal.url}\n\nMonEspacePro`; - const html = emailLayout({ - webUrl, - preheader: `Votre essai se termine le ${end}.`, - eyebrow: 'Essai gratuit', - title: `Votre essai se termine le ${end}`, - paragraphs: [ - `Bonjour ${esc(store.contactName)},`, - `L'abonnement ${esc(def.name)} de ${esc(store.name)} démarrera automatiquement à la fin de l'essai. Rien à faire si vous souhaitez continuer.`, - ], - details: [ - ['Formule', esc(def.name)], - ['Prix', `${euros(def.priceCents[interval])} ${interval === 'YEAR' ? 'par an' : 'par mois'} — TVA non applicable, art. 293 B du CGI`], - ['Premier prélèvement', end], - ], - cta: { label: 'Changer de formule ou résilier', url: portal.url }, - }); - await this.mail.send(store.contactEmail, `Votre essai MonEspacePro se termine le ${end}`, text, html); - } - private async onPaymentFailed(invoice: Stripe.Invoice) { const storeId = await this.storeIdForCustomer(String(invoice.customer)); if (storeId) await this.suspend(storeId, `paiement de ${euros(invoice.amount_due)} refusé`); diff --git a/backend/src/billing/plans.ts b/backend/src/billing/plans.ts index 21c08db..04ae845 100644 --- a/backend/src/billing/plans.ts +++ b/backend/src/billing/plans.ts @@ -62,7 +62,6 @@ export const PLANS: Record = { /** Ancien prix unique à 10 €/mois : traité comme Essentiel (tarif fondateur). */ export const LEGACY_LOOKUP_KEYS = ['mep_magasin_mensuel']; -export const TRIAL_DAYS = 30; export function planFromLookupKey(key: string | null | undefined): { plan: Plan; interval: BillingInterval; legacy: boolean } | null { if (!key) return null; diff --git a/backend/src/birthdays/birthdays.service.ts b/backend/src/birthdays/birthdays.service.ts index bc27216..69ea72b 100644 --- a/backend/src/birthdays/birthdays.service.ts +++ b/backend/src/birthdays/birthdays.service.ts @@ -85,7 +85,7 @@ export class BirthdaysService implements OnModuleInit, OnApplicationBootstrap, O if (!moduleActive(store, 'birthday')) continue; const config = moduleConfig(store, 'birthday'); if (today.hour < Number(config.hourFrom) || today.hour >= Number(config.hourTo)) continue; - const sent = await this.runStore(store.id, Number(config.points), today, now); + const sent = await this.runStore(store.id, Number(config.points), String(config.gift).trim(), today, now); if (sent) this.logger.log(`Anniversaire : ${sent} client(s) de ${store.name}`); } } catch (e) { @@ -95,7 +95,7 @@ export class BirthdaysService implements OnModuleInit, OnApplicationBootstrap, O } } - private async runStore(storeId: string, points: number, today: ReturnType, now: Date) { + private async runStore(storeId: string, points: number, gift: string, today: ReturnType, now: Date) { const notBefore = new Date(now.getTime() - MIN_GAP_MS); const cards = await this.prisma.loyaltyCard.findMany({ where: { @@ -113,6 +113,8 @@ export class BirthdaysService implements OnModuleInit, OnApplicationBootstrap, O data: { birthdayGiftAt: now, passUpdatedAt: now, ...(points > 0 && { balance: { increment: points } }) }, }); if (!count) continue; + // Cadeau en nature : à remettre en caisse depuis l'app Pro. + if (gift) await this.prisma.gift.create({ data: { cardId: id, label: gift, source: 'BIRTHDAY' } }); const card = await this.prisma.loyaltyCard.findUniqueOrThrow({ where: { id }, include: CARD_WITH_CONTEXT }); try { await this.cardUpdates.remind(card.id, birthdayText(card), notificationTitle(card.store, 'birthday')); diff --git a/backend/src/campaigns/campaigns.controller.ts b/backend/src/campaigns/campaigns.controller.ts index c5369f9..ef09cc4 100644 --- a/backend/src/campaigns/campaigns.controller.ts +++ b/backend/src/campaigns/campaigns.controller.ts @@ -1,12 +1,16 @@ import { Body, Controller, Get, Module, Param, Post, UseGuards } from '@nestjs/common'; import { Throttle } from '@nestjs/throttler'; -import { IsString, MaxLength, MinLength } from 'class-validator'; +import { IsOptional, IsString, MaxLength, MinLength } from 'class-validator'; import { JwtPayload } from '../common/auth.types'; import { AdminGuard, CurrentUser, JwtAuthGuard, StaffGuard, StaffRoles } from '../common/guards'; import { PrismaService } from '../prisma/prisma.service'; import { CampaignsService } from './campaigns.service'; class SendCampaignDto { + /** Titre de la notification ; absent ou vide : titre par défaut du module. */ + @IsOptional() @IsString() @MaxLength(40) + title?: string; + @IsString() @MinLength(5) @MaxLength(160) message!: string; } @@ -23,11 +27,11 @@ export class AdminCampaignsController { @Post() send(@Param('id') id: string, @Body() dto: SendCampaignDto) { - return this.campaigns.send(id, dto.message, 'MonEspacePro'); + return this.campaigns.send(id, dto.message, 'MonEspacePro', dto.title); } } -/** App Pro : réservé aux gérants. */ +/** App Pro : réservé aux dirigeants. */ @Controller('staff/campaigns') @UseGuards(JwtAuthGuard, StaffGuard) @StaffRoles('MANAGER') @@ -45,7 +49,7 @@ export class StaffCampaignsController { async send(@CurrentUser() user: JwtPayload, @Body() dto: SendCampaignDto) { if (user.kind !== 'staff') throw new Error('StaffGuard manquant'); const staff = await this.prisma.staffUser.findUniqueOrThrow({ where: { id: user.sub }, select: { displayName: true } }); - return this.campaigns.send(user.storeId, dto.message, staff.displayName); + return this.campaigns.send(user.storeId, dto.message, staff.displayName, dto.title); } } diff --git a/backend/src/campaigns/campaigns.service.ts b/backend/src/campaigns/campaigns.service.ts index 758df26..f160fd8 100644 --- a/backend/src/campaigns/campaigns.service.ts +++ b/backend/src/campaigns/campaigns.service.ts @@ -29,10 +29,10 @@ export class CampaignsService { last && last.createdAt.getTime() + interval > Date.now() ? new Date(last.createdAt.getTime() + interval) : null; - return { allowed, maxLength: Number(config.maxLength), minIntervalHours: Number(config.minIntervalHours), audience: { cards, appleDevices }, nextAllowedAt, items }; + return { allowed, defaultTitle: fill(String(config.title), { magasin: store.name }), maxLength: Number(config.maxLength), minIntervalHours: Number(config.minIntervalHours), audience: { cards, appleDevices }, nextAllowedAt, items }; } - async send(storeId: string, rawMessage: string, sentByName: string) { + async send(storeId: string, rawMessage: string, sentByName: string, rawTitle?: string) { const config = await this.modules.require(storeId, 'campaigns'); const interval = Number(config.minIntervalHours) * 3600_000; const store = await this.prisma.store.findUnique({ where: { id: storeId } }); @@ -44,6 +44,8 @@ export class CampaignsService { if (message.length < 5) throw new BadRequestException('Le message est trop court.'); if (message.length > Number(config.maxLength)) throw new BadRequestException(`Le message dépasse ${config.maxLength} caractères.`); + const title = (rawTitle ?? '').replace(/s+/g, ' ').trim().slice(0, 40) || null; + const last = await this.prisma.campaign.findFirst({ where: { storeId }, orderBy: { createdAt: 'desc' } }); if (last && last.createdAt.getTime() + interval > Date.now()) { const at = new Date(last.createdAt.getTime() + interval); @@ -62,9 +64,9 @@ export class CampaignsService { this.prisma.appleDevice.count({ where: { registrations: { some: { card: { storeId } } } } }), ]); const campaign = await this.prisma.campaign.create({ - data: { storeId, message, sentByName, cards, appleDevices }, + data: { storeId, title, message, sentByName, cards, appleDevices }, }); - this.cardUpdates.broadcast(storeId, campaign, fill(String(config.title), { magasin: store.name }) || store.name); + this.cardUpdates.broadcast(storeId, campaign, fill(title ?? String(config.title), { magasin: store.name }) || store.name); return campaign; } } diff --git a/backend/src/card-design/card-design.service.ts b/backend/src/card-design/card-design.service.ts index 9020d3e..15957b7 100644 --- a/backend/src/card-design/card-design.service.ts +++ b/backend/src/card-design/card-design.service.ts @@ -3,6 +3,7 @@ import { Prisma } from '@prisma/client'; import { mkdir, unlink, writeFile } from 'fs/promises'; import { join } from 'path'; import { randomBytes } from 'crypto'; +import { activateIfReady } from '../stores/activation'; import { PrismaService } from '../prisma/prisma.service'; import { SaveCardDesignDto } from './dto/card-design.dto'; import { CardUpdatesService } from '../wallet/card-updates.service'; @@ -68,6 +69,8 @@ export class CardDesignService { }); // Les cartes déjà dans les Wallets reprennent le nouveau design. this.cardUpdates.notifyStore(storeId); + // Abonnement déjà payé (inscription en ligne) : le programme s'ouvre tout seul. + await activateIfReady(this.prisma, storeId); return this.get(storeId); } diff --git a/backend/src/config/configuration.ts b/backend/src/config/configuration.ts index 34a6183..49c8bc0 100644 --- a/backend/src/config/configuration.ts +++ b/backend/src/config/configuration.ts @@ -5,6 +5,8 @@ export default () => ({ publicUrl: (process.env.PUBLIC_URL ?? 'http://localhost:3100').replace(/\/$/, ''), /** Adresse des pages vues par les clients (QR d'inscription, lien de la carte). Par défaut : PUBLIC_URL. */ webUrl: (process.env.WEB_URL || process.env.PUBLIC_URL || 'http://localhost:3100').replace(/\/$/, ''), + /** Admin MonEspacePro et espace web des commerçants (/espace, /inscription). */ + adminUrl: (process.env.ADMIN_URL || 'https://admin.monespacepro.eu').replace(/\/$/, ''), cors: { origins: process.env.CORS_ORIGINS ?? '' }, jwt: { accessSecret: process.env.JWT_ACCESS_SECRET ?? 'dev-access-secret', diff --git a/backend/src/counter/counter.controller.ts b/backend/src/counter/counter.controller.ts index 2c8911c..91a918e 100644 --- a/backend/src/counter/counter.controller.ts +++ b/backend/src/counter/counter.controller.ts @@ -63,6 +63,12 @@ export class CounterController { return this.counter.redeem(ctx(user), serial, dto.rewardId); } + @Post('cards/:serial/gifts/:giftId/use') + @HttpCode(200) + useGift(@CurrentUser() user: JwtPayload, @Param('serial') serial: string, @Param('giftId') giftId: string) { + return this.counter.useGift(ctx(user), serial, giftId); + } + @Get('transactions') history(@CurrentUser() user: JwtPayload, @Query() q: HistoryQuery) { return this.counter.history(ctx(user), q.period ?? 'today', q.cursor); diff --git a/backend/src/counter/counter.service.ts b/backend/src/counter/counter.service.ts index fbe3c9c..80933fe 100644 --- a/backend/src/counter/counter.service.ts +++ b/backend/src/counter/counter.service.ts @@ -74,7 +74,24 @@ export class CounterService { async lookup(ctx: StaffContext, serial: string) { const card = await this.cardOfStore(ctx, serial); - return this.presentCard(card); + const gifts = await this.prisma.gift.findMany({ + where: { cardId: card.id, usedAt: null }, + orderBy: { createdAt: 'asc' }, + select: { id: true, label: true, source: true, createdAt: true }, + }); + return { ...this.presentCard(card), gifts }; + } + + /** Cadeau en nature remis en caisse (anniversaire, parrainage) : marqué remis, une seule fois. */ + async useGift(ctx: StaffContext, serial: string, giftId: string) { + const card = await this.cardOfStore(ctx, serial); + const staff = await this.prisma.staffUser.findUniqueOrThrow({ where: { id: ctx.staffId }, select: { displayName: true } }); + const { count } = await this.prisma.gift.updateMany({ + where: { id: giftId, cardId: card.id, usedAt: null }, + data: { usedAt: new Date(), usedByName: staff.displayName }, + }); + if (!count) throw new BadRequestException('Cadeau introuvable ou déjà remis'); + return this.lookup(ctx, serial); } async credit(ctx: StaffContext, serial: string, amountCents: number | undefined) { @@ -155,7 +172,7 @@ export class CounterService { return { reward: { id: reward.id, label: reward.label, cost: reward.cost }, balance, firstName: card.customer.firstName }; } - /** Le gérant voit tout le magasin ; l'employé, seulement ses opérations. */ + /** Le dirigeant voit tout le magasin ; l'employé, seulement ses opérations. */ async history(ctx: StaffContext, period: 'today' | 'week', cursor?: string) { const where = this.scope(ctx, period); const items = await this.prisma.transaction.findMany({ diff --git a/backend/src/enrollment/pages.ts b/backend/src/enrollment/pages.ts index 13adce5..38f0d41 100644 --- a/backend/src/enrollment/pages.ts +++ b/backend/src/enrollment/pages.ts @@ -1,5 +1,5 @@ import type { CardDesign, Plan, Reward, Store, SubscriptionStatus } from '@prisma/client'; -import { fill, moduleActive, moduleConfig, quantity } from '../modules/catalog'; +import { fill, moduleActive, moduleConfig, quantity, rewardVars } from '../modules/catalog'; import { nextRewardText, reviewOffered, type CardWithContext } from '../wallet/wallet.types'; /** Pages publiques (clients finaux), rendues côté serveur aux couleurs du magasin. */ @@ -32,11 +32,16 @@ function birthdaySelects() { 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}}`; const stamp = (s: StoreWithDesign) => s.cardDesign?.pointsMode === 'STAMP'; +/** Récompense du filleul (points et/ou cadeau en nature). */ +const friendReward = (s: StoreWithDesign) => { + const c = moduleConfig(s, 'referral'); + return rewardVars(Number(c.friendPoints), c.friendGift, stamp(s)); +}; /** Textes du module Anniversaire, avec {cadeau} (« 3 tampons offerts sur votre carte. » ou vide). */ function birthdayTexts(store: StoreWithDesign) { const c = moduleConfig(store, 'birthday'); - const n = Number(c.points); - const cadeau = n > 0 ? fill(String(c.giftText), { quantite: quantity(n, stamp(store)) }) : ''; + const vars = rewardVars(Number(c.points), c.gift, stamp(store)); + const cadeau = vars.recompense ? fill(String(c.giftText), vars) : ''; return { enrollHint: fill(String(c.enrollHint), { cadeau }), askTitle: String(c.askTitle), askText: fill(String(c.askText), { cadeau }) }; } @@ -200,9 +205,7 @@ export function enrollPage(store: StoreWithDesign, referrer: { code: string; fir ${ referrer ? `
${e(fill(String(moduleConfig(store, 'referral').inviteText), { parrain: referrer.firstName }))} ${e( - Number(moduleConfig(store, 'referral').friendPoints) > 0 - ? fill(String(moduleConfig(store, 'referral').inviteGiftText), { quantite: quantity(Number(moduleConfig(store, 'referral').friendPoints), stamp(store)) }) - : '', + friendReward(store).recompense ? fill(String(moduleConfig(store, 'referral').inviteGiftText), friendReward(store)) : '', )}
` : '' } @@ -384,8 +387,8 @@ ${ opts.referralUrl ? `
${e(String(referral.sectionTitle))} - ${e(fill(String(referral.sectionText), { quantite: quantity(Number(referral.points), stamp(store)) }))}${ - Number(referral.friendPoints) > 0 ? ` ${e(fill(String(referral.sectionFriendText), { quantite: quantity(Number(referral.friendPoints), stamp(store)) }))}` : '' + ${e(fill(String(referral.sectionText), rewardVars(Number(referral.points), referral.gift, stamp(store))))}${ + friendReward(store).recompense ? ` ${e(fill(String(referral.sectionFriendText), friendReward(store)))}` : '' } diff --git a/backend/src/modules/catalog.ts b/backend/src/modules/catalog.ts index 529590c..465b682 100644 --- a/backend/src/modules/catalog.ts +++ b/backend/src/modules/catalog.ts @@ -38,6 +38,15 @@ const title = (def = '{magasin}'): FieldDef => ({ maxLength: 40, variables: ['{magasin}'], }); +/** Cadeau en nature (« Un café offert ») : remis en caisse depuis l'app Pro. */ +const GIFT = (key: string, label: string): FieldDef => ({ + key, + type: 'text', + label, + help: 'Ex. : « Un café offert ». Le client le présente en caisse et l’employé le remet depuis l’app Pro. Vide = pas de cadeau en nature.', + default: '', + maxLength: 60, +}); const hours = (from: number, to: number): FieldDef[] => [ { key: 'hourFrom', type: 'hour', label: 'Envoi à partir de', default: from, min: 0, max: 23, help: 'Heure de Paris.' }, { key: 'hourTo', type: 'hour', label: "Envoi jusqu'à", default: to, min: 1, max: 24, help: 'Heure de Paris (exclue).' }, @@ -75,12 +84,13 @@ export const MODULES: ModuleDef[] = [ id: 'birthday', name: "Offre d'anniversaire", tagline: 'Un cadeau le jour de l’anniversaire', - description: 'Les clients indiquent leur anniversaire (jour et mois). Le jour J, ils reçoivent une notification et, si vous le souhaitez, des points offerts. Un cadeau par an.', + description: 'Les clients indiquent leur anniversaire (jour et mois). Le jour J, ils reçoivent une notification et la récompense de votre choix : points ou tampons offerts, et/ou un cadeau à retirer en magasin. Un cadeau par an.', enabledByDefault: false, fields: [ - { key: 'points', type: 'int', label: 'Points ou tampons offerts', unit: '(0 = message seulement)', default: 0, min: 0, max: 1000 }, + { key: 'points', type: 'int', label: 'Points ou tampons offerts', unit: '(0 = aucun)', default: 0, min: 0, max: 1000 }, + GIFT('gift', 'Cadeau à retirer en magasin'), { key: 'message', type: 'textarea', label: 'Message du jour J', default: 'Joyeux anniversaire, {prenom} ! {cadeau}', maxLength: 160, variables: [...V_CLIENT, '{cadeau}'] }, - { key: 'giftText', type: 'text', label: 'Texte du cadeau', default: '{quantite} offerts sur votre carte.', maxLength: 80, variables: ['{quantite}'], help: 'Remplace {cadeau} quand des points sont offerts.' }, + { key: 'giftText', type: 'text', label: 'Texte du cadeau', default: 'Pour vous : {recompense}.', maxLength: 80, variables: ['{recompense}', '{quantite}'], help: 'Remplace {cadeau} quand une récompense est prévue.' }, title(), { key: 'askTitle', type: 'text', label: 'Titre de la demande (page de la carte)', default: 'Un cadeau pour votre anniversaire ?', maxLength: 60 }, { key: 'askText', type: 'textarea', label: 'Texte de la demande', default: '{cadeau} Indiquez le jour et le mois (l’année n’est pas demandée).', maxLength: 200, variables: ['{cadeau}'] }, @@ -108,20 +118,22 @@ export const MODULES: ModuleDef[] = [ id: 'referral', name: 'Parrainage', tagline: 'Vos clients recrutent leurs proches', - description: 'Chaque client partage un lien personnel. Quand un ami s’inscrit avec ce lien puis fait son premier passage, le parrain (et le filleul si vous le souhaitez) est récompensé.', + description: 'Chaque client partage un lien personnel. Quand un ami s’inscrit avec ce lien puis fait son premier passage, le parrain (et le filleul si vous le souhaitez) reçoit la récompense de votre choix : points ou tampons, et/ou un cadeau à retirer en magasin.', enabledByDefault: false, fields: [ { key: 'points', type: 'int', label: 'Offerts au parrain', unit: 'points / tampons', default: 5, min: 0, max: 1000 }, + GIFT('gift', 'Cadeau du parrain à retirer en magasin'), { key: 'friendPoints', type: 'int', label: 'Offerts au filleul', unit: 'points / tampons', default: 0, min: 0, max: 1000 }, + GIFT('friendGift', 'Cadeau du filleul à retirer en magasin'), { key: 'maxRewardsPer30Days', type: 'int', label: 'Récompenses maximum par parrain', unit: 'sur 30 jours', default: 10, min: 1, max: 1000 }, - { key: 'referrerMessage', type: 'textarea', label: 'Message au parrain', default: 'Merci {prenom} ! {filleul} est venu(e) grâce à vous : {quantite} offerts.', maxLength: 160, variables: [...V_CLIENT, '{filleul}', '{quantite}'] }, - { key: 'friendMessage', type: 'textarea', label: 'Message au filleul', default: 'Bienvenue, {prenom} ! {quantite} offerts grâce à votre parrainage.', maxLength: 160, variables: [...V_CLIENT, '{quantite}'] }, + { key: 'referrerMessage', type: 'textarea', label: 'Message au parrain', default: 'Merci {prenom} ! {filleul} est venu(e) grâce à vous : {recompense}.', maxLength: 160, variables: [...V_CLIENT, '{filleul}', '{recompense}', '{quantite}'] }, + { key: 'friendMessage', type: 'textarea', label: 'Message au filleul', default: 'Bienvenue, {prenom} ! Grâce à votre parrainage : {recompense}.', maxLength: 160, variables: [...V_CLIENT, '{recompense}', '{quantite}'] }, title(), { key: 'inviteText', type: 'text', label: "Bandeau de la page d'inscription", default: '{parrain} vous invite !', maxLength: 80, variables: ['{parrain}'] }, - { key: 'inviteGiftText', type: 'text', label: 'Annonce du cadeau du filleul (inscription)', default: '{quantite} offerts à votre premier passage en magasin.', maxLength: 120, variables: ['{quantite}'], help: 'Affichée si le filleul reçoit des points.' }, + { key: 'inviteGiftText', type: 'text', label: 'Annonce du cadeau du filleul (inscription)', default: 'À votre premier passage en magasin : {recompense}.', maxLength: 120, variables: ['{recompense}', '{quantite}'], help: 'Affichée si le filleul reçoit une récompense.' }, { key: 'sectionTitle', type: 'text', label: 'Titre de la section (page de la carte)', default: 'Parrainez vos proches', maxLength: 60 }, - { key: 'sectionText', type: 'textarea', label: 'Texte de la section', default: 'Gagnez {quantite} pour chaque ami qui s’inscrit avec votre lien et passe en magasin.', maxLength: 200, variables: ['{quantite}'] }, - { key: 'sectionFriendText', type: 'text', label: 'Phrase sur le cadeau du filleul (page de la carte)', default: 'Votre ami reçoit {quantite} lui aussi.', maxLength: 120, variables: ['{quantite}'], help: 'Affichée si le filleul reçoit des points.' }, + { key: 'sectionText', type: 'textarea', label: 'Texte de la section', default: 'Pour chaque ami qui s’inscrit avec votre lien et passe en magasin : {recompense}.', maxLength: 200, variables: ['{recompense}', '{quantite}'] }, + { key: 'sectionFriendText', type: 'text', label: 'Phrase sur le cadeau du filleul (page de la carte)', default: 'Votre ami reçoit lui aussi : {recompense}.', maxLength: 120, variables: ['{recompense}', '{quantite}'], help: 'Affichée si le filleul reçoit une récompense.' }, { key: 'shareText', type: 'text', label: 'Texte du partage', default: 'Rejoignez le programme de fidélité de {magasin} :', maxLength: 120, variables: ['{magasin}'] }, { key: 'linkLabel', type: 'text', label: 'Texte du lien au dos de la carte', default: 'Mon lien de parrainage', maxLength: 40 }, ], @@ -207,6 +219,18 @@ export function quantity(n: number, stamp: boolean) { return `${n} ${stamp ? 'tampon' : 'point'}${n > 1 ? 's' : ''}`; } +/** « 3 tampons offerts », « Un café offert », « 3 tampons offerts et un café offert » ; vide si rien. */ +export function rewardText(points: number, gift: unknown, stamp: boolean) { + const g = typeof gift === 'string' ? gift.trim() : ''; + const parts: string[] = []; + if (points > 0) parts.push(`${quantity(points, stamp)} offert${points > 1 ? 's' : ''}`); + if (g) parts.push(parts.length ? g.charAt(0).toLowerCase() + g.slice(1) : g); + return parts.join(' et '); +} + +/** Variables {recompense} et {quantite} des textes de récompense. */ +export const rewardVars = (points: number, gift: unknown, stamp: boolean) => ({ recompense: rewardText(points, gift, stamp), quantite: quantity(points, stamp) }); + /** Valide et normalise les réglages envoyés par un formulaire ; renvoie les erreurs lisibles. */ export function validateConfig(id: ModuleId, input: Record): { values: Values; errors: string[] } { const def = moduleDef(id); diff --git a/backend/src/modules/modules.controller.ts b/backend/src/modules/modules.controller.ts index 4e35b46..d97bbed 100644 --- a/backend/src/modules/modules.controller.ts +++ b/backend/src/modules/modules.controller.ts @@ -42,7 +42,7 @@ export class AdminModulesController { } } -/** App Pro : les gérants règlent eux-mêmes leurs modules. */ +/** App Pro : les dirigeants règlent eux-mêmes leurs modules. */ @Controller('staff/modules') @UseGuards(JwtAuthGuard, StaffGuard) @StaffRoles('MANAGER') diff --git a/backend/src/referrals/referrals.service.ts b/backend/src/referrals/referrals.service.ts index 69a535f..39e5ac0 100644 --- a/backend/src/referrals/referrals.service.ts +++ b/backend/src/referrals/referrals.service.ts @@ -2,7 +2,7 @@ import { Global, Injectable, Logger, Module, OnModuleInit } from '@nestjs/common import { randomInt } from 'crypto'; import { Prisma } from '@prisma/client'; import { PrismaService } from '../prisma/prisma.service'; -import { fill, moduleActive, moduleConfig, quantity, StoreModules } from '../modules/catalog'; +import { fill, moduleActive, moduleConfig, rewardVars, StoreModules } from '../modules/catalog'; import { ModulesService } from '../modules/modules.service'; import { CardUpdatesService } from '../wallet/card-updates.service'; @@ -86,31 +86,37 @@ export class ReferralsService implements OnModuleInit { const base = { magasin: store.name }; const friendPoints = Number(c.friendPoints); - const friendNews = friendPoints > 0 ? fill(String(c.friendMessage), { ...base, prenom: friend.customer.firstName, quantite: quantity(friendPoints, stamp) }) : null; + const friendGift = String(c.friendGift).trim(); + const friendVars = rewardVars(friendPoints, friendGift, stamp); + const friendNews = friendVars.recompense ? fill(String(c.friendMessage), { ...base, prenom: friend.customer.firstName, ...friendVars }) : null; // Conditionnel : un seul cadeau même si deux crédits arrivent en même temps. const { count } = await this.prisma.loyaltyCard.updateMany({ where: { id: friend.id, referralRewardedAt: null }, data: { referralRewardedAt: now, - ...(friendNews && { balance: { increment: friendPoints }, personalNews: friendNews, personalNewsAt: now, passUpdatedAt: now }), + ...(friendNews && { balance: { increment: friendPoints }, personalNews: friendNews.slice(0, 200), personalNewsAt: now, passUpdatedAt: now }), }, }); if (!count) return; + if (friendGift) await this.prisma.gift.create({ data: { cardId: friend.id, label: friendGift, source: 'REFERRAL_FRIEND' } }); if (friendNews) await this.cardUpdates.remind(friend.id, friendNews, title); const points = Number(c.points); + const gift = String(c.gift).trim(); + const vars = rewardVars(points, gift, stamp); const since = new Date(now.getTime() - 30 * 24 * 3600_000); const recent = await this.prisma.loyaltyCard.count({ where: { referredById: friend.referredById, referralRewardedAt: { gte: since }, id: { not: friend.id } }, }); - if (points <= 0 || recent >= Number(c.maxRewardsPer30Days)) return; + if (!vars.recompense || recent >= Number(c.maxRewardsPer30Days)) return; const referrer = await this.prisma.loyaltyCard.findUnique({ where: { id: friend.referredById }, include: { customer: true } }); if (!referrer || referrer.storeId !== store.id) return; - const news = fill(String(c.referrerMessage), { ...base, prenom: referrer.customer.firstName, filleul: friend.customer.firstName, quantite: quantity(points, stamp) }); + const news = fill(String(c.referrerMessage), { ...base, prenom: referrer.customer.firstName, filleul: friend.customer.firstName, ...vars }); await this.prisma.loyaltyCard.update({ where: { id: referrer.id }, - data: { balance: { increment: points }, personalNews: news, personalNewsAt: now, passUpdatedAt: now }, + data: { balance: { increment: points }, personalNews: news.slice(0, 200), personalNewsAt: now, passUpdatedAt: now }, }); + if (gift) await this.prisma.gift.create({ data: { cardId: referrer.id, label: gift, source: 'REFERRAL' } }); await this.cardUpdates.remind(referrer.id, news, title); } } diff --git a/backend/src/signup/signup.controller.ts b/backend/src/signup/signup.controller.ts new file mode 100644 index 0000000..4d17a5d --- /dev/null +++ b/backend/src/signup/signup.controller.ts @@ -0,0 +1,58 @@ +import { Body, Controller, HttpCode, Post } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import { PickType } from '@nestjs/mapped-types'; +import { Throttle } from '@nestjs/throttler'; +import { BillingInterval, Plan } from '@prisma/client'; +import { Equals, IsEnum, IsString, Length } from 'class-validator'; +import { CreateStoreDto } from '../stores/dto/store.dto'; +import { BillingService } from '../billing/billing.service'; +import { SignupService } from './signup.service'; + +class SignupDto extends PickType(CreateStoreDto, ['name', 'siret', 'addressLine', 'postalCode', 'city', 'contactName', 'contactEmail', 'contactPhone'] as const) { + @IsString() @Length(10, 128, { message: 'Mot de passe : 10 caractères minimum' }) + password!: string; + + @IsEnum(Plan) + plan!: Plan; + + @IsEnum(BillingInterval) + interval!: BillingInterval; + + /** Acceptation des CGV. */ + @Equals(true, { message: 'Acceptez les conditions générales de vente' }) + cgv!: boolean; +} + +/** Inscription en ligne : renvoie l'adresse de paiement Stripe. */ +@Controller('public/signup') +export class SignupController { + constructor( + private signup: SignupService, + private billing: BillingService, + private config: ConfigService, + ) {} + + @Post() + @HttpCode(200) + @Throttle({ default: { limit: 5, ttl: 10 * 60_000 } }) + async start(@Body() dto: SignupDto) { + const { password, plan, interval, cgv: _cgv, ...data } = dto; + const pending = await this.signup.prepare(data, password, plan, interval); + const price = await this.billing.priceFor(plan, interval); + const espace = `${this.config.get('adminUrl')}/espace`; + const session = await this.billing.stripe.checkout.sessions.create({ + mode: 'subscription', + customer_email: pending.email, + line_items: [{ price: price.id, quantity: 1 }], + payment_method_types: ['card', 'sepa_debit'], + allow_promotion_codes: true, + locale: 'fr', + client_reference_id: pending.id, + subscription_data: { metadata: { signupId: pending.id } }, + metadata: { signupId: pending.id }, + success_url: `${espace}?bienvenue=1`, + cancel_url: `${this.config.get('adminUrl')}/inscription?formule=${plan.toLowerCase()}&annule=1`, + }); + return { url: session.url }; + } +} diff --git a/backend/src/signup/signup.module.ts b/backend/src/signup/signup.module.ts new file mode 100644 index 0000000..5fb7158 --- /dev/null +++ b/backend/src/signup/signup.module.ts @@ -0,0 +1,5 @@ +import { Module } from '@nestjs/common'; +import { SignupService } from './signup.service'; + +@Module({ providers: [SignupService], exports: [SignupService] }) +export class SignupModule {} diff --git a/backend/src/signup/signup.service.ts b/backend/src/signup/signup.service.ts new file mode 100644 index 0000000..c8ca37a --- /dev/null +++ b/backend/src/signup/signup.service.ts @@ -0,0 +1,117 @@ +import { ConflictException, Injectable, Logger } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import { BillingInterval, Plan, Prisma } from '@prisma/client'; +import * as argon2 from 'argon2'; +import Stripe from 'stripe'; +import { PrismaService } from '../prisma/prisma.service'; +import { MailService } from '../mail/mail.service'; +import { emailLayout, esc } from '../mail/email-layout'; +import { uniqueSlug } from '../stores/slug'; +import { PLANS } from '../billing/plans'; + +/** Champs du magasin saisis à l'inscription (copiés tels quels dans Store). */ +export interface SignupStoreData { + name: string; + siret: string; + addressLine: string; + postalCode: string; + city: string; + contactName: string; + contactEmail: string; + contactPhone: string; +} + +/** + * Inscription en ligne depuis la page Tarif : formulaire → paiement Stripe → + * création automatique du magasin et du compte Dirigeant (webhook) → e-mail + * de bienvenue avec le lien vers l'espace web pour concevoir la carte. + */ +@Injectable() +export class SignupService { + private readonly logger = new Logger(SignupService.name); + + constructor( + private prisma: PrismaService, + private config: ConfigService, + private mail: MailService, + ) {} + + /** Enregistre la demande ; rien n'est créé avant le paiement. */ + async prepare(data: SignupStoreData, password: string, plan: Plan, interval: BillingInterval) { + const email = data.contactEmail.toLowerCase(); + if (await this.prisma.staffUser.findUnique({ where: { email }, select: { id: true } })) { + throw new ConflictException('Un compte existe déjà avec cet e-mail. Connectez-vous à votre espace, ou utilisez une autre adresse.'); + } + return this.prisma.pendingSignup.create({ + data: { email, data: { ...data, contactEmail: email } as unknown as Prisma.InputJsonValue, passwordHash: await argon2.hash(password), plan, interval }, + }); + } + + /** + * Paiement réussi : crée le magasin (brouillon), le compte Dirigeant et + * l'abonnement. Idempotent (webhook rejoué). Renvoie l'id du magasin. + */ + async complete(session: Stripe.Checkout.Session, stripe: Stripe): Promise { + const pending = await this.prisma.pendingSignup.findUnique({ where: { id: session.metadata!.signupId } }); + if (!pending) { + this.logger.error(`Inscription ${session.metadata!.signupId} introuvable (session ${session.id})`); + return undefined; + } + if (pending.storeId) return pending.storeId; + const data = pending.data as unknown as SignupStoreData; + const customerId = String(session.customer); + + const store = await this.prisma.$transaction(async (tx) => { + const store = await tx.store.create({ data: { ...data, slug: await uniqueSlug(this.prisma, data.name) } }); + await tx.subscription.create({ data: { storeId: store.id, stripeCustomerId: customerId, plan: pending.plan, interval: pending.interval } }); + await tx.pendingSignup.update({ where: { id: pending.id }, data: { storeId: store.id } }); + return store; + }); + // Compte Dirigeant : l'e-mail a pu être pris entre-temps (cas rarissime) ; le magasin existe quand même. + try { + await this.prisma.staffUser.create({ + data: { storeId: store.id, email: pending.email, displayName: data.contactName, role: 'MANAGER', passwordHash: pending.passwordHash }, + }); + } catch (e) { + if (!(e instanceof Prisma.PrismaClientKnownRequestError && e.code === 'P2002')) throw e; + this.logger.error(`Inscription ${pending.id} : e-mail ${pending.email} déjà utilisé, compte Dirigeant à créer depuis l'admin`); + } + // Les prochains événements Stripe retrouvent le magasin par ces métadonnées. + await stripe.customers.update(customerId, { + name: data.name, + phone: data.contactPhone, + address: { line1: data.addressLine, postal_code: data.postalCode, city: data.city, country: 'FR' }, + metadata: { storeId: store.id, siret: data.siret }, + }); + if (session.subscription) await stripe.subscriptions.update(String(session.subscription), { metadata: { storeId: store.id } }); + + await this.welcome(store.id).catch((e) => this.logger.error(`E-mail de bienvenue non envoyé : ${(e as Error).message}`)); + this.logger.log(`Inscription en ligne : magasin ${store.id} (${data.name}) créé, formule ${pending.plan}`); + return store.id; + } + + private async welcome(storeId: string) { + const store = await this.prisma.store.findUniqueOrThrow({ where: { id: storeId }, include: { subscription: true } }); + const espace = `${this.config.get('adminUrl')}/espace`; + const def = PLANS[store.subscription?.plan ?? 'ESSENTIEL']; + const text = `Bonjour ${store.contactName},\n\nBienvenue sur MonEspacePro ! Votre abonnement ${def.name} pour ${store.name} est actif.\n\nDernière étape : concevez votre carte de fidélité (logo, couleurs, récompenses) sur ${espace}, avec l'e-mail ${store.contactEmail} et le mot de passe choisi à l'inscription. Votre programme s'ouvre à vos clients dès la carte enregistrée.\n\nEn caisse, installez l'app MonEspacePro Pro sur votre téléphone et connectez-vous avec les mêmes identifiants.\n\nMonEspacePro`; + const html = emailLayout({ + webUrl: this.config.get('webUrl')!, + preheader: `Concevez votre carte de fidélité pour ouvrir ${store.name} à vos clients.`, + eyebrow: `Formule ${def.name}`, + title: 'Bienvenue sur MonEspacePro', + paragraphs: [ + `Bonjour ${esc(store.contactName)},`, + `Votre abonnement ${esc(def.name)} pour ${esc(store.name)} est actif. Dernière étape : concevez votre carte de fidélité (logo, couleurs, récompenses). Votre programme s'ouvre à vos clients dès la carte enregistrée.`, + ], + cta: { label: 'Concevoir ma carte', url: espace }, + details: [ + ['Identifiant', esc(store.contactEmail)], + ['Mot de passe', 'Celui choisi à l’inscription'], + ['En caisse', 'App MonEspacePro Pro, mêmes identifiants'], + ], + note: 'Depuis l’app Pro, vous créez aussi les comptes de vos employés et réglez vos modules.', + }); + await this.mail.send(store.contactEmail, `Bienvenue sur MonEspacePro, ${store.name}`, text, html); + } +} diff --git a/backend/src/staff/staff-space.controller.ts b/backend/src/staff/staff-space.controller.ts new file mode 100644 index 0000000..35515df --- /dev/null +++ b/backend/src/staff/staff-space.controller.ts @@ -0,0 +1,150 @@ +import { + BadRequestException, + Body, + Controller, + ForbiddenException, + Get, + HttpCode, + Param, + ParseEnumPipe, + Patch, + Post, + Put, + UploadedFile, + UseGuards, + UseInterceptors, +} from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import { FileInterceptor } from '@nestjs/platform-express'; +import { Throttle } from '@nestjs/throttler'; +import * as argon2 from 'argon2'; +import { IsString, Length } from 'class-validator'; +import { JwtPayload } from '../common/auth.types'; +import { CurrentUser, JwtAuthGuard, StaffGuard, StaffRoles } from '../common/guards'; +import { PrismaService } from '../prisma/prisma.service'; +import { CardDesignService, ImageKind } from '../card-design/card-design.service'; +import { SaveCardDesignDto } from '../card-design/dto/card-design.dto'; +import { BillingService } from '../billing/billing.service'; +import { CreateStaffDto, UpdateStaffDto } from './dto/staff.dto'; +import { StaffService } from './staff.service'; + +enum ImageKindParam { + logo = 'logo', + strip = 'strip', +} + +function staffOf(user: JwtPayload) { + if (user.kind !== 'staff') throw new Error('StaffGuard manquant'); + return user; +} + +class ChangePasswordDto { + @IsString() + current!: string; + + @IsString() @Length(10, 128, { message: 'Nouveau mot de passe : 10 caractères minimum' }) + next!: string; +} + +/** + * Espace du Dirigeant (app Pro et espace web) : fiche du magasin, conception + * de la carte, comptes des employés. Les employés n'y ont pas accès. + */ +@Controller('staff') +@UseGuards(JwtAuthGuard, StaffGuard) +@StaffRoles('MANAGER') +export class StaffSpaceController { + constructor( + private prisma: PrismaService, + private config: ConfigService, + private designs: CardDesignService, + private staff: StaffService, + private billing: BillingService, + ) {} + + @Get('store') + async store(@CurrentUser() user: JwtPayload) { + const { storeId } = staffOf(user); + const store = await this.prisma.store.findUniqueOrThrow({ where: { id: storeId }, include: { subscription: true } }); + const sub = store.subscription; + const subscribed = !!sub?.stripeSubscriptionId && sub.status !== 'CANCELED'; + return { + id: store.id, + name: store.name, + status: store.status, + enrollUrl: `${this.config.get('webUrl')}/c/${store.slug}`, + subscription: sub && { status: sub.status, plan: sub.plan, interval: sub.interval }, + // Pas encore payé : le Dirigeant peut finaliser lui-même l'abonnement. + subscribeUrl: subscribed ? null : this.billing.subscribeUrl(store.id), + }; + } + + // ── Carte de fidélité ── + @Get('card-design') + getDesign(@CurrentUser() user: JwtPayload) { + return this.designs.get(staffOf(user).storeId); + } + + @Put('card-design') + saveDesign(@CurrentUser() user: JwtPayload, @Body() dto: SaveCardDesignDto) { + return this.designs.save(staffOf(user).storeId, dto); + } + + @Post('card-design/images/:kind') + @UseInterceptors(FileInterceptor('file', { limits: { fileSize: 2 * 1024 * 1024 } })) + upload( + @CurrentUser() user: JwtPayload, + @Param('kind', new ParseEnumPipe(ImageKindParam, { exceptionFactory: () => new BadRequestException('Type d’image inconnu') })) + kind: ImageKind, + @UploadedFile() file: Express.Multer.File | undefined, + ) { + return this.designs.saveImage(staffOf(user).storeId, kind, file); + } + + // ── Employés ── + @Get('team') + team(@CurrentUser() user: JwtPayload) { + return this.staff.list(staffOf(user).storeId); + } + + @Post('team') + addMember(@CurrentUser() user: JwtPayload, @Body() dto: CreateStaffDto) { + return this.staff.create(staffOf(user).storeId, dto); + } + + @Patch('team/:id') + updateMember(@CurrentUser() user: JwtPayload, @Param('id') id: string, @Body() dto: UpdateStaffDto) { + const me = staffOf(user); + // Évite de se retirer soi-même l'accès (plus aucun Dirigeant). + if (id === me.sub && (dto.active === false || (dto.role && dto.role !== 'MANAGER'))) { + throw new ForbiddenException('Vous ne pouvez pas désactiver votre propre compte ni retirer votre rôle de Dirigeant.'); + } + return this.staff.update(me.storeId, id, dto); + } + + @Post('team/:id/reset-password') + @HttpCode(200) + resetMember(@CurrentUser() user: JwtPayload, @Param('id') id: string) { + const me = staffOf(user); + if (id === me.sub) throw new ForbiddenException('Changez votre propre mot de passe depuis « Mon compte ».'); + return this.staff.resetPassword(me.storeId, id); + } +} + +/** Mot de passe personnel : tous les rôles. */ +@Controller('staff/password') +@UseGuards(JwtAuthGuard, StaffGuard) +export class StaffPasswordController { + constructor(private prisma: PrismaService) {} + + @Post() + @HttpCode(200) + @Throttle({ default: { limit: 5, ttl: 10 * 60_000 } }) + async change(@CurrentUser() user: JwtPayload, @Body() dto: ChangePasswordDto) { + const me = staffOf(user); + const staff = await this.prisma.staffUser.findUniqueOrThrow({ where: { id: me.sub } }); + if (!(await argon2.verify(staff.passwordHash, dto.current))) throw new BadRequestException('Mot de passe actuel incorrect'); + await this.prisma.staffUser.update({ where: { id: me.sub }, data: { passwordHash: await argon2.hash(dto.next) } }); + return { ok: true }; + } +} diff --git a/backend/src/stats/stats.controller.ts b/backend/src/stats/stats.controller.ts index 5c9e4dc..7018aba 100644 --- a/backend/src/stats/stats.controller.ts +++ b/backend/src/stats/stats.controller.ts @@ -53,7 +53,7 @@ export class AdminStatsController { } } -/** App Pro : statistiques et exports pour les gérants (formule Pro). */ +/** App Pro : statistiques et exports pour les dirigeants (formule Pro). */ @Controller('staff') @UseGuards(JwtAuthGuard, StaffGuard) @StaffRoles('MANAGER') @@ -74,7 +74,7 @@ export class StaffStatsController { return this.stats.compute(user.storeId, period(days)); } - /** Le fichier part par e-mail au gérant : rien à stocker sur le téléphone. */ + /** Le fichier part par e-mail au dirigeant : rien à stocker sur le téléphone. */ @Post('export') @HttpCode(200) @Throttle({ default: { limit: 5, ttl: 10 * 60_000 } }) diff --git a/backend/src/stores/activation.ts b/backend/src/stores/activation.ts new file mode 100644 index 0000000..f1262e1 --- /dev/null +++ b/backend/src/stores/activation.ts @@ -0,0 +1,17 @@ +import { Logger } from '@nestjs/common'; +import { PrismaService } from '../prisma/prisma.service'; + +const logger = new Logger('Activation'); + +/** + * Ouverture automatique d'un magasin en brouillon dès que tout est prêt : + * abonnement payé ET carte de fidélité conçue (appelé après chacun des deux). + */ +export async function activateIfReady(prisma: PrismaService, storeId: string) { + const { count } = await prisma.store.updateMany({ + where: { id: storeId, status: 'DRAFT', cardDesign: { isNot: null }, subscription: { is: { status: 'ACTIVE' } } }, + data: { status: 'ACTIVE' }, + }); + if (count) logger.log(`Magasin ${storeId} ouvert automatiquement (abonnement payé, carte conçue)`); + return count > 0; +} diff --git a/backend/src/stores/dto/store.dto.ts b/backend/src/stores/dto/store.dto.ts index b3e9463..15531ed 100644 --- a/backend/src/stores/dto/store.dto.ts +++ b/backend/src/stores/dto/store.dto.ts @@ -1,5 +1,5 @@ import { PartialType } from '@nestjs/mapped-types'; -import { StoreStatus } from '@prisma/client'; +import { BillingInterval, Plan, StoreStatus } from '@prisma/client'; import { Transform } from 'class-transformer'; import { IsEmail, @@ -67,6 +67,15 @@ export class CreateStoreDto { minScanIntervalMin!: number; } +/** Création depuis l'admin : la formule choisie part avec le lien de paiement. */ +export class AdminCreateStoreDto extends CreateStoreDto { + @IsEnum(Plan) + plan!: Plan; + + @IsEnum(BillingInterval) + interval!: BillingInterval; +} + export class UpdateStoreDto extends PartialType(CreateStoreDto) {} export class SetStoreStatusDto { diff --git a/backend/src/stores/slug.ts b/backend/src/stores/slug.ts new file mode 100644 index 0000000..ce878b1 --- /dev/null +++ b/backend/src/stores/slug.ts @@ -0,0 +1,18 @@ +import { randomBytes } from 'crypto'; +import { PrismaService } from '../prisma/prisma.service'; + +/** « Boulangerie Le Fournil » → « boulangerie-le-fournil-k3f9 » (suffixe : non devinable, sans collision). */ +export async function uniqueSlug(prisma: PrismaService, name: string) { + const base = + name + .normalize('NFD') + .replace(/[̀-ͯ]/g, '') + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-|-$/g, '') + .slice(0, 40) || 'magasin'; + for (;;) { + const slug = `${base}-${randomBytes(3).toString('hex').slice(0, 4)}`; + if (!(await prisma.store.findUnique({ where: { slug }, select: { id: true } }))) return slug; + } +} diff --git a/backend/src/stores/stores.controller.ts b/backend/src/stores/stores.controller.ts index f6b910b..3b5895a 100644 --- a/backend/src/stores/stores.controller.ts +++ b/backend/src/stores/stores.controller.ts @@ -1,12 +1,18 @@ import { Body, Controller, Get, Param, Patch, Post, Query, UseGuards } from '@nestjs/common'; import { AdminGuard, JwtAuthGuard } from '../common/guards'; -import { CreateStoreDto, ListStoresQuery, SetStoreStatusDto, UpdateStoreDto } from './dto/store.dto'; +import { AdminCreateStoreDto, ListStoresQuery, SetStoreStatusDto, UpdateStoreDto } from './dto/store.dto'; import { StoresService } from './stores.service'; +import { BillingService } from '../billing/billing.service'; +import { StaffService } from '../staff/staff.service'; @Controller('admin/stores') @UseGuards(JwtAuthGuard, AdminGuard) export class StoresController { - constructor(private stores: StoresService) {} + constructor( + private stores: StoresService, + private billing: BillingService, + private staff: StaffService, + ) {} @Get() list(@Query() query: ListStoresQuery) { @@ -14,8 +20,25 @@ export class StoresController { } @Post() - create(@Body() dto: CreateStoreDto) { - return this.stores.create(dto); + async create(@Body() dto: AdminCreateStoreDto) { + const { plan, interval, ...fields } = dto; + const store = await this.stores.create(fields); + // Tout part automatiquement : compte Dirigeant du contact + lien de paiement par e-mail. + const manager = await this.staff + .create(store.id, { displayName: store.contactName, email: store.contactEmail, role: 'MANAGER' }) + .catch(() => null); // e-mail déjà utilisé par un autre compte : à créer à la main + const link = await this.billing + .checkoutLink(store.id, { + plan, + interval, + sendEmail: true, + credentials: manager ? { email: manager.email, password: manager.provisionalPassword } : undefined, + }) + .catch(async (e: Error) => { + await this.billing.choosePlan(store.id, plan, interval); + return { url: null, emailedTo: null, error: e.message }; + }); + return { ...store, manager, link }; } @Get(':id') diff --git a/backend/src/stores/stores.service.ts b/backend/src/stores/stores.service.ts index 4db6e39..626ecb4 100644 --- a/backend/src/stores/stores.service.ts +++ b/backend/src/stores/stores.service.ts @@ -1,8 +1,8 @@ import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { Prisma, Store, StoreStatus } from '@prisma/client'; -import { randomBytes } from 'crypto'; import { PrismaService } from '../prisma/prisma.service'; +import { uniqueSlug } from './slug'; import { CreateStoreDto, ListStoresQuery, UpdateStoreDto } from './dto/store.dto'; /** Transitions autorisées depuis l'admin (la suspension pour impayé viendra de Stripe). */ @@ -64,7 +64,7 @@ export class StoresService { async create(dto: CreateStoreDto) { const store = await this.prisma.store.create({ - data: { ...this.toData(dto), slug: await this.uniqueSlug(dto.name) } as Prisma.StoreCreateInput, + data: { ...this.toData(dto), slug: await uniqueSlug(this.prisma, dto.name) } as Prisma.StoreCreateInput, }); return this.present(store); } @@ -110,20 +110,4 @@ export class StoresService { const { maxAmountCents, minScanIntervalSec, ...rest } = s; return { ...rest, maxAmountEuros: maxAmountCents / 100, minScanIntervalMin: Math.round(minScanIntervalSec / 60) }; } - - /** « Boulangerie Le Fournil » → « boulangerie-le-fournil-k3f9 » (suffixe : non devinable, sans collision). */ - private async uniqueSlug(name: string) { - const base = - name - .normalize('NFD') - .replace(/[̀-ͯ]/g, '') - .toLowerCase() - .replace(/[^a-z0-9]+/g, '-') - .replace(/^-|-$/g, '') - .slice(0, 40) || 'magasin'; - for (;;) { - const slug = `${base}-${randomBytes(3).toString('hex').slice(0, 4)}`; - if (!(await this.prisma.store.findUnique({ where: { slug }, select: { id: true } }))) return slug; - } - } } diff --git a/backend/src/wallet/wallet.types.ts b/backend/src/wallet/wallet.types.ts index 16f147e..ac90af4 100644 --- a/backend/src/wallet/wallet.types.ts +++ b/backend/src/wallet/wallet.types.ts @@ -1,5 +1,5 @@ import { Prisma } from '@prisma/client'; -import { fill, ModuleId, moduleActive, moduleConfig, quantity } from '../modules/catalog'; +import { fill, ModuleId, moduleActive, moduleConfig, quantity, rewardVars } from '../modules/catalog'; /** Tout ce qu'il faut pour dessiner une carte, chargé en une requête. */ export const CARD_WITH_CONTEXT = { @@ -67,11 +67,11 @@ export function reminderText(card: CardWithContext) { return fill(String(moduleConfig(card.store, 'reminders').message), messageVars(card)); } -/** Annonce du cadeau d'anniversaire (« 3 tampons offerts sur votre carte. »), vide si message seulement. */ +/** Annonce du cadeau d'anniversaire (« Pour vous : 3 tampons offerts. »), vide si message seulement. */ export function birthdayGiftText(store: CardWithContext['store']) { const c = moduleConfig(store, 'birthday'); - const n = Number(c.points); - return n > 0 ? fill(String(c.giftText), { quantite: quantity(n, stampMode(store)) }) : ''; + const vars = rewardVars(Number(c.points), c.gift, stampMode(store)); + return vars.recompense ? fill(String(c.giftText), vars) : ''; } export function birthdayText(card: CardWithContext) { diff --git a/pro/app/campaigns.tsx b/pro/app/campaigns.tsx index 6f5107b..b6c0f8d 100644 --- a/pro/app/campaigns.tsx +++ b/pro/app/campaigns.tsx @@ -19,7 +19,7 @@ interface Overview { const when = (d: string) => new Date(d).toLocaleString('fr-FR', { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' }); -/** Campagnes (gérants, formule Pro) : un message envoyé en notification à toutes les cartes du magasin. */ +/** Campagnes (dirigeants, formule Pro) : un message envoyé en notification à toutes les cartes du magasin. */ export default function Campaigns() { const c = useColors(); const store = useStore(); diff --git a/pro/app/history.tsx b/pro/app/history.tsx index bf7495d..9fa8a54 100644 --- a/pro/app/history.tsx +++ b/pro/app/history.tsx @@ -13,7 +13,7 @@ const REASON: Record = { INSUFFICIENT_BALANCE: 'Refusé : solde insuffisant', }; -/** Historique (maquettes 9a/9b) : le gérant voit tout, l'employé ses opérations. */ +/** Historique (maquettes 9a/9b) : le dirigeant voit tout, l'employé ses opérations. */ export default function History() { const c = useColors(); const { me } = useSession(); diff --git a/pro/app/index.tsx b/pro/app/index.tsx index d2ac6a0..8b2832d 100644 --- a/pro/app/index.tsx +++ b/pro/app/index.tsx @@ -59,7 +59,7 @@ export default function Home() { {store.name} - {me?.displayName} · {isManager ? 'Gérant' : 'Employé'} + {me?.displayName} · {isManager ? 'Dirigeant' : 'Employé'} @@ -142,20 +142,20 @@ const EDITS = { ['10 €', `${euros(PLANS.PRO.priceCents.MONTH)} €`], ['

par mois, sans engagement

', '

par mois, sans engagement

'], ['

Prélèvement mensuel

10 € par magasin, prélevés chaque mois.

', '

Mensuel ou annuel

Prélevé chaque mois, ou une fois par an avec 2 mois offerts. Carte bancaire ou prélèvement SEPA.

'], - ['

Non. Le tarif est de 10 € par mois et par magasin, sans frais d’installation et sans commission.

', `

Non. Vous payez seulement votre formule, à partir de ${FROM} par mois et par magasin, sans frais d’installation et sans commission. Et les ${TRIAL_DAYS} premiers jours sont gratuits.

`], + ['

Non. Le tarif est de 10 € par mois et par magasin, sans frais d’installation et sans commission.

', `

Non. Vous payez seulement votre formule, à partir de ${FROM} par mois et par magasin, sans frais d’installation et sans commission.

`], ['

Automatiquement, au format PDF, après chaque prélèvement mensuel. La TVA n’est pas applicable (art. 293 B du CGI).

', '

Automatiquement, au format PDF, après chaque prélèvement (mensuel ou annuel). La TVA n’est pas applicable (art. 293 B du CGI).

'], ['

10 € par mois et par magasin. Le simulateur ci-dessus calcule le total.

', `

Chaque magasin a sa formule. À partir de 3 magasins, la formule Réseau revient à ${euros(PLANS.RESEAU.priceCents.MONTH)} € par mois et par magasin, avec toutes les fonctions Pro. Le simulateur ci-dessus calcule le total.

`], ], 'Main.dc.html': [ ['10 €/mois', `Dès ${euros(min)} €/mois`], [/
10 €<\/div>\s*

par mois et par magasin<\/p>/, `

À partir de

\n
${FROM}
\n

par mois et par magasin

`], - ['
  • Sans engagement, prélèvement mensuel
  • ', `
  • 3 formules, ${TRIAL_DAYS} jours d’essai gratuit
  • \n
  • Sans engagement, mensuel ou annuel
  • `], + ['
  • Sans engagement, prélèvement mensuel
  • ', `
  • 3 formules au choix
  • \n
  • Sans engagement, mensuel ou annuel
  • `], ['Voir le détail du tarif', 'Comparer les formules'], - ['

    10 € par mois et par magasin, sans engagement. Le prélèvement est mensuel et les factures sont automatiques.

    ', `

    À partir de ${FROM} par mois et par magasin, sans engagement, avec ${TRIAL_DAYS} jours d’essai gratuit. Paiement mensuel ou annuel, factures automatiques.

    `], + ['

    10 € par mois et par magasin, sans engagement. Le prélèvement est mensuel et les factures sont automatiques.

    ', `

    À partir de ${FROM} par mois et par magasin, sans engagement. Paiement mensuel ou annuel, factures automatiques.

    `], ], 'Faq.dc.html': [ ['

    Le tarif est de 10 € par mois et par magasin.

    ', `

    Chaque magasin a sa formule. À partir de 3 magasins, la formule Réseau revient à ${euros(PLANS.RESEAU.priceCents.MONTH)} € par mois et par magasin. Voir les formules.

    `], - ['

    10 € par mois et par magasin, sans frais d’installation et sans commission. TVA non applicable, art. 293 B du CGI.

    ', `

    Trois formules : Essentiel à ${euros(PLANS.ESSENTIEL.priceCents.MONTH)} €, Pro à ${euros(PLANS.PRO.priceCents.MONTH)} € et Réseau à ${euros(PLANS.RESEAU.priceCents.MONTH)} € par magasin, par mois. Sans frais d’installation, sans commission, ${TRIAL_DAYS} jours d’essai gratuit. TVA non applicable, art. 293 B du CGI. Comparer les formules.

    `], + ['

    10 € par mois et par magasin, sans frais d’installation et sans commission. TVA non applicable, art. 293 B du CGI.

    ', `

    Trois formules : Essentiel à ${euros(PLANS.ESSENTIEL.priceCents.MONTH)} €, Pro à ${euros(PLANS.PRO.priceCents.MONTH)} € et Réseau à ${euros(PLANS.RESEAU.priceCents.MONTH)} € par magasin, par mois. Sans frais d’installation, sans commission. TVA non applicable, art. 293 B du CGI. Comparer les formules.

    `], ], 'Cgv.dc.html': [ ['

    Le service est proposé au prix de 10 € par mois et par magasin. TVA non applicable, art. 293 B du CGI.

    ', '

    Le prix dépend de la formule choisie (Essentiel, Pro ou Réseau) et de sa périodicité (mensuelle ou annuelle). Il est indiqué sur la page Tarif et rappelé lors de la souscription. TVA non applicable, art. 293 B du CGI.

    '], @@ -173,7 +173,7 @@ function applyPricing(file, body) { const DESCRIPTIONS = { 'Main.dc.html': `La carte de fidélité dématérialisée pour les commerces indépendants : vos clients l'ajoutent à Apple Wallet ou Google Wallet, sans application. Dès ${euros(min)} € par mois, sans engagement.`, - 'Tarif.dc.html': `Trois formules sans engagement : Essentiel ${euros(PLANS.ESSENTIEL.priceCents.MONTH)} €, Pro ${euros(PLANS.PRO.priceCents.MONTH)} €, Réseau ${euros(PLANS.RESEAU.priceCents.MONTH)} € par magasin et par mois. ${TRIAL_DAYS} jours d’essai gratuit, sans frais d’installation. Modules inclus selon la formule.`, + 'Tarif.dc.html': `Trois formules sans engagement : Essentiel ${euros(PLANS.ESSENTIEL.priceCents.MONTH)} €, Pro ${euros(PLANS.PRO.priceCents.MONTH)} €, Réseau ${euros(PLANS.RESEAU.priceCents.MONTH)} € par magasin et par mois, sans frais d’installation. Modules inclus selon la formule.`, }; const CSS = [ diff --git a/site/comment-ca-marche/index.html b/site/comment-ca-marche/index.html index 5f29f05..7ce2a72 100644 --- a/site/comment-ca-marche/index.html +++ b/site/comment-ca-marche/index.html @@ -108,7 +108,7 @@
    3

    Durée estimée : [durée]

    Comptes employés et app Pro

    Vous créez les comptes de votre équipe. Chacun installe l’app MonEspacePro Pro sur son téléphone.

    Vous : inviter l’équipeEmployés : installer l’app
    -
    [Employé 1]Gérant
    [Employé 2]Employé
    +
    [Employé 1]Dirigeant
    [Employé 2]Employé
    diff --git a/site/faq/index.html b/site/faq/index.html index f8ef0c2..96b372a 100644 --- a/site/faq/index.html +++ b/site/faq/index.html @@ -128,7 +128,7 @@

    Paiement et résiliation

    -
    Combien ça coûte ?

    Trois formules : Essentiel à 19 €, Pro à 39 € et Réseau à 29 € par magasin, par mois. Sans frais d’installation, sans commission, 30 jours d’essai gratuit. TVA non applicable, art. 293 B du CGI. Comparer les formules.

    +
    Combien ça coûte ?

    Trois formules : Essentiel à 19 €, Pro à 39 € et Réseau à 29 € par magasin, par mois. Sans frais d’installation, sans commission. TVA non applicable, art. 293 B du CGI. Comparer les formules.

    Comment se passe le paiement ?

    Vous recevez un lien d’abonnement par e-mail. Le prélèvement est mensuel et la facture PDF est émise automatiquement.

    Puis-je résilier quand je veux ?

    Oui, à tout moment. Il n’y a pas d’engagement.

    diff --git a/site/fonctionnalites/index.html b/site/fonctionnalites/index.html index 85a4df2..f7370e5 100644 --- a/site/fonctionnalites/index.html +++ b/site/fonctionnalites/index.html @@ -146,13 +146,13 @@

    L’app Pro pour vos employés

    Scan, montant, récompenses, historique.

    -

    L’app mobile MonEspacePro Pro tient dans la poche de l’équipe. Deux rôles : gérant et employé.

    +

    L’app mobile MonEspacePro Pro tient dans la poche de l’équipe. Deux rôles : dirigeant et employé.

    • Scanner la carte du client
    • Saisir le montant, valider une récompense
    • Retrouver chaque opération dans l’historique
    MonEspacePro Pro
    -
    EmployéGérant
    +
    EmployéDirigeant
    Scanner
    Montant
    diff --git a/site/index.html b/site/index.html index 5e7380c..9b23e85 100644 --- a/site/index.html +++ b/site/index.html @@ -245,7 +245,7 @@
  • La carte à vos couleurs, dans le Wallet
  • L’app MonEspacePro Pro pour vos employés
  • L’affichette de comptoir A5 / A6
  • -
  • 3 formules, 30 jours d’essai gratuit
  • +
  • 3 formules au choix
  • Sans engagement, mensuel ou annuel
  • Factures automatiques
  • @@ -267,7 +267,7 @@
    Mes clients doivent-ils installer une application ?

    Non. Ils scannent le QR du comptoir, saisissent leur prénom et leur e-mail, puis ajoutent la carte à Apple Wallet ou Google Wallet.

    Que contient la carte ?

    Votre logo, vos couleurs, le solde du client et un QR code personnel. Le solde se met à jour tout seul dans le Wallet.

    -
    Combien ça coûte, et suis-je engagé ?

    À partir de 19 € par mois et par magasin, sans engagement, avec 30 jours d’essai gratuit. Paiement mensuel ou annuel, factures automatiques.

    +
    Combien ça coûte, et suis-je engagé ?

    À partir de 19 € par mois et par magasin, sans engagement. Paiement mensuel ou annuel, factures automatiques.

    Où sont hébergées les données ?

    Dans l’Union européenne. Le client donne son consentement et peut demander la suppression de ses données à tout moment.

    Comment éviter les abus ?

    Un plafond par opération, un délai entre deux crédits, et chaque opération est tracée avec l’employé qui l’a faite.

    diff --git a/site/tarif/index.html b/site/tarif/index.html index 8443451..c5c3020 100644 --- a/site/tarif/index.html +++ b/site/tarif/index.html @@ -4,12 +4,12 @@ Tarif — MonEspacePro - + - + @@ -83,7 +83,7 @@

    Tarif

    Trois formules, aucun engagement.

    -

    Commencez simple, passez en Pro quand vous voulez faire revenir vos clients plus souvent. 30 jours d’essai gratuit, sans frais d’installation.

    +

    Commencez simple, passez en Pro quand vous voulez faire revenir vos clients plus souvent. Sans engagement, sans frais d’installation.

    @@ -95,7 +95,7 @@

    La carte de fidélité dans le Wallet de vos clients

    19 €/ mois

    Sans engagement, résiliable à tout moment

    -Essayer 30 jours gratuits +Choisir Essentiel
    • La carte à vos couleurs, dans Apple Wallet et Google Wallet
    • @@ -114,7 +114,7 @@

      Faites revenir vos clients

      39 €/ mois

      Sans engagement, résiliable à tout moment

      -Essayer 30 jours gratuits +Choisir Pro

      Tout Essentiel, plus :

      • Employés illimités
      • @@ -136,7 +136,7 @@

        Plusieurs magasins, une seule carte

        29 €/ mois / magasin

        Sans engagement, résiliable à tout moment

        -Essayer 30 jours gratuits +Choisir Réseau

        Tout Pro, plus :

        • Une carte commune à tous vos magasins Bientôt
        • @@ -258,7 +258,7 @@
    -
    Y a-t-il des frais d’installation ?

    Non. Vous payez seulement votre formule, à partir de 19 € par mois et par magasin, sans frais d’installation et sans commission. Et les 30 premiers jours sont gratuits.

    +
    Y a-t-il des frais d’installation ?

    Non. Vous payez seulement votre formule, à partir de 19 € par mois et par magasin, sans frais d’installation et sans commission.

    Puis-je arrêter quand je veux ?

    Oui. Il n’y a pas d’engagement : vous pouvez résilier à tout moment.

    Comment sont émises les factures ?

    Automatiquement, au format PDF, après chaque prélèvement (mensuel ou annuel). La TVA n’est pas applicable (art. 293 B du CGI).

    J’ai plusieurs magasins : que paie-je ?

    Chaque magasin a sa formule. À partir de 3 magasins, la formule Réseau revient à 29 € par mois et par magasin, avec toutes les fonctions Pro. Le simulateur ci-dessus calcule le total.