Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
136 changes: 136 additions & 0 deletions app/mijn-ribba/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
'use client';

// Mijn Ribba — permanent klantportaal van Ribba (S4-ontwerp). Bewust
// minimaal: Ribba authenticeert, en "Abonnement & facturatie" opent per
// bezoek een VERSE Stripe Customer Portal-sessie via de Supabase edge
// function stripe-portal-session (B5: alle Stripe-secrets blijven in de
// projectbrede Supabase-set; hier alleen de user-JWT). Stripe blijft één
// onderdeel achter deze pagina; support en licenties blijven bij Ribba.

import { useEffect, useRef, useState } from 'react';
import { useRouter } from 'next/navigation';
import { createBrowserClient } from '@supabase/ssr';
import RibbaLogo from '../components/RibbaLogo';
import { createPortalGate, openStripePortal } from '@/lib/stripe-upgrade';

const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!;

function getSupabaseBrowser() {
return createBrowserClient(supabaseUrl, supabaseAnonKey);
}

export default function MijnRibbaPage() {
const router = useRouter();
const [loading, setLoading] = useState(true);
const [schoolId, setSchoolId] = useState<string | null>(null);
const [schoolName, setSchoolName] = useState<string | null>(null);
const [userEmail, setUserEmail] = useState<string | null>(null);
const [portalBusy, setPortalBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
// Synchrone request-level dubbelklikblokkade (correctieronde 21 jul):
// portalBusy/disabled is UI-bescherming, maar twee click-events kunnen
// dezelfde render-state zien; deze ref-gate niet.
const portalGateRef = useRef(createPortalGate());

useEffect(() => {
const supabase = getSupabaseBrowser();
supabase.auth.getSession().then(async ({ data }) => {
if (!data.session) {
router.replace('/login');
return;
}
setUserEmail(data.session.user.email ?? null);
try {
const meRes = await fetch('/api/me', {
headers: { Authorization: `Bearer ${data.session.access_token}` },
});
if (meRes.ok) {
const me = await meRes.json();
if (me.school_id) setSchoolId(me.school_id);
if (me.school_name) setSchoolName(me.school_name);
}
} catch {
// foutafhandeling hieronder via ontbrekende schoolId
} finally {
setLoading(false);
}
});
Comment on lines +38 to +58

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

getSession() rejection leaves the page stuck on "Laden…".

The .then(...) chain has no rejection handler, and setLoading(false) runs only inside the inner try/finally. If getSession() itself rejects (network/session error), loading never clears and the user sees an indefinite spinner. Add a .catch that clears loading (and surfaces an error).

🛡️ Suggested guard
-    supabase.auth.getSession().then(async ({ data }) => {
+    supabase.auth.getSession().then(async ({ data }) => {
       if (!data.session) {
         router.replace('/login');
         return;
       }
       setUserEmail(data.session.user.email ?? null);
       try {
         const meRes = await fetch('/api/me', {
           headers: { Authorization: `Bearer ${data.session.access_token}` },
         });
         if (meRes.ok) {
           const me = await meRes.json();
           if (me.school_id) setSchoolId(me.school_id);
           if (me.school_name) setSchoolName(me.school_name);
         }
       } catch {
         // foutafhandeling hieronder via ontbrekende schoolId
       } finally {
         setLoading(false);
       }
-    });
+    }).catch(() => setLoading(false));
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
supabase.auth.getSession().then(async ({ data }) => {
if (!data.session) {
router.replace('/login');
return;
}
setUserEmail(data.session.user.email ?? null);
try {
const meRes = await fetch('/api/me', {
headers: { Authorization: `Bearer ${data.session.access_token}` },
});
if (meRes.ok) {
const me = await meRes.json();
if (me.school_id) setSchoolId(me.school_id);
if (me.school_name) setSchoolName(me.school_name);
}
} catch {
// foutafhandeling hieronder via ontbrekende schoolId
} finally {
setLoading(false);
}
});
supabase.auth.getSession().then(async ({ data }) => {
if (!data.session) {
router.replace('/login');
return;
}
setUserEmail(data.session.user.email ?? null);
try {
const meRes = await fetch('/api/me', {
headers: { Authorization: `Bearer ${data.session.access_token}` },
});
if (meRes.ok) {
const me = await meRes.json();
if (me.school_id) setSchoolId(me.school_id);
if (me.school_name) setSchoolName(me.school_name);
}
} catch {
// foutafhandeling hieronder via ontbrekende schoolId
} finally {
setLoading(false);
}
}).catch(() => setLoading(false));
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@app/mijn-ribba/page.tsx` around lines 32 - 52, Update the getSession promise
chain in the page component to add a rejection handler that calls
setLoading(false) and surfaces the authentication/session error using the
component’s existing error-handling mechanism. Keep the inner try/finally
behavior unchanged for successful session retrieval and API failures.

}, [router]);

const openPortal = async () => {
if (!schoolId) return;
// Lock vóór getSession/fetch; een tweede aanroep stopt hier synchroon.
if (!portalGateRef.current.begin()) return;
setPortalBusy(true);
setError(null);

try {
// Refresh-veilige token-fetch (zelfde patroon als /upgrade).
const supabase = getSupabaseBrowser();
const { data: sessionData } = await supabase.auth.getSession();
const token = sessionData.session?.access_token;
if (!token) {
router.replace('/login');
return;
}

const result = await openStripePortal({
supabaseUrl,
accessToken: token,
schoolId,
});
if (!result.ok) {
setError(result.error);
setPortalBusy(false);
return;
}
// Succes: portalBusy blijft staan tot de navigatie de pagina verlaat;
// de gate komt in finally vrij, dus een bewuste nieuwe sessie kan.
window.location.href = result.url;
} finally {
portalGateRef.current.end();
}
};

return (
<main className="page-wrapper">
<div className="card">
<div className="logo"><RibbaLogo height={36} /></div>
<h1>Mijn Ribba</h1>

{loading ? (
<p className="subtitle">Laden…</p>
) : (
<>
<p className="subtitle">
{schoolName ? <strong>{schoolName}</strong> : 'Je rijschool'}
{userEmail ? <> · ingelogd als {userEmail}</> : null}
</p>

{error && <div className="checkout-error">{error}</div>}

<button
type="button"
className="btn-primary"
onClick={openPortal}
disabled={!schoolId || portalBusy}
>
{portalBusy ? 'Bezig…' : 'Abonnement & facturatie beheren'}
</button>
<p className="footer-text" style={{ marginTop: 12 }}>
Facturen downloaden, betaalmethode wijzigen of opzeggen — veilig via Stripe.
</p>

<div className="divider" />

<p className="footer-text">
Abonnement kiezen of wijzigen? <a href="/upgrade">Bekijk de plannen</a>.<br />

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Use next/link for internal navigation to /upgrade.

The raw <a href="/upgrade"> triggers a full page reload instead of client-side navigation.

♻️ Suggested change
-import { useRouter } from 'next/navigation';
+import { useRouter } from 'next/navigation';
+import Link from 'next/link';
-              Abonnement kiezen of wijzigen? <a href="/upgrade">Bekijk de plannen</a>.<br />
+              Abonnement kiezen of wijzigen? <Link href="/upgrade">Bekijk de plannen</Link>.<br />
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
Abonnement kiezen of wijzigen? <a href="/upgrade">Bekijk de plannen</a>.<br />
Abonnement kiezen of wijzigen? <Link href="/upgrade">Bekijk de plannen</Link>.<br />
🧰 Tools
🪛 ESLint

[error] 123-123: Do not use an <a> element to navigate to /upgrade/. Use <Link /> from next/link instead. See: https://nextjs.org/docs/messages/no-html-link-for-pages

(@next/next/no-html-link-for-pages)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@app/mijn-ribba/page.tsx` at line 123, Replace the raw anchor for the internal
/upgrade navigation in the page component with Next.js’s Link component,
importing next/link as needed while preserving the existing link text and
surrounding markup.

Source: Linters/SAST tools

Vragen? <a href="mailto:hallo@ribba.app">hallo@ribba.app</a>
</p>
</>
)}
</div>
</main>
);
}
77 changes: 54 additions & 23 deletions app/upgrade/page.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
'use client';

import { Suspense, useState, useEffect } from 'react';
import { Suspense, useState, useEffect, useRef } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import { createBrowserClient } from '@supabase/ssr';
import RibbaLogo from '../components/RibbaLogo';
import { BASIC_MAX_STUDENTS, BASIC_MAX_INSTRUCTORS } from '@/lib/plan-limits';
import { getPlanPricing, formatCentsForDisplay } from '@/lib/plan-pricing';
import {
createCheckoutController,
startStripeCheckout,
type UpgradePlan,
} from '@/lib/stripe-upgrade';

const basicPricing = getPlanPricing('basic');
const premiumPricing = getPlanPricing('premium');
Expand Down Expand Up @@ -154,12 +159,38 @@ function UpgradeContent() {
router.replace('/login');
};

const handleCheckout = async (plan: 'basic' | 'premium') => {
// Stripe-checkout-bedrading: één attempt_id per bewuste poging, hergebruik
// bij een retry van hetzelfde plan, en dubbelklik-blokkade in de controller
// (naast de disabled-knop). De billinglogica leeft in de edge function.
const checkoutControllerRef = useRef(createCheckoutController());

// bfcache-herstel (correctieronde 21 jul): na een geslaagde checkout blijft
// de lock bewust staan tot de redirect naar Stripe. Keert de gebruiker via
// browser-back terug, dan herstelt Safari/Firefox/Chrome de pagina uit de
// back/forward-cache mét die actieve lock — zonder reset zouden de
// checkoutknoppen permanent dood zijn. pageshow met event.persisted=true is
// dé bfcache-detectie; bij een normale (verse) load is persisted false en
// gebeurt er niets. attempt_id-semantiek blijft onaangetast.
useEffect(() => {
const onPageShow = (event: PageTransitionEvent) => {
if (event.persisted) {
checkoutControllerRef.current.reset();
setLoading(null);
}
};
window.addEventListener('pageshow', onPageShow);
return () => window.removeEventListener('pageshow', onPageShow);
}, []);

const handleCheckout = async (plan: UpgradePlan) => {
if (!schoolId) {
setError('Geen rijschool gekoppeld. Open deze pagina vanuit de Ribba app.');
return;
}

const attemptId = checkoutControllerRef.current.begin(plan);
if (attemptId === null) return; // er loopt al een poging (dubbelklik)

setLoading(plan);
setError(null);

Expand All @@ -174,29 +205,25 @@ function UpgradeContent() {
}
setAccessToken(token);

try {
const res = await fetch('/api/checkout', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({ school_id: schoolId, plan }),
});

const data = await res.json();

if (!res.ok) {
setError(data.error || 'Er ging iets mis.');
setLoading(null);
return;
}
const result = await startStripeCheckout({
supabaseUrl,
accessToken: token,
schoolId,
plan,
attemptId,
});

window.location.href = data.checkoutUrl;
} catch {
setError('Kan geen verbinding maken. Probeer het opnieuw.');
if (!result.ok) {
// 'network' hervat dezelfde poging bij een nieuwe klik; 'definitive'
// sluit de poging af zodat de volgende klik een nieuwe attempt_id
// krijgt (Stripe cachet ook fouten op een idempotency-key).
checkoutControllerRef.current.fail(plan, result.kind);
setError(result.error);
setLoading(null);
return;
}

window.location.href = result.checkoutUrl;
};

const handleCancel = () => {
Expand Down Expand Up @@ -562,7 +589,11 @@ function UpgradeContent() {
<div style={{ textAlign: 'center', marginTop: 48 }}>
<p style={{ fontSize: 14, color: '#78716C', lineHeight: 1.8 }}>
Annuleer wanneer je wilt. Geen verplichtingen.<br />
Alle prijzen zijn exclusief 21% btw; de incasso via Mollie is inclusief btw.
Alle prijzen zijn exclusief 21% btw; de incasso is inclusief btw.
</p>
<p style={{ fontSize: 14, color: '#78716C', marginTop: 8 }}>
Al een abonnement? Beheer facturen, betaalmethode en opzegging via{' '}
<a href="/mijn-ribba" style={{ color: '#2563EB', fontWeight: 600 }}>Mijn Ribba</a>.
</p>
<div className="divider" />
<p style={{ fontSize: 13, color: '#A8A29E' }}>
Expand Down
12 changes: 6 additions & 6 deletions app/upgrade/success/page.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
'use client';

import { Suspense, useEffect } from 'react';
import { useSearchParams } from 'next/navigation';
import RibbaLogo from '../../components/RibbaLogo';
import { APP_STORE_URL } from '@/lib/app-links';

function SuccessContent() {
const searchParams = useSearchParams();
const plan = searchParams.get('plan') || 'premium';
const planLabel = plan === 'premium' ? 'Premium' : 'Basic';
// Bewust plan-neutraal (besluit 21 jul 2026): een losse ?plan=-parameter
// of client-side opslag mag niet zelfstandig bepalen wat als gekocht wordt
// gepresenteerd. Pas wanneer er een betrouwbare server-side bron is
// (Checkout Session/Subscription), mag hier weer een planlabel staan.

useEffect(() => {
// Auto-open app after 2 seconds
Expand Down Expand Up @@ -38,9 +38,9 @@ function SuccessContent() {

<p className="pill pill-green">Betaling geslaagd</p>

<h1>Welkom bij Ribba {planLabel}!</h1>
<h1>Welkom bij Ribba!</h1>
<p className="subtitle">
Je abonnement is geactiveerd. Alle {planLabel}-functies zijn nu beschikbaar in de app.
Je abonnement is geactiveerd. Alle functies van je gekozen plan zijn nu beschikbaar in de app.
</p>

<a href="ribba://upgrade-success" className="btn-primary">
Expand Down
Loading