diff --git a/external_types/UserServiceAPI.yaml b/external_types/UserServiceAPI.yaml
index 73a73e6a..80751b6e 100644
--- a/external_types/UserServiceAPI.yaml
+++ b/external_types/UserServiceAPI.yaml
@@ -101,6 +101,36 @@ paths:
"500":
description: Internal server error.
+ /v1/user/announcements/sync:
+ post:
+ summary: Refresh the current user's API announcements opt-in from Brevo
+ description: |
+ Reads the user's Brevo contact and turns their `api.announcements` subscription
+ off when they unsubscribed from a Brevo email, then returns the profile. It never
+ turns announcements on and never writes to Brevo. The daily reconcile task does the
+ same for every user; this lets the website show the change at once, e.g. after the
+ Brevo unsubscribe redirect. Makes one Brevo call, only when the subscription is on.
+ operationId: syncUserAnnouncements
+ tags:
+ - "users"
+ security:
+ - Authentication: []
+ responses:
+ "200":
+ description: The user's profile after the refresh.
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/UserProfile"
+ "401":
+ description: Unauthorized — missing or invalid token.
+ "403":
+ description: Forbidden — guest users have no profile.
+ "404":
+ description: User not found.
+ "502":
+ description: Brevo could not be reached or returned an error.
+
/v1/notifications:
get:
summary: List available notification types
@@ -349,8 +379,8 @@ paths:
Behaviour depends on the notification type:
- **`api.announcements`** — never deleted; the subscription is *disabled*
(`active=false`), the contact is removed from the Brevo announcements
- list, and `app_user.is_registered_to_receive_api_announcements` is
- cleared. Kept idempotent so a repeated click still succeeds.
+ list, and the user's `is_registered_to_receive_api_announcements`
+ therefore reads `false`. Kept idempotent so a repeated click still succeeds.
- **all other types** (e.g. `feed.url_updated`) — the subscription row is
hard-deleted; a second call therefore returns `404`.
@@ -358,8 +388,7 @@ paths:
(Brevo) cannot be reached while updating an announcements subscription.
The `id` embedded in an email is the subscription's own UUID
- (`notification_subscription.id`) — mirrored onto the Brevo contact as the
- `MDB_SUBSCRIPTION_ID` attribute — **not** the notification-type string
+ (`notification_subscription.id`) — **not** the notification-type string
(`api.announcements`), which is shared by all recipients and is not a
valid subscription ID.
@@ -500,8 +529,8 @@ components:
description: >-
Unique subscription ID (UUID v4). This is the **capability token** used
by the public `/v1/subscriptions/{id}` endpoints and by email
- unsubscribe links; for `api.announcements` it is mirrored onto the
- Brevo contact as the `MDB_SUBSCRIPTION_ID` attribute.
+ unsubscribe links. `api.announcements` emails are Brevo campaigns and
+ use Brevo's own unsubscribe link instead.
user_id:
type: string
description: The ID of the subscribed user.
diff --git a/messages/en.json b/messages/en.json
index d6ff8cbf..bda1cda1 100644
--- a/messages/en.json
+++ b/messages/en.json
@@ -162,7 +162,10 @@
"notFoundDescription": "This unsubscribe link is invalid, or you've already unsubscribed.",
"loadFailedDescription": "We couldn't load this subscription. Please try again in a moment.",
"unsubscribeFailed": "Something went wrong and you're still subscribed. Please try again.",
- "tryAgain": "Try again"
+ "tryAgain": "Try again",
+ "brevoUnsubscribedTitle": "You've been unsubscribed",
+ "brevoUnsubscribedDescription": "You'll no longer receive Mobility Database API announcements. Your account can take up to 24 hours to show this change.",
+ "signInToManage": "Sign in to manage other subscriptions"
},
"resetPassword": {
"verifyingTitle": "Checking your link",
@@ -692,6 +695,7 @@
"personalInformationSubtitle": "Your account details and contact information",
"saveSuccess": "Account changes were successful",
"saveError": "Failed to save account changes. Please try again.",
+ "announcementsSyncFailed": "We couldn't refresh your API announcements preference. If you just unsubscribed from an email, it can take up to 24 hours to show here.",
"edit": "Edit",
"save": "Save",
"cancel": "Cancel",
diff --git a/messages/fr.json b/messages/fr.json
index 411d8ce8..8f01e70a 100644
--- a/messages/fr.json
+++ b/messages/fr.json
@@ -162,7 +162,10 @@
"notFoundDescription": "Ce lien de désabonnement n'est pas valide, ou vous êtes déjà désabonné.",
"loadFailedDescription": "Nous n'avons pas pu charger cet abonnement. Veuillez réessayer dans un instant.",
"unsubscribeFailed": "Une erreur s'est produite et vous êtes toujours abonné. Veuillez réessayer.",
- "tryAgain": "Réessayer"
+ "tryAgain": "Réessayer",
+ "brevoUnsubscribedTitle": "Vous êtes désabonné",
+ "brevoUnsubscribedDescription": "Vous ne recevrez plus les annonces de l'API de la Mobility Database. La mise à jour de votre compte peut prendre jusqu'à 24 heures.",
+ "signInToManage": "Se connecter pour gérer les autres abonnements"
},
"resetPassword": {
"verifyingTitle": "Vérification de votre lien",
@@ -692,6 +695,7 @@
"personalInformationSubtitle": "Vos informations de compte et de contact",
"saveSuccess": "Les modifications du compte ont été effectuées avec succès",
"saveError": "Échec de l'enregistrement des modifications du compte. Veuillez réessayer.",
+ "announcementsSyncFailed": "Nous n'avons pas pu actualiser votre préférence pour les annonces de l'API. Si vous venez de vous désabonner depuis un courriel, l'affichage peut prendre jusqu'à 24 heures.",
"edit": "Modifier",
"save": "Enregistrer",
"cancel": "Annuler",
diff --git a/src/app/[locale]/account/AccountGeneral.tsx b/src/app/[locale]/account/AccountGeneral.tsx
index ea469f56..ddd74c3f 100644
--- a/src/app/[locale]/account/AccountGeneral.tsx
+++ b/src/app/[locale]/account/AccountGeneral.tsx
@@ -1,6 +1,7 @@
'use client';
import * as React from 'react';
+import { useSearchParams } from 'next/navigation';
import { useRouter } from '../../../i18n/navigation';
import {
Alert,
@@ -24,7 +25,11 @@ import { AccountSectionContainer } from './AccountSectionContainer';
import {
saveUserProfile,
saveUserProfileReset,
+ setApiAnnouncementsOptIn,
} from '../../store/profile-reducer';
+import { syncAnnouncementsFromBrevo } from '../../services/profile-service';
+import { ACCOUNT_TARGET } from '../../constants/Navigation';
+import { shouldSyncAnnouncements } from './lib/announcementsSync';
export default function AccountGeneral(): React.ReactElement {
const t = useTranslations('account');
@@ -34,6 +39,11 @@ export default function AccountGeneral(): React.ReactElement {
const router = useRouter();
const signedInWithProvider = useSelector(selectSignedInWithProvider);
const saveStatus = useSelector(selectSaveUserProfileStatus);
+ const searchParams = useSearchParams();
+ const syncRequested = shouldSyncAnnouncements(searchParams);
+ const [announcementsSync, setAnnouncementsSync] = React.useState<
+ 'idle' | 'syncing' | 'failed'
+ >(syncRequested ? 'syncing' : 'idle');
const [isEditing, setIsEditing] = React.useState(false);
const [draftFullName, setDraftFullName] = React.useState('');
@@ -73,6 +83,28 @@ export default function AccountGeneral(): React.ReactElement {
dispatch(saveUserProfileReset());
}, [dispatch]);
+ // After a Brevo unsubscribe the stored opt-in can still read "subscribed"
+ // until the daily reconcile runs, and saving the form with it would
+ // re-subscribe the user. Refresh it from Brevo first, then drop the param so
+ // a reload doesn't call Brevo again. On failure the stored value is kept.
+ React.useEffect(() => {
+ if (!syncRequested) {
+ return;
+ }
+ setAnnouncementsSync('syncing');
+ syncAnnouncementsFromBrevo()
+ .then((isRegistered) => {
+ dispatch(setApiAnnouncementsOptIn(isRegistered));
+ setAnnouncementsSync('idle');
+ })
+ .catch(() => {
+ setAnnouncementsSync('failed');
+ })
+ .finally(() => {
+ router.replace(ACCOUNT_TARGET);
+ });
+ }, [syncRequested]);
+
React.useEffect(() => {
if (saveStatus === 'success') {
setIsEditing(false);
@@ -81,6 +113,7 @@ export default function AccountGeneral(): React.ReactElement {
// Reference is due to dispatch save status acting faster than the exit animation of the alert, causing a flash of the wrong alert severity. With this reference, the severity will be consistent during the whole display of the alert.
const isSaving = saveStatus === 'loading';
+ const isSyncing = announcementsSync === 'syncing';
const alertSeverity = React.useRef<'success' | 'error'>('success');
if (saveStatus === 'success') alertSeverity.current = 'success';
if (saveStatus === 'fail') alertSeverity.current = 'error';
@@ -110,7 +143,7 @@ export default function AccountGeneral(): React.ReactElement {
@@ -132,7 +165,12 @@ export default function AccountGeneral(): React.ReactElement {
) : (
-
diff --git a/src/app/[locale]/account/lib/announcementsSync.spec.ts b/src/app/[locale]/account/lib/announcementsSync.spec.ts
new file mode 100644
index 00000000..b45bdf44
--- /dev/null
+++ b/src/app/[locale]/account/lib/announcementsSync.spec.ts
@@ -0,0 +1,28 @@
+import {
+ ACCOUNT_ANNOUNCEMENTS_SYNC_TARGET,
+ shouldSyncAnnouncements,
+} from './announcementsSync';
+
+describe('shouldSyncAnnouncements', () => {
+ it('syncs only for sync=announcements', () => {
+ expect(
+ shouldSyncAnnouncements(new URLSearchParams('sync=announcements')),
+ ).toBe(true);
+ expect(shouldSyncAnnouncements(new URLSearchParams('sync=other'))).toBe(
+ false,
+ );
+ expect(shouldSyncAnnouncements(new URLSearchParams(''))).toBe(false);
+ expect(shouldSyncAnnouncements(null)).toBe(false);
+ });
+
+ it('builds a target the sign-in redirect accepts', () => {
+ expect(ACCOUNT_ANNOUNCEMENTS_SYNC_TARGET).toBe(
+ '/account?sync=announcements',
+ );
+ expect(
+ shouldSyncAnnouncements(
+ new URLSearchParams(ACCOUNT_ANNOUNCEMENTS_SYNC_TARGET.split('?')[1]),
+ ),
+ ).toBe(true);
+ });
+});
diff --git a/src/app/[locale]/account/lib/announcementsSync.ts b/src/app/[locale]/account/lib/announcementsSync.ts
new file mode 100644
index 00000000..708dbde0
--- /dev/null
+++ b/src/app/[locale]/account/lib/announcementsSync.ts
@@ -0,0 +1,18 @@
+import { ACCOUNT_TARGET } from '../../../constants/Navigation';
+
+/**
+ * `/account?sync=announcements` asks the account page to refresh the API
+ * announcements opt-in from Brevo before showing it. Brevo's unsubscribe
+ * redirect sends users here (through sign-in when needed), since the daily
+ * reconcile may not have turned the subscription off yet.
+ */
+export const ANNOUNCEMENTS_SYNC_PARAM = 'sync';
+export const ANNOUNCEMENTS_SYNC_VALUE = 'announcements';
+
+export const ACCOUNT_ANNOUNCEMENTS_SYNC_TARGET = `${ACCOUNT_TARGET}?${ANNOUNCEMENTS_SYNC_PARAM}=${ANNOUNCEMENTS_SYNC_VALUE}`;
+
+export function shouldSyncAnnouncements(
+ params: Pick | null,
+): boolean {
+ return params?.get(ANNOUNCEMENTS_SYNC_PARAM) === ANNOUNCEMENTS_SYNC_VALUE;
+}
diff --git a/src/app/[locale]/notifications/unsubscribe/UnsubscribeContent.tsx b/src/app/[locale]/notifications/unsubscribe/UnsubscribeContent.tsx
index 69c2ca4c..2256f7b8 100644
--- a/src/app/[locale]/notifications/unsubscribe/UnsubscribeContent.tsx
+++ b/src/app/[locale]/notifications/unsubscribe/UnsubscribeContent.tsx
@@ -23,6 +23,7 @@ import {
ACCOUNT_NOTIFICATIONS_TARGET,
SIGN_IN_TARGET,
} from '../../../constants/Navigation';
+import { ACCOUNT_ANNOUNCEMENTS_SYNC_TARGET } from '../../account/lib/announcementsSync';
import {
getSubscriptionById,
unsubscribeBySubscriptionId,
@@ -80,6 +81,7 @@ export default function UnsubscribeContent(): React.ReactElement {
const lookup = toSubscriptionLookup({
subscriptionId,
+ idMissing: idParam === null,
data,
error,
authFailed: !isAuthReady && anonymousLoginError,
@@ -95,12 +97,16 @@ export default function UnsubscribeContent(): React.ReactElement {
}
// Signed-out (or not yet registered) users go through sign-in, which sends
- // them on to the notifications page once their account is ready.
+ // them on to their account once it's ready. After a Brevo unsubscribe (no
+ // id) that's the account page, which refreshes the announcements opt-in
+ // from Brevo before showing it.
+ const manageTarget =
+ lookup.status === 'noId'
+ ? ACCOUNT_ANNOUNCEMENTS_SYNC_TARGET
+ : ACCOUNT_NOTIFICATIONS_TARGET;
const manageHref = isRegistered
- ? ACCOUNT_NOTIFICATIONS_TARGET
- : `${SIGN_IN_TARGET}?redirect_to=${encodeURIComponent(
- ACCOUNT_NOTIFICATIONS_TARGET,
- )}`;
+ ? manageTarget
+ : `${SIGN_IN_TARGET}?redirect_to=${encodeURIComponent(manageTarget)}`;
// The subscription the buttons act on, while the user can still act.
const actionable =
@@ -227,11 +233,13 @@ export default function UnsubscribeContent(): React.ReactElement {
- {t('manageNotifications')}
+ {lookup.status === 'noId' && !isRegistered
+ ? t('signInToManage')
+ : t('manageNotifications')}
)}
diff --git a/src/app/[locale]/notifications/unsubscribe/lib/unsubscribe.spec.ts b/src/app/[locale]/notifications/unsubscribe/lib/unsubscribe.spec.ts
index 6bc4b7ba..279cdead 100644
--- a/src/app/[locale]/notifications/unsubscribe/lib/unsubscribe.spec.ts
+++ b/src/app/[locale]/notifications/unsubscribe/lib/unsubscribe.spec.ts
@@ -39,6 +39,18 @@ describe('toSubscriptionLookup', () => {
).toEqual({ status: 'invalidId' });
});
+ it('treats a link with no id as a Brevo unsubscribe redirect', () => {
+ expect(
+ toSubscriptionLookup({
+ subscriptionId: undefined,
+ idMissing: true,
+ data: undefined,
+ error: undefined,
+ authFailed: false,
+ }),
+ ).toEqual({ status: 'noId' });
+ });
+
it('is loading until the request settles', () => {
expect(
toSubscriptionLookup({
@@ -161,6 +173,14 @@ describe('resolveViewCopy', () => {
);
expect(resolveViewCopy({ status: 'loading' }, null).status).toBe('loading');
});
+
+ it('confirms a Brevo unsubscribe instead of showing an error', () => {
+ expect(resolveViewCopy({ status: 'noId' }, null)).toEqual({
+ status: 'info',
+ titleKey: 'brevoUnsubscribedTitle',
+ descriptionKey: 'brevoUnsubscribedDescription',
+ });
+ });
});
describe('toUnsubscribeResult', () => {
diff --git a/src/app/[locale]/notifications/unsubscribe/lib/unsubscribe.ts b/src/app/[locale]/notifications/unsubscribe/lib/unsubscribe.ts
index 22ffc880..d960ff17 100644
--- a/src/app/[locale]/notifications/unsubscribe/lib/unsubscribe.ts
+++ b/src/app/[locale]/notifications/unsubscribe/lib/unsubscribe.ts
@@ -19,11 +19,12 @@ export type UnsubscribeResult = 'success' | 'notFound' | 'error';
export type SubscriptionLookup =
| { status: 'loading' }
| { status: 'found'; notificationId: string; active: boolean }
+ | { status: 'noId' }
| { status: 'invalidId' }
| { status: 'notFound' }
| { status: 'error' };
-export type ViewStatus = 'loading' | 'ready' | 'success' | 'error';
+export type ViewStatus = 'loading' | 'ready' | 'success' | 'error' | 'info';
export interface ViewCopy {
status: ViewStatus;
@@ -58,15 +59,19 @@ export function toUnsubscribeResult(status: number): UnsubscribeResult {
* `data` is null when the API reported the subscription missing, and
* undefined while the request hasn't settled (or hasn't started because the
* Firebase user isn't ready yet). `authFailed` means no Firebase user is
- * coming, so the request never will.
+ * coming, so the request never will. `idMissing` means the URL has no `id`
+ * at all: Brevo's unsubscribe confirmation redirects here without one, since
+ * API announcements are Brevo campaigns that don't know the subscription.
*/
export function toSubscriptionLookup({
subscriptionId,
+ idMissing = false,
data,
error,
authFailed,
}: {
subscriptionId: string | undefined;
+ idMissing?: boolean;
data:
| Pick
| null
@@ -75,7 +80,7 @@ export function toSubscriptionLookup({
authFailed: boolean;
}): SubscriptionLookup {
if (subscriptionId === undefined) {
- return { status: 'invalidId' };
+ return idMissing ? { status: 'noId' } : { status: 'invalidId' };
}
if (error != null || authFailed) {
return { status: 'error' };
@@ -133,6 +138,12 @@ export function resolveViewCopy(
? 'description'
: 'alreadyUnsubscribedDescription',
};
+ case 'noId':
+ return {
+ status: 'info',
+ titleKey: 'brevoUnsubscribedTitle',
+ descriptionKey: 'brevoUnsubscribedDescription',
+ };
case 'error':
return {
status: 'error',
diff --git a/src/app/services/profile-service.ts b/src/app/services/profile-service.ts
index ef6158fc..9e7d0804 100644
--- a/src/app/services/profile-service.ts
+++ b/src/app/services/profile-service.ts
@@ -129,6 +129,29 @@ export const retrieveUserInformation = async (): Promise<
}
};
+/**
+ * Asks the user service to turn API announcements off when the user
+ * unsubscribed from a Brevo email, and returns the resulting opt-in. It never
+ * turns announcements on. Used after Brevo's unsubscribe redirect, so the
+ * account page doesn't show a stale "subscribed" until the daily reconcile.
+ */
+export const syncAnnouncementsFromBrevo = async (): Promise => {
+ const accessToken = await getUserAccessToken();
+ const authMiddleware = generateAuthMiddlewareWithToken(accessToken);
+ userServiceClient.use(authMiddleware);
+ try {
+ const { data, error } = await userServiceClient.POST(
+ '/v1/user/announcements/sync',
+ );
+ if (error !== undefined || data === undefined) {
+ throw new Error('Failed to sync API announcements');
+ }
+ return data.is_registered_to_receive_api_announcements;
+ } finally {
+ userServiceClient.eject(authMiddleware);
+ }
+};
+
export const populateUserWithAdditionalInfo = (
user: User,
userData: UserData | undefined,
diff --git a/src/app/services/user-service-api-types.ts b/src/app/services/user-service-api-types.ts
index b84f912d..342e6929 100644
--- a/src/app/services/user-service-api-types.ts
+++ b/src/app/services/user-service-api-types.ts
@@ -30,6 +30,30 @@ export interface paths {
patch?: never;
trace?: never;
};
+ '/v1/user/announcements/sync': {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ /**
+ * Refresh the current user's API announcements opt-in from Brevo
+ * @description Reads the user's Brevo contact and turns their `api.announcements` subscription
+ * off when they unsubscribed from a Brevo email, then returns the profile. It never
+ * turns announcements on and never writes to Brevo. The daily reconcile task does the
+ * same for every user; this lets the website show the change at once, e.g. after the
+ * Brevo unsubscribe redirect. Makes one Brevo call, only when the subscription is on.
+ */
+ post: operations['syncUserAnnouncements'];
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
'/v1/notifications': {
parameters: {
query?: never;
@@ -170,8 +194,8 @@ export interface paths {
* Behaviour depends on the notification type:
* - **`api.announcements`** — never deleted; the subscription is *disabled*
* (`active=false`), the contact is removed from the Brevo announcements
- * list, and `app_user.is_registered_to_receive_api_announcements` is
- * cleared. Kept idempotent so a repeated click still succeeds.
+ * list, and the user's `is_registered_to_receive_api_announcements`
+ * therefore reads `false`. Kept idempotent so a repeated click still succeeds.
* - **all other types** (e.g. `feed.url_updated`) — the subscription row is
* hard-deleted; a second call therefore returns `404`.
*
@@ -179,8 +203,7 @@ export interface paths {
* (Brevo) cannot be reached while updating an announcements subscription.
*
* The `id` embedded in an email is the subscription's own UUID
- * (`notification_subscription.id`) — mirrored onto the Brevo contact as the
- * `MDB_SUBSCRIPTION_ID` attribute — **not** the notification-type string
+ * (`notification_subscription.id`) — **not** the notification-type string
* (`api.announcements`), which is shared by all recipients and is not a
* valid subscription ID.
*
@@ -281,7 +304,7 @@ export interface components {
description?: string | null;
};
NotificationSubscription: {
- /** @description Unique subscription ID (UUID v4). This is the **capability token** used by the public `/v1/subscriptions/{id}` endpoints and by email unsubscribe links; for `api.announcements` it is mirrored onto the Brevo contact as the `MDB_SUBSCRIPTION_ID` attribute. */
+ /** @description Unique subscription ID (UUID v4). This is the **capability token** used by the public `/v1/subscriptions/{id}` endpoints and by email unsubscribe links. `api.announcements` emails are Brevo campaigns and use Brevo's own unsubscribe link instead. */
id: string;
/** @description The ID of the subscribed user. */
user_id: string;
@@ -512,6 +535,54 @@ export interface operations {
};
};
};
+ syncUserAnnouncements: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description The user's profile after the refresh. */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ 'application/json': components['schemas']['UserProfile'];
+ };
+ };
+ /** @description Unauthorized — missing or invalid token. */
+ 401: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
+ /** @description Forbidden — guest users have no profile. */
+ 403: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
+ /** @description User not found. */
+ 404: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
+ /** @description Brevo could not be reached or returned an error. */
+ 502: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
+ };
+ };
getNotifications: {
parameters: {
query?: never;
diff --git a/src/app/store/profile-reducer.ts b/src/app/store/profile-reducer.ts
index 872c0e95..d19133ce 100644
--- a/src/app/store/profile-reducer.ts
+++ b/src/app/store/profile-reducer.ts
@@ -186,6 +186,11 @@ export const userProfileSlice = createSlice({
action.payload?.isRegisteredToReceiveAPIAnnouncements ?? false;
}
},
+ setApiAnnouncementsOptIn: (state, action: PayloadAction) => {
+ if (state.user !== undefined) {
+ state.user.isRegisteredToReceiveAPIAnnouncements = action.payload;
+ }
+ },
saveUserProfile: (
state,
action: PayloadAction<{
@@ -337,6 +342,7 @@ export const {
updateUserProfile,
saveUserProfile,
saveUserProfileSuccess,
+ setApiAnnouncementsOptIn,
saveUserProfileFail,
saveUserProfileReset,
changePassword,