-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathdelivery.py
More file actions
542 lines (419 loc) · 22 KB
/
Copy pathdelivery.py
File metadata and controls
542 lines (419 loc) · 22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
"""Delivery-related Pydantic schemas.
Extracted from the monolithic schemas module. All classes are re-exported
from ``src.core.schemas`` for backward compatibility.
"""
from datetime import date
from enum import StrEnum
from typing import Any
from adcp.types import AggregatedTotals as LibraryAggregatedTotals
from adcp.types import DeliveryMeasurement as LibraryDeliveryMeasurement
from adcp.types import DeliveryMetrics as LibraryDeliveryMetrics
from adcp.types import (
DeliveryStatus, # noqa: F401 — re-exported for backward compat
PricingModel,
)
from adcp.types import GetCreativeDeliveryResponse as LibraryGetCreativeDeliveryResponse
from adcp.types import GetMediaBuyDeliveryRequest as LibraryGetMediaBuyDeliveryRequest
from adcp.types import GetMediaBuyDeliveryResponse as LibraryGetMediaBuyDeliveryResponse
from adcp.types import MediaBuyDeliveryStatus as LibraryMediaBuyDeliveryStatus
from adcp.types import ReportingPeriod as LibraryReportingPeriod
from adcp.types.generated_poc.core.geo_delivery_metrics import (
GeoDeliveryMetrics as LibraryByGeoItem,
) # adcp 6.6: inline ByGeoItem promoted to named $ref type GeoDeliveryMetrics (spec 3.1.1 geo-delivery-metrics.json)
from adcp.types.generated_poc.media_buy.get_media_buy_delivery_response import (
ByDeviceTypeItem as LibraryByDeviceTypeItem,
) # TODO: no stable alias in adcp.types
from pydantic import ConfigDict, Field
from src.core.config import get_pydantic_extra_mode
from src.core.schemas._base import NestedModelSerializerMixin, SalesAgentBaseModel
# ---------------------------------------------------------------------------
# Simple enum / leaf types
# ---------------------------------------------------------------------------
class DeliveryMeasurement(LibraryDeliveryMeasurement):
"""Measurement provider and methodology for delivery metrics per AdCP spec.
Extends library type - all fields inherited from AdCP spec.
The buyer accepts the declared provider as the source of truth for the buy.
"""
pass # All fields inherited from library
class DeliveryType(StrEnum):
"""Valid delivery types per AdCP spec."""
GUARANTEED = "guaranteed"
NON_GUARANTEED = "non_guaranteed"
# DeliveryStatus: imported from adcp library (all 6 values: delivering,
# not_delivering, completed, budget_exhausted, flight_ended, goal_met).
# ---------------------------------------------------------------------------
# Request schemas
# ---------------------------------------------------------------------------
class GetMediaBuyDeliveryRequest(LibraryGetMediaBuyDeliveryRequest):
"""Request delivery data for one or more media buys.
Extends library GetMediaBuyDeliveryRequest - all fields inherited from AdCP spec.
Examples:
- Single buy: media_buy_ids=["buy_123"]
- Multiple buys: media_buy_ids=["buy_123", "buy_456"]
- All active buys: status_filter="active"
- All buys: status_filter="all"
- Date range: start_date="2025-01-01", end_date="2025-01-31"
Note: push_notification_config support pending upstream (adcp issue #276).
Use ext field for extensions until spec is updated.
"""
model_config = ConfigDict(extra=get_pydantic_extra_mode())
# account, reporting_dimensions, attribution_window, time_granularity,
# include_window_breakdown, include_package_daily_breakdown: all now provided
# by adcp SDK 5.7 (spec 3.1.0-beta.3). No local redeclarations needed.
# ---------------------------------------------------------------------------
# Delivery data models
# ---------------------------------------------------------------------------
# AdCP-compliant delivery models
# FIXME(salesagent-jz3y): DeliveryTotals and PackageDelivery duplicate fields from
# adcp library Totals/ByPackageItem instead of inheriting. These should extend the
# library types (Pattern #1). Field names are now spec-aligned (completed_views);
# remaining work is switching to inheritance.
class DeliveryTotals(SalesAgentBaseModel):
"""Aggregate metrics for a media buy or package.
Note: Does not yet extend library Totals, but field names are aligned with
the AdCP spec (delivery-metrics.json), including ``completed_views``.
"""
impressions: float = Field(ge=0, description="Total impressions delivered")
spend: float = Field(ge=0, description="Total amount spent")
clicks: float | None = Field(None, ge=0, description="Total clicks (if applicable)")
ctr: float | None = Field(None, ge=0, le=1, description="Click-through rate (clicks/impressions)")
completed_views: float | None = Field(None, ge=0, description="Total completed views (if applicable)")
completion_rate: float | None = Field(
None, ge=0, le=1, description="Video completion rate (completions/impressions)"
)
conversions: float | None = Field(None, ge=0, description="Total conversions (if applicable)")
conversion_value: float | None = Field(
None,
ge=0,
description="Total monetary value of attributed conversions in the reporting currency (if applicable)",
)
viewability: float | None = Field(None, ge=0, le=1, description="Viewability percentage as 0.0-1.0 (if applicable)")
class PlacementBreakdown(SalesAgentBaseModel):
"""Delivery metrics for a single placement within a package."""
placement_id: str = Field(description="Placement identifier")
impressions: float = Field(ge=0, description="Placement impressions")
spend: float = Field(ge=0, description="Placement spend")
clicks: float | None = Field(None, ge=0, description="Placement clicks")
class GeoBreakdown(LibraryByGeoItem):
"""Geographic delivery breakdown entry (extends library GeoDeliveryMetrics).
Library provides geo_level, system, geo_code, geo_name plus the full
DeliveryMetrics surface. For metro/postal_area levels the ``system``
field carries the classification system the seller used
(e.g. 'nielsen_dma', 'us_zip'). See ``get_media_buy_delivery.mdx``
§Geo Breakdown.
"""
pass # All fields inherited from library GeoDeliveryMetrics
class DeviceTypeBreakdown(LibraryByDeviceTypeItem):
"""Device-type delivery breakdown entry (extends library ByDeviceTypeItem).
Library provides device_type enum (desktop, mobile, tablet, ctv, dooh,
unknown) plus the full DeliveryMetrics surface (impressions, spend, clicks,
ctr, views, completed_views, ...).
Returned when reporting_dimensions includes 'device_type'. The sibling
flag ``by_device_type_truncated`` MUST accompany this array whenever it
is present (``get-media-buy-delivery-response.json``).
"""
pass # All fields inherited from library ByDeviceTypeItem
class PackageDelivery(SalesAgentBaseModel):
"""Metrics broken down by package.
Note: Does not yet extend library ByPackageItem. See DeliveryTotals note.
"""
package_id: str = Field(description="Publisher's package identifier")
impressions: float = Field(ge=0, description="Package impressions")
spend: float = Field(ge=0, description="Package spend")
clicks: float | None = Field(None, ge=0, description="Package clicks")
completed_views: float | None = Field(None, ge=0, description="Package completed views")
pacing_index: float | None = Field(
None, ge=0, description="Delivery pace (1.0 = on track, <1.0 = behind, >1.0 = ahead)"
)
pricing_model: str | None = Field(
None, description="Pricing model for this package during delivery (e.g., 'cpm', 'cpc', 'vpm', 'flat_rate')"
)
rate: float | None = Field(
None,
ge=0,
description="Pricing rate for this package during delivery (required if fixed pricing, null for auction-based)",
)
currency: str | None = Field(
None,
pattern=r"^[A-Z]{3}$",
description="ISO 4217 currency code for this package during delivery (e.g., USD, EUR, GBP)",
)
by_placement: list[PlacementBreakdown] | None = Field(
None,
description="Placement-level delivery breakdown (populated when reporting_dimensions includes 'placement')",
)
by_placement_truncated: bool | None = Field(
None,
description="True when by_placement was truncated by the requested limit; false when complete. "
"MUST be present whenever by_placement is present "
"(get-media-buy-delivery-response.json §by_placement_truncated; get_media_buy_delivery.mdx §Truncation).",
)
by_geo: list[GeoBreakdown] | None = Field(
None,
description="Geographic delivery breakdown (populated when reporting_dimensions includes 'geo'). "
"For metro/postal_area levels each entry declares the classification 'system' used.",
)
by_geo_truncated: bool | None = Field(
None,
description="True when by_geo was truncated by the requested limit; false when complete. "
"MUST be present whenever by_geo is present "
"(get-media-buy-delivery-response.json §by_geo_truncated; get_media_buy_delivery.mdx §Truncation).",
)
by_device_type: list[DeviceTypeBreakdown] | None = Field(
None,
description="Device-type delivery breakdown (populated when reporting_dimensions includes 'device_type'). "
"Entries cover device_type enum values: desktop, mobile, tablet, ctv, dooh, unknown.",
)
by_device_type_truncated: bool | None = Field(
None,
description="True when by_device_type was truncated by the requested limit; false when complete. "
"MUST be present whenever by_device_type is present "
"(get-media-buy-delivery-response.json §by_device_type_truncated; get_media_buy_delivery.mdx §Truncation).",
)
class DailyBreakdown(SalesAgentBaseModel):
"""Day-by-day delivery metrics.
Note: Does not yet extend library DailyBreakdownItem. Library also includes
conversions, conversion_value, roas, new_to_brand_rate fields.
"""
date: str = Field(description="Date (YYYY-MM-DD)", pattern=r"^\d{4}-\d{2}-\d{2}$")
impressions: float = Field(ge=0, description="Daily impressions")
spend: float = Field(ge=0, description="Daily spend")
# Status vocabulary of the AdCP delivery response. Re-export the pinned adcp
# library enum (Pattern #1: use the library type, never duplicate) rather than a
# hand-maintained Literal that had already drifted — it omitted "pending", which
# both the library enum and the pinned get-media-buy-delivery-response.json
# fixture list (as a legacy alias for pending_start). Wider than the media-buy
# lifecycle enum: delivery responses may additionally report "pending", "failed",
# and "reporting_delayed".
MediaBuyDeliveryStatus = LibraryMediaBuyDeliveryStatus
class MediaBuyDeliveryData(SalesAgentBaseModel):
"""AdCP-compliant delivery data for a single media buy.
Note: Does not yet extend library MediaBuyDelivery. Field names are
spec-aligned (completed_views); remaining work is switching DeliveryTotals
and PackageDelivery to extend their library counterparts.
TODO(salesagent-jz3y): Add buyer_campaign_ref field from adcp spec
(present in library MediaBuyDelivery but missing here).
"""
# use_enum_values keeps ``status`` (and ``pricing_model``) as their str
# values after validation, so the library MediaBuyDeliveryStatus enum
# validates the wire vocabulary while downstream ``status == "completed"``
# comparisons and JSON serialization stay string-native.
model_config = ConfigDict(extra=get_pydantic_extra_mode(), use_enum_values=True)
media_buy_id: str = Field(description="Publisher's media buy identifier")
status: MediaBuyDeliveryStatus = Field(
description="Current media buy status per the AdCP delivery-response taxonomy (get-media-buy-delivery-response.json)."
)
expected_availability: str | None = Field(
default=None,
description="When delayed data is expected to be available (only present when status is reporting_delayed)",
pattern=r"^\d{4}-\d{2}-\d{2}$",
)
is_adjusted: bool = Field(
description="Indicates this delivery contains updated data for a previously reported period. Buyer should replace previous period data with these totals.",
default=False,
)
pricing_model: PricingModel | None = Field(default=None, description="Pricing model for this media buy")
pricing_options: list[dict[str, Any]] | None = Field(
default=None,
description="Pricing options active for this media buy, linking back to PricingOption records",
)
totals: DeliveryTotals = Field(description="Aggregate metrics for this media buy across all packages")
by_package: list[PackageDelivery] = Field(description="Metrics broken down by package")
daily_breakdown: list[DailyBreakdown] | None = Field(None, description="Day-by-day delivery")
ext: dict[str, Any] = Field(
default_factory=dict,
description="AdCP extension object for adapter-specific data",
)
class ReportingPeriod(LibraryReportingPeriod):
"""Extends library ReportingPeriod.
Library provides: start (AwareDatetime), end (AwareDatetime).
Accepts datetime objects or ISO 8601 strings with timezone info.
"""
model_config = ConfigDict(extra=get_pydantic_extra_mode())
class AggregatedTotals(LibraryAggregatedTotals):
"""Combined metrics across all returned media buys.
Extends library type - all fields inherited from AdCP spec.
"""
pass # All fields inherited from library
# ---------------------------------------------------------------------------
# Response schemas
# ---------------------------------------------------------------------------
class GetMediaBuyDeliveryResponse(NestedModelSerializerMixin, LibraryGetMediaBuyDeliveryResponse):
"""Extends library GetMediaBuyDeliveryResponse with local overrides.
Library provides: reporting_period, currency, errors, context, ext,
notification_type, partial_data, sequence_number, unavailable_count,
next_expected_at -- all inherited from AdCP spec.
Local overrides:
- aggregated_totals: Required (library makes it optional)
- media_buy_deliveries: Uses local MediaBuyDeliveryData type
"""
model_config = ConfigDict(extra=get_pydantic_extra_mode())
aggregated_totals: AggregatedTotals = Field(..., description="Combined metrics across all returned media buys")
media_buy_deliveries: list[MediaBuyDeliveryData] = Field( # type: ignore[assignment]
..., description="Array of delivery data for each media buy"
)
def model_dump(self, **kwargs: Any) -> dict[str, Any]:
"""Override to ensure webhook metadata fields are present when notification_type is set.
The base AdCPBaseModel excludes None values, but the AdCP protocol requires
next_expected_at to be explicitly present (as null) when notification_type
is 'final' so consumers know no further reports are expected.
"""
result = super().model_dump(**kwargs)
if self.notification_type is not None and "next_expected_at" not in result:
result["next_expected_at"] = None
return result
def __str__(self) -> str:
"""Return human-readable summary message for protocol envelope."""
count = len(self.media_buy_deliveries)
if count == 0:
return "No delivery data found for the specified period."
elif count == 1:
return "Retrieved delivery data for 1 media buy."
return f"Retrieved delivery data for {count} media buys."
def webhook_payload(
self,
requested_metrics: list[str] | None = None,
) -> dict[str, Any]:
"""Serialize response as a webhook payload.
Webhook payloads differ from polling responses:
- ``aggregated_totals`` is excluded (polling-only field)
- When *requested_metrics* is provided, each media-buy ``totals``
dict is filtered to only include those metric keys.
Args:
requested_metrics: If provided, only these metric names are
kept in each ``totals`` dict. Non-metric keys (like
``media_buy_id``, ``status``) are never filtered.
Returns:
JSON-ready dict suitable for webhook POST body.
"""
data = self.model_dump(mode="json", exclude={"aggregated_totals"})
if requested_metrics is not None:
metrics_set = set(requested_metrics)
for delivery in data.get("media_buy_deliveries", []):
totals = delivery.get("totals")
if totals is not None:
filtered = {k: v for k, v in totals.items() if k in metrics_set}
delivery["totals"] = filtered
return data
# Deprecated - kept for backward compatibility
class GetAllMediaBuyDeliveryRequest(SalesAgentBaseModel):
"""DEPRECATED: Use GetMediaBuyDeliveryRequest with filter='all' instead."""
today: date
media_buy_ids: list[str] | None = None
class GetAllMediaBuyDeliveryResponse(NestedModelSerializerMixin, SalesAgentBaseModel):
"""DEPRECATED: Use GetMediaBuyDeliveryResponse instead."""
deliveries: list[MediaBuyDeliveryData]
total_spend: float
total_impressions: int
active_count: int
summary_date: date
# ---------------------------------------------------------------------------
# Adapter-specific schemas
# ---------------------------------------------------------------------------
class AdapterPackageDelivery(SalesAgentBaseModel):
package_id: str
impressions: int
spend: float
by_placement: list[dict[str, Any]] | None = None
by_geo: list[dict[str, Any]] | None = None
by_device_type: list[dict[str, Any]] | None = None
class AdapterGetMediaBuyDeliveryResponse(NestedModelSerializerMixin, SalesAgentBaseModel):
"""Response from adapter's get_media_buy_delivery method"""
media_buy_id: str
reporting_period: ReportingPeriod
totals: DeliveryTotals
by_package: list[AdapterPackageDelivery]
currency: str
daily_breakdown: list[dict] | None = None # Optional day-by-day delivery metrics
# ---------------------------------------------------------------------------
# Creative Delivery schemas (GH #1030)
# ---------------------------------------------------------------------------
class GetCreativeDeliveryRequest(SalesAgentBaseModel):
"""Request creative-level delivery metrics.
Flattened from the adcp library's union-based GetCreativeDeliveryRequest
(RootModel of 3 variants). At least one scoping filter is required:
media_buy_ids or creative_ids.
All fields mirror the adcp spec; this flat model is easier to work with
for MCP parameter expansion and validation.
"""
model_config = ConfigDict(extra=get_pydantic_extra_mode())
media_buy_ids: list[str] | None = Field(
None,
min_length=1,
description="Filter to specific media buys by publisher ID.",
)
creative_ids: list[str] | None = Field(
None,
min_length=1,
description="Filter to specific creatives by ID.",
)
account_id: str | None = Field(
None,
description="Account context for routing and scoping.",
)
start_date: str | None = Field(
None,
pattern=r"^\d{4}-\d{2}-\d{2}$",
description="Start date for delivery period (YYYY-MM-DD).",
)
end_date: str | None = Field(
None,
pattern=r"^\d{4}-\d{2}-\d{2}$",
description="End date for delivery period (YYYY-MM-DD).",
)
max_variants: int | None = Field(
None,
ge=1,
description="Maximum number of variants to return per creative.",
)
context: Any | None = Field(None)
class DeliveryMetrics(LibraryDeliveryMetrics):
"""Creative delivery metrics extending the adcp library type.
All fields inherited from AdCP spec: impressions, clicks, ctr, spend,
views, completed_views, completion_rate, conversions, roas, reach,
frequency, viewability, quartile_data, etc.
"""
pass # All fields inherited from library
class CreativeDeliveryData(SalesAgentBaseModel):
"""Delivery data for a single creative within a media buy."""
creative_id: str = Field(description="Creative identifier")
format_id: dict[str, Any] | None = Field(None, description="Format identifier (FormatId object)")
media_buy_id: str | None = Field(None, description="Media buy this creative is assigned to")
totals: DeliveryMetrics | None = Field(None, description="Aggregate delivery metrics for this creative")
variant_count: int | None = Field(None, ge=0, description="Total number of variants for this creative")
variants: list[dict[str, Any]] = Field(
default_factory=list,
description="Variant-level delivery data (initially empty, populated in follow-up)",
)
class GetCreativeDeliveryResponse(NestedModelSerializerMixin, LibraryGetCreativeDeliveryResponse):
"""Extends library GetCreativeDeliveryResponse.
Library provides: reporting_period, currency, creatives, errors,
pagination, media_buy_id, context, ext.
Local override:
- creatives: Uses local CreativeDeliveryData for consistent serialization
"""
model_config = ConfigDict(extra=get_pydantic_extra_mode())
creatives: list[CreativeDeliveryData] = Field( # type: ignore[assignment]
..., description="Array of creative delivery data"
)
def __str__(self) -> str:
"""Return human-readable summary message for protocol envelope."""
count = len(self.creatives)
if count == 0:
return "No creative delivery data found for the specified period."
elif count == 1:
return "Retrieved delivery data for 1 creative."
return f"Retrieved delivery data for {count} creatives."
class AdapterCreativeDeliveryItem(SalesAgentBaseModel):
"""Creative delivery data returned by an adapter."""
creative_id: str
media_buy_id: str | None = None
impressions: float = 0.0
clicks: float | None = None
spend: float | None = None
ctr: float | None = None
class AdapterGetCreativeDeliveryResponse(NestedModelSerializerMixin, SalesAgentBaseModel):
"""Response from adapter's get_creative_delivery method."""
creatives: list[AdapterCreativeDeliveryItem]
reporting_period: ReportingPeriod
currency: str