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
41 changes: 35 additions & 6 deletions external_types/UserServiceAPI.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -349,17 +379,16 @@ 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`.

Returns `404` for an unknown/invalid ID, and `502` if the email provider
(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.

Expand Down Expand Up @@ -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.
Expand Down
6 changes: 5 additions & 1 deletion messages/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand Down
6 changes: 5 additions & 1 deletion messages/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand Down
49 changes: 46 additions & 3 deletions src/app/[locale]/account/AccountGeneral.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use client';

import * as React from 'react';
import { useSearchParams } from 'next/navigation';
import { useRouter } from '../../../i18n/navigation';
import {
Alert,
Expand All @@ -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');
Expand All @@ -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('');
Expand Down Expand Up @@ -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);
Expand All @@ -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';
Expand Down Expand Up @@ -110,7 +143,7 @@ export default function AccountGeneral(): React.ReactElement {
<AccountSectionContainer
title={t('personalInformation')}
subtitle={t('personalInformationSubtitle')}
loading={isSaving}
loading={isSaving || isSyncing}
action={
isEditing ? (
<Box sx={{ display: 'flex', gap: 1 }}>
Expand All @@ -132,7 +165,12 @@ export default function AccountGeneral(): React.ReactElement {
</Button>
</Box>
) : (
<Button variant='outlined' size='small' onClick={handleEditClick}>
<Button
variant='outlined'
size='small'
onClick={handleEditClick}
disabled={isSyncing}
>
{t('edit')}
</Button>
)
Expand Down Expand Up @@ -201,8 +239,13 @@ export default function AccountGeneral(): React.ReactElement {
/>
}
label={t('registerApiAnnouncements')}
sx={{ mt: 0.5 }}
sx={{ mt: 0.5, visibility: isSyncing ? 'hidden' : 'visible' }}
/>
{announcementsSync === 'failed' ? (
<Alert severity='info' data-testid='announcements-sync-failed'>
{t('announcementsSyncFailed')}
</Alert>
) : null}
</Box>
</AccountSectionContainer>
<AccountSectionContainer title={t('supportTitle')} sx={{ mt: 3 }}>
Expand Down
28 changes: 28 additions & 0 deletions src/app/[locale]/account/lib/announcementsSync.spec.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
18 changes: 18 additions & 0 deletions src/app/[locale]/account/lib/announcementsSync.ts
Original file line number Diff line number Diff line change
@@ -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<URLSearchParams, 'get'> | null,
): boolean {
return params?.get(ANNOUNCEMENTS_SYNC_PARAM) === ANNOUNCEMENTS_SYNC_VALUE;
}
22 changes: 15 additions & 7 deletions src/app/[locale]/notifications/unsubscribe/UnsubscribeContent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -80,6 +81,7 @@ export default function UnsubscribeContent(): React.ReactElement {

const lookup = toSubscriptionLookup({
subscriptionId,
idMissing: idParam === null,
data,
error,
authFailed: !isAuthReady && anonymousLoginError,
Expand All @@ -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 =
Expand Down Expand Up @@ -227,11 +233,13 @@ export default function UnsubscribeContent(): React.ReactElement {
<Button
component={Link}
href={manageHref}
variant='text'
variant={lookup.status === 'noId' ? 'outlined' : 'text'}
disabled={isPending}
data-testid='manage-notifications'
>
{t('manageNotifications')}
{lookup.status === 'noId' && !isRegistered
? t('signInToManage')
: t('manageNotifications')}
</Button>
</Stack>
)}
Expand Down
20 changes: 20 additions & 0 deletions src/app/[locale]/notifications/unsubscribe/lib/unsubscribe.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down Expand Up @@ -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', () => {
Expand Down
Loading
Loading