feat(billing): expose l'annulation programmée + bouton "Réactiver"
Quand l'user annule via le Customer Portal Stripe, la subscription reste
`active` jusqu'à la fin du cycle (cancel_at_period_end=true) — Stripe
n'envoie le `subscription.deleted` qu'à period_end. Avant ce commit, l'UI
affichait toujours "prochaine facture le 28 mai" comme avant l'annulation,
ce qui faisait croire à l'user qu'il allait re-payer.
Backend :
- Migration `cancel_at_period_end boolean DEFAULT false` sur orgs.
- `applySubscriptionToOrg` : lit le flag du Stripe Subscription et
persiste sur l'org.
- `handleSubscriptionDeleted` : reset le flag à false (cohérence DB).
- `OrgSubscriptionState` : nouveau champ `cancelAtPeriodEnd: boolean`.
- Endpoint `POST /api/v1/billing/reactivate` :
• Idempotent (si déjà actif → no-op + 200)
• Appelle `subscriptions.update(id, { cancel_at_period_end: false })`
• Persist le nouvel état sur l'org
Frontend :
- Hook `useReactivateSubscription` (mutation + invalidate billing query).
- `CurrentPlanStrip` :
• Détecte `isCancelling = plan !== 'free' && cancelAtPeriodEnd`
• Switch border/bg en mode rubis-deep + rubis-glow pour attirer l'œil
• Icône Clock à la place de Gem (visuel "compte à rebours")
• Badge "ANNULÉ" en uppercase
• Sous-titre : "Accès Pro jusqu'au DD/MM, puis retour automatique
au plan Free."
• Bouton primary "Réactiver" (RotateCcw icon) qui remplace "Gérer"
• Masque la progress bar Free (non pertinente)
- `SubscriptionState` type étendu avec `cancelAtPeriodEnd`.
- Test factory updated.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
parent
b1361de606
commit
cb87bbc8d1
@ -103,6 +103,44 @@ export default class BillingController {
|
||||
return response.json({ data: { url: session.url } })
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/v1/billing/reactivate — auth.
|
||||
*
|
||||
* Annule l'annulation programmée au period_end : set Stripe
|
||||
* `cancel_at_period_end: false` et persiste côté org. Pas de proration,
|
||||
* pas de paiement immédiat — la subscription continue son cycle normal.
|
||||
*/
|
||||
async reactivate({ auth, response }: HttpContext) {
|
||||
const organizationId = requireOrgId(auth)
|
||||
const org = await Organization.findOrFail(organizationId)
|
||||
|
||||
if (!org.stripeSubscriptionId) {
|
||||
throw new Exception('Aucune souscription active à réactiver', {
|
||||
status: 400,
|
||||
code: 'no_active_subscription',
|
||||
})
|
||||
}
|
||||
if (!org.cancelAtPeriodEnd) {
|
||||
// Idempotent : déjà actif, on renvoie OK sans toucher Stripe.
|
||||
return response.json({ data: { ok: true } })
|
||||
}
|
||||
|
||||
const stripe = getStripe()
|
||||
const updated = await stripe.subscriptions.update(org.stripeSubscriptionId, {
|
||||
cancel_at_period_end: false,
|
||||
})
|
||||
org.cancelAtPeriodEnd = !!updated.cancel_at_period_end // = false normalement
|
||||
org.subscriptionStatus = updated.status
|
||||
await org.save()
|
||||
|
||||
logger.info(
|
||||
{ orgId: org.id, subscriptionId: org.stripeSubscriptionId },
|
||||
'Subscription réactivée (cancel_at_period_end=false)'
|
||||
)
|
||||
|
||||
return response.json({ data: { ok: true } })
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/v1/billing/portal — auth.
|
||||
* Crée une session Stripe Customer Portal pour gérer abonnement, CB,
|
||||
@ -259,6 +297,7 @@ export default class BillingController {
|
||||
org.subscriptionStatus = 'canceled'
|
||||
org.billingCycle = null
|
||||
org.currentPeriodEnd = null
|
||||
org.cancelAtPeriodEnd = false
|
||||
await org.save()
|
||||
logger.info({ orgId: org.id }, 'Org redescendue en plan free (subscription deleted)')
|
||||
}
|
||||
@ -297,6 +336,9 @@ export default class BillingController {
|
||||
org.currentPeriodEnd = item.current_period_end
|
||||
? DateTime.fromSeconds(item.current_period_end)
|
||||
: null
|
||||
// L'user a-t-il programmé une annulation ? (via Customer Portal)
|
||||
// Reflété en UI pour qu'il sache que son accès s'éteint au period_end.
|
||||
org.cancelAtPeriodEnd = !!subscription.cancel_at_period_end
|
||||
await org.save()
|
||||
|
||||
logger.info(
|
||||
|
||||
@ -144,6 +144,13 @@ export type OrgSubscriptionState = {
|
||||
currentPeriodEnd: string | null
|
||||
/** True si l'org a un Stripe customer ID (= a déjà payé une fois). */
|
||||
hasStripeCustomer: boolean
|
||||
/**
|
||||
* True si l'user a annulé sa souscription côté Stripe et qu'elle s'éteindra
|
||||
* à `currentPeriodEnd`. Pendant cette fenêtre l'org reste sur son plan
|
||||
* payant (status `active`), mais l'UI affiche "annulé, accès jusqu'au DD/MM"
|
||||
* et propose un bouton "Réactiver".
|
||||
*/
|
||||
cancelAtPeriodEnd: boolean
|
||||
}
|
||||
|
||||
export async function getOrgSubscriptionState(
|
||||
@ -168,5 +175,6 @@ export async function getOrgSubscriptionState(
|
||||
: null,
|
||||
currentPeriodEnd: org.currentPeriodEnd?.toISO() ?? null,
|
||||
hasStripeCustomer: !!org.stripeCustomerId,
|
||||
cancelAtPeriodEnd: !!org.cancelAtPeriodEnd,
|
||||
}
|
||||
}
|
||||
|
||||
@ -0,0 +1,24 @@
|
||||
import { BaseSchema } from '@adonisjs/lucid/schema'
|
||||
|
||||
/**
|
||||
* `cancel_at_period_end` : Stripe permet à l'user d'annuler une souscription
|
||||
* sans coupure immédiate — le sub reste `active` jusqu'à `current_period_end`,
|
||||
* puis Stripe envoie `customer.subscription.deleted`. Pendant cette fenêtre on
|
||||
* doit afficher "annulé, accès jusqu'au DD/MM" côté UI au lieu de
|
||||
* "prochaine facture le DD/MM" — sinon l'user pense qu'il va re-payer.
|
||||
*/
|
||||
export default class extends BaseSchema {
|
||||
protected tableName = 'organizations'
|
||||
|
||||
async up() {
|
||||
this.schema.alterTable(this.tableName, (table) => {
|
||||
table.boolean('cancel_at_period_end').notNullable().defaultTo(false)
|
||||
})
|
||||
}
|
||||
|
||||
async down() {
|
||||
this.schema.alterTable(this.tableName, (table) => {
|
||||
table.dropColumn('cancel_at_period_end')
|
||||
})
|
||||
}
|
||||
}
|
||||
@ -218,10 +218,12 @@ export class InvoiceSchema extends BaseModel {
|
||||
}
|
||||
|
||||
export class OrganizationSchema extends BaseModel {
|
||||
static $columns = ['billingCycle', 'createdAt', 'currentPeriodEnd', 'demoMode', 'demoSpeedFactor', 'gracePeriodEndsAt', 'id', 'monthlyVolumeBucket', 'name', 'onboardingCompletedAt', 'plan', 'rubisCount', 'siret', 'stripeCustomerId', 'stripeSubscriptionId', 'subscriptionStatus', 'updatedAt', 'virtualNow'] as const
|
||||
static $columns = ['billingCycle', 'cancelAtPeriodEnd', 'createdAt', 'currentPeriodEnd', 'demoMode', 'demoSpeedFactor', 'gracePeriodEndsAt', 'id', 'monthlyVolumeBucket', 'name', 'onboardingCompletedAt', 'plan', 'rubisCount', 'siret', 'stripeCustomerId', 'stripeSubscriptionId', 'subscriptionStatus', 'updatedAt', 'virtualNow'] as const
|
||||
$columns = OrganizationSchema.$columns
|
||||
@column()
|
||||
declare billingCycle: string | null
|
||||
@column()
|
||||
declare cancelAtPeriodEnd: boolean
|
||||
@column.dateTime({ autoCreate: true })
|
||||
declare createdAt: DateTime
|
||||
@column.dateTime()
|
||||
|
||||
@ -185,6 +185,9 @@ router
|
||||
.post('checkout', [controllers.Billing, 'checkout'])
|
||||
.as('checkout')
|
||||
router.post('portal', [controllers.Billing, 'portal']).as('portal')
|
||||
router
|
||||
.post('reactivate', [controllers.Billing, 'reactivate'])
|
||||
.as('reactivate')
|
||||
})
|
||||
.prefix('billing')
|
||||
.as('billing')
|
||||
|
||||
@ -46,6 +46,7 @@ function fakeState(overrides: Partial<SubscriptionState> = {}): SubscriptionStat
|
||||
billingCycle: null,
|
||||
currentPeriodEnd: null,
|
||||
hasStripeCustomer: false,
|
||||
cancelAtPeriodEnd: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { api } from "@/lib/api";
|
||||
|
||||
/** Identique au type côté API (`OrgSubscriptionState`). */
|
||||
@ -21,6 +21,8 @@ export type SubscriptionState = {
|
||||
billingCycle: BillingCycle | null;
|
||||
currentPeriodEnd: string | null;
|
||||
hasStripeCustomer: boolean;
|
||||
/** L'user a annulé : sub reste active jusqu'à currentPeriodEnd puis Free. */
|
||||
cancelAtPeriodEnd: boolean;
|
||||
};
|
||||
|
||||
/** Lit l'état de l'abonnement courant. */
|
||||
@ -54,6 +56,20 @@ export function useOpenPortal() {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Réactive une souscription annulée (cancel_at_period_end=true → false).
|
||||
* Pas de paiement immédiat — le sub continue son cycle normal.
|
||||
*/
|
||||
export function useReactivateSubscription() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: () => api.post<{ ok: true }>("/api/v1/billing/reactivate"),
|
||||
onSuccess: () => {
|
||||
void qc.invalidateQueries({ queryKey: ["billing", "subscription"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* True si l'org est sur Free, hors grace period, et ≥ limit. Le SPA
|
||||
* l'utilise pour afficher un banner "limite atteinte" et bloquer
|
||||
|
||||
@ -1,10 +1,16 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { createFileRoute, Link } from "@tanstack/react-router";
|
||||
import { ArrowLeft, ArrowRight, CreditCard } from "lucide-react";
|
||||
import { ArrowLeft, ArrowRight, CreditCard, RotateCcw, Clock } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
import { z } from "zod";
|
||||
|
||||
import { useOpenPortal, useStartCheckout, useSubscription, type BillingCycle } from "@/lib/billing";
|
||||
import {
|
||||
useOpenPortal,
|
||||
useReactivateSubscription,
|
||||
useStartCheckout,
|
||||
useSubscription,
|
||||
type BillingCycle,
|
||||
} from "@/lib/billing";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { formatDate } from "@/lib/format";
|
||||
import { Gem } from "@/components/brand/Gem";
|
||||
@ -28,6 +34,7 @@ function AbonnementPage() {
|
||||
const { data: sub, isPending } = useSubscription();
|
||||
const checkout = useStartCheckout();
|
||||
const portal = useOpenPortal();
|
||||
const reactivate = useReactivateSubscription();
|
||||
const [cycle, setCycle] = useState<BillingCycle>("monthly");
|
||||
|
||||
useEffect(() => {
|
||||
@ -59,6 +66,13 @@ function AbonnementPage() {
|
||||
});
|
||||
};
|
||||
|
||||
const onReactivate = () => {
|
||||
reactivate.mutate(undefined, {
|
||||
onSuccess: () => toast.success("Souscription réactivée — tout repart comme avant."),
|
||||
onError: () => toast.error("Impossible de réactiver. Réessaye."),
|
||||
});
|
||||
};
|
||||
|
||||
const currentPlan = sub?.plan;
|
||||
|
||||
return (
|
||||
@ -90,6 +104,8 @@ function AbonnementPage() {
|
||||
state={sub}
|
||||
onOpenPortal={onOpenPortal}
|
||||
isOpeningPortal={portal.isPending}
|
||||
onReactivate={onReactivate}
|
||||
isReactivating={reactivate.isPending}
|
||||
/>
|
||||
)}
|
||||
|
||||
@ -136,25 +152,44 @@ function CurrentPlanStrip({
|
||||
state,
|
||||
onOpenPortal,
|
||||
isOpeningPortal,
|
||||
onReactivate,
|
||||
isReactivating,
|
||||
}: {
|
||||
state: ReturnType<typeof useSubscription>["data"] & {};
|
||||
onOpenPortal: () => void;
|
||||
isOpeningPortal: boolean;
|
||||
onReactivate: () => void;
|
||||
isReactivating: boolean;
|
||||
}) {
|
||||
const { plan, activeInvoicesCount, caps, inGracePeriod, gracePeriodEndsAt } = state;
|
||||
const { plan, activeInvoicesCount, caps, inGracePeriod, gracePeriodEndsAt, cancelAtPeriodEnd } =
|
||||
state;
|
||||
const limit = caps.activeInvoicesLimit;
|
||||
const isLimited = plan === "free" && limit !== null;
|
||||
const limitReached =
|
||||
isLimited && limit !== null && !inGracePeriod && activeInvoicesCount >= limit;
|
||||
const isCancelling = plan !== "free" && cancelAtPeriodEnd;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center gap-4 rounded-card border bg-white px-5 py-4",
|
||||
"border-line",
|
||||
"flex items-center gap-4 rounded-card border px-5 py-4",
|
||||
// Border + bg switchent en mode "annulation programmée" pour
|
||||
// attirer l'œil — l'user doit voir tout de suite que son accès
|
||||
// s'éteint bientôt.
|
||||
isCancelling
|
||||
? "border-rubis-deep bg-rubis-glow/30"
|
||||
: "border-line bg-white",
|
||||
)}
|
||||
>
|
||||
<Gem size={22} className="shrink-0" />
|
||||
{isCancelling ? (
|
||||
<Clock
|
||||
size={22}
|
||||
className="shrink-0 text-rubis-deep"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
) : (
|
||||
<Gem size={22} className="shrink-0" />
|
||||
)}
|
||||
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="font-display text-[15px] font-bold text-ink leading-tight">
|
||||
@ -162,49 +197,67 @@ function CurrentPlanStrip({
|
||||
{plan !== "free" && (
|
||||
<span className="ml-1 text-rubis">{plan === "pro" ? " Pro" : " Business"}</span>
|
||||
)}
|
||||
{state.subscriptionStatus && state.subscriptionStatus !== "active" && (
|
||||
{isCancelling && (
|
||||
<span className="ml-2 text-[10.5px] font-bold text-rubis-deep uppercase tracking-[0.12em]">
|
||||
· Annulé
|
||||
</span>
|
||||
)}
|
||||
{!isCancelling && state.subscriptionStatus && state.subscriptionStatus !== "active" && (
|
||||
<span className="ml-2 text-[10.5px] font-medium text-rubis-deep uppercase tracking-[0.1em]">
|
||||
· {state.subscriptionStatus}
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
<p className="mt-0.5 text-[12px] text-ink-3 leading-tight">
|
||||
{plan === "free" && inGracePeriod && gracePeriodEndsAt && (
|
||||
{/* Cas prioritaire : annulation programmée → on insiste là-dessus */}
|
||||
{isCancelling && state.currentPeriodEnd ? (
|
||||
<>
|
||||
Période illimitée jusqu'au{" "}
|
||||
<strong className="text-ink-2 font-medium">
|
||||
{formatDate(gracePeriodEndsAt)}
|
||||
</strong>
|
||||
</>
|
||||
)}
|
||||
{plan === "free" && !inGracePeriod && limit !== null && (
|
||||
<>
|
||||
<strong
|
||||
className={cn(
|
||||
"tabular-nums font-medium",
|
||||
limitReached ? "text-rubis-deep" : "text-ink-2",
|
||||
)}
|
||||
>
|
||||
{activeInvoicesCount} / {limit}
|
||||
</strong>{" "}
|
||||
factures actives
|
||||
{limitReached && " — limite atteinte"}
|
||||
</>
|
||||
)}
|
||||
{plan !== "free" && state.currentPeriodEnd && (
|
||||
<>
|
||||
Renouvellement le{" "}
|
||||
<strong className="text-ink-2 font-medium">
|
||||
Accès Pro jusqu'au{" "}
|
||||
<strong className="text-rubis-deep font-semibold">
|
||||
{formatDate(state.currentPeriodEnd)}
|
||||
</strong>
|
||||
{state.billingCycle === "yearly" ? " (annuel)" : " (mensuel)"}
|
||||
, puis retour automatique au plan Free.
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{plan === "free" && inGracePeriod && gracePeriodEndsAt && (
|
||||
<>
|
||||
Période illimitée jusqu'au{" "}
|
||||
<strong className="text-ink-2 font-medium">
|
||||
{formatDate(gracePeriodEndsAt)}
|
||||
</strong>
|
||||
</>
|
||||
)}
|
||||
{plan === "free" && !inGracePeriod && limit !== null && (
|
||||
<>
|
||||
<strong
|
||||
className={cn(
|
||||
"tabular-nums font-medium",
|
||||
limitReached ? "text-rubis-deep" : "text-ink-2",
|
||||
)}
|
||||
>
|
||||
{activeInvoicesCount} / {limit}
|
||||
</strong>{" "}
|
||||
factures actives
|
||||
{limitReached && " — limite atteinte"}
|
||||
</>
|
||||
)}
|
||||
{plan !== "free" && state.currentPeriodEnd && (
|
||||
<>
|
||||
Renouvellement le{" "}
|
||||
<strong className="text-ink-2 font-medium">
|
||||
{formatDate(state.currentPeriodEnd)}
|
||||
</strong>
|
||||
{state.billingCycle === "yearly" ? " (annuel)" : " (mensuel)"}
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Mini progress bar mobile-OK pour Free */}
|
||||
{isLimited && limit !== null && !inGracePeriod && (
|
||||
{/* Mini progress bar — uniquement Free post-grace, masqué si cancelling */}
|
||||
{isLimited && limit !== null && !inGracePeriod && !isCancelling && (
|
||||
<div className="hidden sm:block w-32 shrink-0">
|
||||
<div className="h-1 w-full rounded-full bg-cream-2 overflow-hidden">
|
||||
<div
|
||||
@ -220,15 +273,28 @@ function CurrentPlanStrip({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{state.hasStripeCustomer && (
|
||||
{/* Actions : Réactiver si annulé, sinon Gérer */}
|
||||
{isCancelling ? (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={onOpenPortal}
|
||||
loading={isOpeningPortal}
|
||||
variant="primary"
|
||||
onClick={onReactivate}
|
||||
loading={isReactivating}
|
||||
className="shrink-0"
|
||||
>
|
||||
<CreditCard size={13} aria-hidden="true" /> Gérer
|
||||
<RotateCcw size={13} aria-hidden="true" /> Réactiver
|
||||
</Button>
|
||||
) : (
|
||||
state.hasStripeCustomer && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={onOpenPortal}
|
||||
loading={isOpeningPortal}
|
||||
>
|
||||
<CreditCard size={13} aria-hidden="true" /> Gérer
|
||||
</Button>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user