-
Notifications
You must be signed in to change notification settings - Fork 6
feat: user subscriptions + subscription endpoints impl #1740
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
cka-y
wants to merge
4
commits into
main
Choose a base branch
from
feat/1692
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -40,6 +40,54 @@ class BrevoSubscriptionStatus(Enum): | |
| NOT_FOUND = "not_found" | ||
|
|
||
|
|
||
| def _get_contacts_api() -> "sib_api_v3_sdk.ContactsApi": | ||
| """Build a Brevo ContactsApi client. Raises RuntimeError if BREVO_API_KEY is unset.""" | ||
| api_key = os.getenv("BREVO_API_KEY") | ||
| if not api_key: | ||
| raise RuntimeError("BREVO_API_KEY environment variable is not set") | ||
| configuration = sib_api_v3_sdk.Configuration() | ||
| configuration.api_key["api-key"] = api_key | ||
| return sib_api_v3_sdk.ContactsApi(sib_api_v3_sdk.ApiClient(configuration)) | ||
|
|
||
|
|
||
| def get_announcements_list_id() -> int: | ||
| """Return the Brevo API-announcements list id from BREVO_API_ANNOUNCEMENTS_LIST_ID.""" | ||
| raw = os.getenv("BREVO_API_ANNOUNCEMENTS_LIST_ID") | ||
| if not raw: | ||
| raise RuntimeError("BREVO_API_ANNOUNCEMENTS_LIST_ID environment variable is not set") | ||
| return int(raw) | ||
|
|
||
|
|
||
| def add_contact_to_list(email: str, list_id: int, subscription_id: str) -> None: | ||
| """Create/update a Brevo contact, add it to the list, and set MDB_SUBSCRIPTION_ID. | ||
|
|
||
| Uses create_contact with update_enabled so it works whether or not the | ||
| contact already exists. | ||
| """ | ||
| api = _get_contacts_api() | ||
| api.create_contact( | ||
| sib_api_v3_sdk.CreateContact( | ||
| email=email, | ||
| attributes={"MDB_SUBSCRIPTION_ID": subscription_id}, | ||
| list_ids=[list_id], | ||
| update_enabled=True, | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 👍 |
||
| ) | ||
| ) | ||
|
|
||
|
|
||
| def remove_contact_from_list(email: str, list_id: int) -> None: | ||
| """Remove a Brevo contact from the list. No-op if the contact is not on the list.""" | ||
| api = _get_contacts_api() | ||
| try: | ||
| api.remove_contact_from_list(list_id, sib_api_v3_sdk.RemoveContactFromList(emails=[email])) | ||
| except sib_api_v3_sdk.rest.ApiException as exc: | ||
| # 400 "Contact already removed from list" / 404 contact-not-found are idempotent no-ops. | ||
| if exc.status in (400, 404): | ||
| logger.info("Contact %s not on list %s, nothing to remove", email, list_id) | ||
| return | ||
| raise | ||
|
|
||
|
|
||
| def get_contact_subscription_status( | ||
| email: str, | ||
| list_id: int | None = None, | ||
|
|
@@ -56,13 +104,7 @@ def get_contact_subscription_status( | |
| Raises RuntimeError if BREVO_API_KEY is not set. | ||
| Raises sib_api_v3_sdk.rest.ApiException on unexpected API errors. | ||
| """ | ||
| api_key = os.getenv("BREVO_API_KEY") | ||
| if not api_key: | ||
| raise RuntimeError("BREVO_API_KEY environment variable is not set") | ||
|
|
||
| configuration = sib_api_v3_sdk.Configuration() | ||
| configuration.api_key["api-key"] = api_key | ||
| api = sib_api_v3_sdk.ContactsApi(sib_api_v3_sdk.ApiClient(configuration)) | ||
| api = _get_contacts_api() | ||
|
|
||
| try: | ||
| contact = api.get_contact_info(email) | ||
|
|
||
24 changes: 24 additions & 0 deletions
24
api/src/shared/db_models/notification_subscription_impl.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| from shared.users_database_gen.sqlacodegen_models import NotificationSubscription as NotificationSubscriptionOrm | ||
| from user_service_gen.models.notification_subscription import NotificationSubscription | ||
|
|
||
|
|
||
| class NotificationSubscriptionImpl(NotificationSubscription): | ||
| """Implementation of the NotificationSubscription model. | ||
| Converts a SQLAlchemy NotificationSubscription ORM object to a Pydantic NotificationSubscription model. | ||
| """ | ||
|
|
||
| class Config: | ||
| from_attributes = True | ||
|
|
||
| @classmethod | ||
| def from_orm(cls, sub: NotificationSubscriptionOrm | None) -> NotificationSubscription | None: | ||
| if not sub: | ||
| return None | ||
| return cls( | ||
| id=sub.id, | ||
| user_id=sub.user_id, | ||
| notification_id=sub.notification_type_id, | ||
| active=sub.active, | ||
| last_notified_at=sub.last_notified_at, | ||
| created_at=sub.created_at, | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| # | ||
| # MobilityData 2026 | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| # | ||
| """Helpers shared between the authenticated (users) and public (subscriptions) APIs.""" | ||
|
|
||
| import logging | ||
|
|
||
| from fastapi import HTTPException | ||
|
|
||
| import sib_api_v3_sdk | ||
| from shared.common.brevo import add_contact_to_list, get_announcements_list_id, remove_contact_from_list | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| ANNOUNCEMENTS_NOTIFICATION_TYPE_ID = "api.announcements" | ||
|
|
||
|
|
||
| def sync_announcements(email: str, subscribe: bool, subscription_id: str | None = None) -> None: | ||
| """Sync an api.announcements subscription with Brevo, mapping provider errors to 502.""" | ||
| try: | ||
| if subscribe: | ||
| add_contact_to_list(email, get_announcements_list_id(), subscription_id) | ||
| else: | ||
| remove_contact_from_list(email, get_announcements_list_id()) | ||
| except (RuntimeError, sib_api_v3_sdk.rest.ApiException) as exc: | ||
| logger.error("Brevo sync failed for %s: %s", email, exc) | ||
| raise HTTPException(status_code=502, detail="Failed to sync subscription with email provider.") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,55 @@ | ||
| # | ||
| # MobilityData 2026 | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| # | ||
|
|
||
| from fastapi import HTTPException | ||
|
|
||
| from shared.database.users_database import with_users_db_session | ||
| from shared.db_models.notification_subscription_impl import NotificationSubscriptionImpl | ||
| from shared.users_database_gen.sqlacodegen_models import ( | ||
| AppUser, | ||
| NotificationSubscription as NotificationSubscriptionOrm, | ||
| ) | ||
| from user_service.impl.subscription_helpers import ANNOUNCEMENTS_NOTIFICATION_TYPE_ID, sync_announcements | ||
| from user_service_gen.apis.subscriptions_api_base import BaseSubscriptionsApi | ||
| from user_service_gen.models.notification_subscription import NotificationSubscription | ||
|
|
||
|
|
||
| class SubscriptionsApiImpl(BaseSubscriptionsApi): | ||
| """Public, unauthenticated subscription management. | ||
|
|
||
| The subscription UUID is the access capability | ||
| """ | ||
|
|
||
| @with_users_db_session | ||
| def get_subscription(self, id: str, db_session=None) -> NotificationSubscription: | ||
| sub = db_session.get(NotificationSubscriptionOrm, id) | ||
| if sub is None: | ||
| raise HTTPException(status_code=404, detail="Subscription not found.") | ||
| return NotificationSubscriptionImpl.from_orm(sub) | ||
|
|
||
| @with_users_db_session | ||
| def delete_subscription(self, id: str, db_session=None) -> None: | ||
| sub = db_session.get(NotificationSubscriptionOrm, id) | ||
| if sub is None: | ||
| raise HTTPException(status_code=404, detail="Subscription not found.") | ||
|
|
||
| if sub.notification_type_id == ANNOUNCEMENTS_NOTIFICATION_TYPE_ID: | ||
| user = db_session.get(AppUser, sub.user_id) | ||
| if user is not None: | ||
| sync_announcements(user.email, subscribe=False) | ||
|
|
||
| db_session.delete(sub) | ||
| db_session.flush() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[question]: Does the
update_enabledadd the list_id to the lists, or does itresetthe list to only one list?