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
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
# Changelog

## Unreleased

Added:

- `athletes.create_onboarding_link(athlete_id, locale=None)` (`POST /v1/athletes/{athlete_id}/onboarding-link`) returns `OnboardingLink`: a fresh link to the hosted onboarding page (`url`), valid until `expires_at` (Unix seconds, 90 days on). Call it from your refresh address, where an athlete who opens an expired link is sent with `athlete_id` and `locale` in the query, and redirect them to `url`. Production refuses it with `PermissionDeniedError` (`hosted_onboarding_unavailable`) until the page opens there. A 5xx on it is retried.
- `PartnerAccount["return_url"]` and `PartnerAccount["refresh_url"]`: the addresses on your account that the hosted onboarding page sends athletes to.

## 0.8.0 (unreleased)

Breaking changes:
Expand Down
4 changes: 4 additions & 0 deletions saturday/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,8 @@
NutrientAmounts,
NutritionCalculateResponse,
OnboardingInvite,
OnboardingLink,
OnboardingLocale,
OnboardingOption,
OnboardingQuestion,
OnboardingQuestionsResponse,
Expand Down Expand Up @@ -252,6 +254,8 @@
"NutrientAmounts",
"NutritionCalculateResponse",
"OnboardingInvite",
"OnboardingLink",
"OnboardingLocale",
"OnboardingOption",
"OnboardingQuestion",
"OnboardingQuestionsResponse",
Expand Down
14 changes: 12 additions & 2 deletions saturday/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@
IntegrationSyncResponse,
LicenseListResponse,
NutritionCalculateResponse,
OnboardingLink,
OnboardingLocale,
OnboardingQuestionsResponse,
Organization,
OrganizationListResponse,
Expand Down Expand Up @@ -79,13 +81,13 @@
DEFAULT_BASE_URL = "https://api.saturday.fit"
DEFAULT_TIMEOUT = 30.0
DEFAULT_MAX_RETRIES = 3
_RETRY_SAFE_ACTIVITY_POST = re.compile(r"^/v1/athletes/[^/]+/(activities/[^/]+/(calculate|prep)|export)$")
_RETRY_SAFE_ACTIVITY_POST = re.compile(r"^/v1/athletes/[^/]+/(activities/[^/]+/(calculate|prep)|export|onboarding-link)$")


def _retry_safe_on_server_error(method: str, path: str) -> bool:
"""A 5xx is retried only where a repeat cannot make a second record: every GET, PUT, PATCH
and DELETE, and the POSTs that compute or read (calculations, product fit and compare, label
reading, inference, an activity's calculate and prep, export)."""
reading, inference, an activity's calculate and prep, export, an onboarding link)."""
if method.upper() != "POST":
return True
bare = path.split("?")[0]
Expand Down Expand Up @@ -346,6 +348,14 @@ def get_fueling_profile(self, athlete_id: str) -> FuelingProfile:
only ``on`` carries ``profile``; ``off`` and ``not_linked`` carry ``message``."""
return self._client.request("GET", f"/v1/athletes/{_seg(athlete_id)}/fueling-profile")

def create_onboarding_link(self, athlete_id: str, locale: Optional[OnboardingLocale] = None) -> OnboardingLink:
"""A fresh link to the hosted onboarding page for the athlete, valid for 90 days. Call it from
your refresh address, once your signed-in user owns ``athlete_id``, and redirect the athlete
to ``url``. Production refuses it with ``PermissionDeniedError``
(``hosted_onboarding_unavailable``) until the page opens there."""
body: Dict[str, Any] = {"locale": locale} if locale else {}
return self._client.request("POST", f"/v1/athletes/{_seg(athlete_id)}/onboarding-link", json=body)

def batch_create(self, athletes: List[Dict[str, Any]]) -> BatchAthleteResponse:
"""Create up to 100 athletes in one call. An item whose ``external_id`` one of your athletes
holds, an earlier item of the same batch included, fails with ``athlete_exists`` and that
Expand Down
22 changes: 21 additions & 1 deletion saturday/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,19 @@ class OnboardingInvite(_OnboardingInviteRequired, total=False):
url: str


# A language the hosted onboarding page opens in.
OnboardingLocale = Literal["en", "es", "fr", "pt", "de", "ja"]


class OnboardingLink(TypedDict):
"""POST /v1/athletes/{athlete_id}/onboarding-link: a fresh link to the hosted onboarding page."""

object: Literal["onboarding_link"]
athlete_id: str
url: str
expires_at: int # Unix seconds; the link stops working then, 90 days after it was made.


class _PrecisionRequired(TypedDict):
profile_complete: bool

Expand Down Expand Up @@ -1200,7 +1213,7 @@ class PartnerRateLimits(TypedDict):
trial_answers: Optional[int]


class PartnerAccount(TypedDict):
class _PartnerAccountRequired(TypedDict):
id: str
name: str
contact_email: str
Expand All @@ -1211,6 +1224,13 @@ class PartnerAccount(TypedDict):
created_at: int # Unix seconds.


class PartnerAccount(_PartnerAccountRequired, total=False):
return_url: str # Where the hosted onboarding page sends athletes back to you; absent when none is set.
# Where an athlete who opens an expired onboarding link is sent, with athlete_id and locale in the
# query, so your server can get a fresh link and send them on. Absent when none is set.
refresh_url: str


class DailyUsage(TypedDict):
date: str # YYYY-MM-DD, UTC.
total_calls: int
Expand Down
29 changes: 28 additions & 1 deletion tests/fixtures/contracts.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"_meta": {
"backend_sha": "aae11b6dd0d6814810d8b337f8e9cbee27b2a310",
"backend_sha": "c5382f6d157b4d8074719e25c033adf95887d3b1",
"source": "pkg/api Go JSON types, stored-prescription/list/settings HTTP handlers, the coach billing structs in pkg/purchase, pkg/connect and pkg/coachbilling, and the profile-sharing types in pkg/api, pkg/partner and pkg/webhook; synthetic values, no API calls"
},
"activity": {
Expand Down Expand Up @@ -1093,6 +1093,33 @@
"required": false
}
},
"onboarding_link": {
"object": "onboarding_link",
"athlete_id": "ath_1",
"url": "https://saturday.fit/onboard?ot=eyJwaWQiOiJwYXJ0bmVyXzEifQ.sig",
"expires_at": 1707776000
},
"partner_profile": {
"id": "partner_1",
"name": "Fixture Partner",
"contact_email": "partner@example.com",
"status": "active",
"plan": "partner",
"return_url": "https://partner.example/fueling",
"refresh_url": "https://partner.example/saturday/refresh",
"rate_limits": {
"requests_per_second": 10,
"burst_size": 20,
"requests_per_minute": 600,
"requests_per_day": 2000,
"ip_requests_per_day": 1000,
"trial_starts_per_day": 50,
"trial_profiles_per_athlete": 3,
"trial_days": 14,
"trial_answers": 42
},
"created_at": 1700000000
},
"settings_empty": {},
"settings_full": {
"sweat_level": 5,
Expand Down
1 change: 1 addition & 0 deletions tests/test_contracts.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
"athlete_sharing": "Athlete",
"fueling_profile_on": "FuelingProfile", "fueling_profile_off": "FuelingProfile", "fueling_profile_not_linked": "FuelingProfile",
"webhook_profile_sharing_changed": "ProfileSharingChangedEvent", "webhook_fueling_profile_updated": "FuelingProfileUpdatedEvent",
"onboarding_link": "OnboardingLink", "partner_profile": "PartnerAccount",
}


Expand Down
40 changes: 40 additions & 0 deletions tests/test_onboarding.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,3 +158,43 @@ def handler(request: httpx.Request) -> httpx.Response:
assert rx["precision"]["profile_complete"] is True
assert "missing_fields" not in rx["precision"]
assert rx["carb_g_per_hr"] == 70



def test_create_onboarding_link_posts_locale():
"""create_onboarding_link() POSTs the locale to /v1/athletes/{id}/onboarding-link."""
seen = {}

def handler(request: httpx.Request) -> httpx.Response:
seen["method"] = request.method
seen["path"] = request.url.raw_path.decode()
seen["body"] = request.content
return httpx.Response(
200,
json={
"object": "onboarding_link",
"athlete_id": "ath_1",
"url": "https://saturday.fit/onboard?ot=abc&test=1&locale=de",
"expires_at": 1771200000,
},
)

client = _client_with(handler)
res = client.athletes.create_onboarding_link("ath 1", locale="de")

assert seen["method"] == "POST"
assert seen["path"] == "/v1/athletes/ath%201/onboarding-link"
assert seen["body"] == b'{"locale":"de"}' or seen["body"] == b'{"locale": "de"}'
assert res["expires_at"] == 1771200000
assert "locale=de" in res["url"]


def test_create_onboarding_link_without_locale_sends_empty_body():
seen = {}

def handler(request: httpx.Request) -> httpx.Response:
seen["body"] = request.content
return httpx.Response(200, json={"object": "onboarding_link", "athlete_id": "ath_1", "url": "u", "expires_at": 1})

_client_with(handler).athletes.create_onboarding_link("ath_1")
assert seen["body"] in (b"{}", b"{ }")