Skip to content

Commit 3aa4c2a

Browse files
pbertschclaude
andcommitted
feat: add imports resource + analytics.get_aggregate_stats (#parity B2)
Adds the Workstream B2 parity surface to the dual sync/async SDK: - New `imports` resource (sync + async) wrapping /api/v1/imports: start (snake_case body), get_status, cancel, list, wait_for_completion (polls to a terminal state; sync time.sleep / async asyncio.sleep). - Extends the analytics resource (sync + async) with get_aggregate_stats -> GET /api/v1/links/{short_path}/stats/aggregate. - Pydantic v2 models: ImportJob, ImportCounts, AggregateStats, DayClicks, HourClicks, DeviceBreakdown, UTMBreakdown, UpgradeForMore. - Attaches `imports` to Client and AsyncClient; exports new models. - Fully mocked tests (sync + async) for imports + aggregate stats. - README sections; version bump 1.2.0 -> 1.3.0 (pyproject + __version__). NOTE: backing routes are staging-only (prod deploy pending APPROVE) — this PR is a DRAFT and all tests are mocked (no live calls). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent af49c45 commit 3aa4c2a

11 files changed

Lines changed: 794 additions & 7 deletions

File tree

‎README.md‎

Lines changed: 62 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,8 @@ client.links.delete("my-link")
8787

8888
| Method | Description |
8989
|---|---|
90-
| `client.analytics.get_stats(short_path)` | Get click stats for a link |
90+
| `client.analytics.get_stats(short_path)` | Get raw per-click stats for a link |
91+
| `client.analytics.get_aggregate_stats(short_path, *, period=None)` | Get rolled-up (aggregated) stats for a link |
9192

9293
```python
9394
stats = client.analytics.get_stats("abc123")
@@ -96,6 +97,25 @@ for click in stats.clicks:
9697
print(click.country, click.device, click.timestamp)
9798
```
9899

100+
`get_aggregate_stats` returns server-side aggregations (clicks-by-day,
101+
country/device/UTM breakdowns, unique visitors). The breakdowns present are
102+
**tier-gated** — free-tier responses include an `upgrade_for_more` hint and
103+
omit the richer breakdowns; higher tiers populate `device_breakdown`,
104+
`utm_breakdown`, `hour_breakdown`, etc.
105+
106+
```python
107+
agg = client.analytics.get_aggregate_stats("abc123", period="30d")
108+
print(agg.total_clicks, agg.unique_visitors, agg.tier)
109+
for day in agg.clicks_by_day:
110+
print(day.date, day.clicks)
111+
print(agg.country_breakdown) # {"US": 100, ...}
112+
113+
if agg.device_breakdown: # populated on Pro+
114+
print(agg.device_breakdown.mobile, agg.device_breakdown.desktop)
115+
if agg.upgrade_for_more: # present on free tier
116+
print(agg.upgrade_for_more.message, agg.upgrade_for_more.available)
117+
```
118+
99119
### QR Codes
100120

101121
| Method | Description |
@@ -193,6 +213,40 @@ session = client.web2app.consume_session("0123456789abcdef0123456789abcdef")
193213
print(session.link_id, session.utm_params, session.country)
194214
```
195215

216+
### Imports
217+
218+
| Method | Description |
219+
|---|---|
220+
| `client.imports.start(*, provider, access_token, target_namespace=None, scan_only=None)` | Start a provider link-import job |
221+
| `client.imports.get_status(job_id)` | Get the current state of an import job |
222+
| `client.imports.cancel(job_id)` | Cancel an in-progress import job |
223+
| `client.imports.list(*, limit=None)` | List import jobs for the account |
224+
| `client.imports.wait_for_completion(job_id, *, poll_interval=2.0, timeout=120.0)` | Poll until the job reaches a terminal state |
225+
226+
Import jobs run asynchronously server-side. `start` returns a `pending`
227+
`ImportJob`; poll `get_status` (or use `wait_for_completion`) until the status
228+
is one of `completed`, `partial`, `failed`, or `cancelled`. Pass
229+
`scan_only=True` to preview what would be imported without writing links.
230+
231+
```python
232+
job = client.imports.start(provider="bitly", access_token="<bitly-token>")
233+
print(job.id, job.status)
234+
235+
# Block until the import finishes (raises TimeoutError if it overruns).
236+
done = client.imports.wait_for_completion(job.id, poll_interval=5.0, timeout=300.0)
237+
print(done.status, done.counts.written, done.counts.errored)
238+
for err in done.errors:
239+
print(err)
240+
241+
# Or drive it manually
242+
for j in client.imports.list(limit=10):
243+
print(j.id, j.provider, j.status)
244+
client.imports.cancel(job.id)
245+
```
246+
247+
All `imports` methods are available identically on `AsyncClient`
248+
(`await client.imports.start(...)`, `await client.imports.wait_for_completion(...)`).
249+
196250
## Error Handling
197251

198252
All errors inherit from `AwsysError`.
@@ -288,6 +342,13 @@ All responses are parsed into Pydantic v2 models:
288342
| `UsageLimits` | `links_per_month`, `monthly_links`, `daily_links`, `monthly_tracked_clicks`, `qr_codes`, `folders` (each `int` or `"unlimited"`), `api_calls_per_month`, `custom_slugs` |
289343
| `UsageOverage` | `active`, `started_at`, `expires_at`, `hours_until_drop`, `clicks_this_cycle`, `spending_limit_cents`, `estimated_charge_cents` |
290344
| `Web2AppSession` | `success`, `link_id`, `utm_params`, `routing_rule`, `country`, `clicked_at` |
345+
| `ImportJob` | `id`, `user_id`, `provider`, `status`, `scan_only`, `target_namespace`, `scope_filter`, `counts`, `errors`, `created_at`, `updated_at` |
346+
| `ImportCounts` | `fetched`, `transformed`, `written`, `errored` |
347+
| `AggregateStats` | `short_code`, `full_path`, `period`, `total_clicks`, `unique_visitors`, `clicks_by_day`, `country_breakdown`, `tier_limit`, `tier`, `device_breakdown`, `referrer_breakdown`, `browser_breakdown`, `os_breakdown`, `source_breakdown`, `hour_breakdown`, `utm_breakdown`, `upgrade_for_more` |
348+
| `DayClicks` / `HourClicks` | `date`/`hour`, `clicks` |
349+
| `DeviceBreakdown` | `mobile`, `desktop`, `tablet` |
350+
| `UTMBreakdown` | `sources`, `mediums`, `campaigns` |
351+
| `UpgradeForMore` | `available`, `message` |
291352

292353
## Development Setup
293354

‎awsysco/__init__.py‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,19 @@
1212
)
1313
from .models import (
1414
AffiliateProgram,
15+
AggregateStats,
1516
BulkLinkResult,
1617
BulkResult,
1718
ClickEvent,
1819
CustomDomain,
20+
DayClicks,
21+
DeviceBreakdown,
1922
Folder,
2023
FolderList,
2124
GeoRestriction,
25+
HourClicks,
26+
ImportCounts,
27+
ImportJob,
2228
Link,
2329
LinkList,
2430
LinkStats,
@@ -31,15 +37,17 @@
3137
SavedView,
3238
SavedViewFilters,
3339
TrustScoreResult,
40+
UpgradeForMore,
3441
UsageLimits,
3542
UsageOverage,
3643
UsageStats,
44+
UTMBreakdown,
3745
UtmTemplate,
3846
Web2AppSession,
3947
Webhook,
4048
)
4149

42-
__version__ = "1.2.0"
50+
__version__ = "1.3.0"
4351
__all__ = [
4452
# Clients
4553
"Client",
@@ -90,4 +98,14 @@
9098
"UsageOverage",
9199
# Web2App
92100
"Web2AppSession",
101+
# Imports
102+
"ImportCounts",
103+
"ImportJob",
104+
# Aggregate analytics
105+
"AggregateStats",
106+
"DayClicks",
107+
"HourClicks",
108+
"DeviceBreakdown",
109+
"UTMBreakdown",
110+
"UpgradeForMore",
93111
]

‎awsysco/async_resources/analytics.py‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from typing import List, Optional
66

77
from .._async_http import AsyncHttpClient
8-
from ..models import ClickEvent, LinkStats
8+
from ..models import AggregateStats, ClickEvent, LinkStats
99

1010

1111
class AsyncAnalyticsResource:
@@ -22,6 +22,18 @@ async def get_stats(self, short_path: str, *, period: Optional[str] = None) -> L
2222
)
2323
return LinkStats.model_validate(data)
2424

25+
async def get_aggregate_stats(
26+
self, short_path: str, *, period: Optional[str] = None
27+
) -> AggregateStats:
28+
params = {}
29+
if period is not None:
30+
params["period"] = period
31+
data = await self._http.get(
32+
f"/api/v1/links/{short_path}/stats/aggregate",
33+
params=params if params else None,
34+
)
35+
return AggregateStats.model_validate(data)
36+
2537
async def get_recent_clicks(self, *, limit: Optional[int] = None) -> List[ClickEvent]:
2638
params = {}
2739
if limit is not None:

‎awsysco/async_resources/imports.py‎

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
"""Async Imports resource."""
2+
3+
from __future__ import annotations
4+
5+
import asyncio
6+
import time
7+
from typing import List, Optional
8+
from urllib.parse import quote
9+
10+
from .._async_http import AsyncHttpClient
11+
from ..models import ImportJob
12+
13+
# Statuses that indicate the import job has stopped progressing.
14+
_TERMINAL_STATES = {"completed", "partial", "failed", "cancelled"}
15+
16+
17+
class AsyncImportsResource:
18+
def __init__(self, http: AsyncHttpClient) -> None:
19+
self._http = http
20+
21+
async def start(
22+
self,
23+
*,
24+
provider: str,
25+
access_token: str,
26+
target_namespace: Optional[str] = None,
27+
scan_only: Optional[bool] = None,
28+
) -> ImportJob:
29+
"""Start a new provider link-import job.
30+
31+
The request body uses snake_case keys (``provider``, ``access_token``,
32+
optional ``target_namespace`` / ``scan_only``).
33+
"""
34+
body = {"provider": provider, "access_token": access_token}
35+
if target_namespace is not None:
36+
body["target_namespace"] = target_namespace
37+
if scan_only is not None:
38+
body["scan_only"] = scan_only
39+
data = await self._http.post("/api/v1/imports", json=body)
40+
return ImportJob.model_validate(data)
41+
42+
async def get_status(self, job_id: str) -> ImportJob:
43+
"""Get the current state of an import job."""
44+
encoded = quote(job_id, safe="")
45+
data = await self._http.get(f"/api/v1/imports/{encoded}")
46+
return ImportJob.model_validate(data)
47+
48+
async def cancel(self, job_id: str) -> ImportJob:
49+
"""Cancel an in-progress import job."""
50+
encoded = quote(job_id, safe="")
51+
data = await self._http.delete(f"/api/v1/imports/{encoded}")
52+
return ImportJob.model_validate(data)
53+
54+
async def list(self, *, limit: Optional[int] = None) -> List[ImportJob]:
55+
"""List import jobs for the authenticated user."""
56+
params = {}
57+
if limit is not None:
58+
params["limit"] = limit
59+
data = await self._http.get(
60+
"/api/v1/imports",
61+
params=params if params else None,
62+
)
63+
items = data.get("jobs", []) if isinstance(data, dict) else (data or [])
64+
return [ImportJob.model_validate(item) for item in items]
65+
66+
async def wait_for_completion(
67+
self,
68+
job_id: str,
69+
*,
70+
poll_interval: float = 2.0,
71+
timeout: float = 120.0,
72+
) -> ImportJob:
73+
"""Poll an import job until it reaches a terminal state.
74+
75+
Polls ``get_status`` every ``poll_interval`` seconds until the job
76+
status is one of ``completed``, ``partial``, ``failed``, or
77+
``cancelled``.
78+
79+
Raises:
80+
TimeoutError: If the job does not finish within ``timeout``.
81+
"""
82+
deadline = time.monotonic() + timeout
83+
while True:
84+
job = await self.get_status(job_id)
85+
if job.status in _TERMINAL_STATES:
86+
return job
87+
if time.monotonic() >= deadline:
88+
raise TimeoutError(
89+
f"Import job {job_id} did not complete within {timeout}s "
90+
f"(last status: {job.status})"
91+
)
92+
await asyncio.sleep(poll_interval)

‎awsysco/client.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
from .async_resources.custom_domains import AsyncCustomDomainsResource
1414
from .async_resources.data_export import AsyncDataExportResource
1515
from .async_resources.folders import AsyncFoldersResource
16+
from .async_resources.imports import AsyncImportsResource
1617
from .async_resources.links import AsyncLinksResource
1718
from .async_resources.me import AsyncMeResource
1819
from .async_resources.namespace import AsyncNamespaceResource
@@ -31,6 +32,7 @@
3132
from .resources.custom_domains import CustomDomainsResource
3233
from .resources.data_export import DataExportResource
3334
from .resources.folders import FoldersResource
35+
from .resources.imports import ImportsResource
3436
from .resources.links import LinksResource
3537
from .resources.me import MeResource
3638
from .resources.namespace import NamespaceResource
@@ -99,6 +101,7 @@ def __init__(
99101
# Parity resources
100102
self.usage = UsageResource(self._http)
101103
self.web2app = Web2AppResource(self._http)
104+
self.imports = ImportsResource(self._http)
102105

103106
def close(self) -> None:
104107
"""Close the underlying HTTP connection pool."""
@@ -162,6 +165,7 @@ def __init__(
162165
# Parity resources
163166
self.usage = AsyncUsageResource(self._http)
164167
self.web2app = AsyncWeb2AppResource(self._http)
168+
self.imports = AsyncImportsResource(self._http)
165169

166170
async def aclose(self) -> None:
167171
"""Close the underlying async HTTP connection pool."""

0 commit comments

Comments
 (0)