vatly-fluent-python 0.1.0a2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- vatly_fluent/__init__.py +64 -0
- vatly_fluent/builders.py +139 -0
- vatly_fluent/client.py +170 -0
- vatly_fluent/contracts.py +202 -0
- vatly_fluent/customers.py +133 -0
- vatly_fluent/handles.py +176 -0
- vatly_fluent/linkage.py +44 -0
- vatly_fluent/py.typed +1 -0
- vatly_fluent/webhooks.py +154 -0
- vatly_fluent_python-0.1.0a2.dist-info/METADATA +119 -0
- vatly_fluent_python-0.1.0a2.dist-info/RECORD +13 -0
- vatly_fluent_python-0.1.0a2.dist-info/WHEEL +4 -0
- vatly_fluent_python-0.1.0a2.dist-info/licenses/LICENSE +21 -0
vatly_fluent/__init__.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Vatly Fluent: builders, handles, driver contracts and signed webhook reactions."""
|
|
2
|
+
|
|
3
|
+
from .builders import CheckoutBuilder, CheckoutResult, SubscriptionBuilder
|
|
4
|
+
from .client import CheckoutResolution, TestHelpers, Vatly
|
|
5
|
+
from .contracts import (
|
|
6
|
+
CheckoutRecord,
|
|
7
|
+
CheckoutRecords,
|
|
8
|
+
CustomerBindings,
|
|
9
|
+
CustomerProfile,
|
|
10
|
+
DomainEvent,
|
|
11
|
+
EntityRef,
|
|
12
|
+
EventDispatcher,
|
|
13
|
+
FluentError,
|
|
14
|
+
LocalEvent,
|
|
15
|
+
LocalSubscription,
|
|
16
|
+
Repository,
|
|
17
|
+
ReversalRepository,
|
|
18
|
+
Stored,
|
|
19
|
+
SubscriptionState,
|
|
20
|
+
WebhookCalls,
|
|
21
|
+
WebhookReaction,
|
|
22
|
+
Wiring,
|
|
23
|
+
subscription_ends_at,
|
|
24
|
+
subscription_state,
|
|
25
|
+
)
|
|
26
|
+
from .customers import CustomerHandle, CustomerService
|
|
27
|
+
from .handles import OrderHandle, SubscriptionHandle
|
|
28
|
+
from .webhooks import WebhookProcessor
|
|
29
|
+
|
|
30
|
+
__version__ = "0.1.0a2"
|
|
31
|
+
|
|
32
|
+
__all__ = [
|
|
33
|
+
"Vatly",
|
|
34
|
+
"Wiring",
|
|
35
|
+
"CheckoutBuilder",
|
|
36
|
+
"CheckoutResult",
|
|
37
|
+
"SubscriptionBuilder",
|
|
38
|
+
"CustomerProfile",
|
|
39
|
+
"CustomerBindings",
|
|
40
|
+
"EntityRef",
|
|
41
|
+
"CheckoutRecord",
|
|
42
|
+
"CheckoutRecords",
|
|
43
|
+
"Stored",
|
|
44
|
+
"LocalSubscription",
|
|
45
|
+
"Repository",
|
|
46
|
+
"ReversalRepository",
|
|
47
|
+
"DomainEvent",
|
|
48
|
+
"EventDispatcher",
|
|
49
|
+
"LocalEvent",
|
|
50
|
+
"WebhookCalls",
|
|
51
|
+
"WebhookReaction",
|
|
52
|
+
"FluentError",
|
|
53
|
+
"SubscriptionState",
|
|
54
|
+
"subscription_ends_at",
|
|
55
|
+
"subscription_state",
|
|
56
|
+
"CheckoutResolution",
|
|
57
|
+
"TestHelpers",
|
|
58
|
+
"CustomerHandle",
|
|
59
|
+
"CustomerService",
|
|
60
|
+
"OrderHandle",
|
|
61
|
+
"SubscriptionHandle",
|
|
62
|
+
"WebhookProcessor",
|
|
63
|
+
"__version__",
|
|
64
|
+
]
|
vatly_fluent/builders.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
from collections.abc import Sequence
|
|
5
|
+
from copy import deepcopy
|
|
6
|
+
from datetime import datetime, timezone
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from pydantic import ValidationError
|
|
10
|
+
from typing_extensions import Self
|
|
11
|
+
from vatly import RequestOptions
|
|
12
|
+
from vatly.models import BillingAddress, Checkout, CheckoutProduct, CreateCheckoutRequest, Metadata
|
|
13
|
+
|
|
14
|
+
from .contracts import CheckoutRecord, CustomerProfile, EntityRef, FluentError, Wiring, required
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class CheckoutResult(Checkout):
|
|
18
|
+
def get_url(self) -> str:
|
|
19
|
+
return self.links.checkout_url.href
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class CheckoutBuilder:
|
|
23
|
+
def __init__(self, wiring: Wiring, profile: CustomerProfile | None = None) -> None:
|
|
24
|
+
self._wiring = wiring
|
|
25
|
+
self._entity: EntityRef | None = None
|
|
26
|
+
self._data: dict[str, Any] = {
|
|
27
|
+
"products": [],
|
|
28
|
+
"redirectUrlSuccess": wiring.redirect_url_success,
|
|
29
|
+
"redirectUrlCanceled": wiring.redirect_url_canceled,
|
|
30
|
+
}
|
|
31
|
+
if profile and profile.vatly_id:
|
|
32
|
+
self._data["customerId"] = profile.vatly_id
|
|
33
|
+
|
|
34
|
+
def for_entity(self, entity: EntityRef) -> Self:
|
|
35
|
+
"""Bind to an already-authorized entity through host-owned checkout records."""
|
|
36
|
+
self._entity = entity
|
|
37
|
+
return self
|
|
38
|
+
|
|
39
|
+
def with_redirect_url_success(self, url: str) -> Self:
|
|
40
|
+
self._data["redirectUrlSuccess"] = url
|
|
41
|
+
return self
|
|
42
|
+
|
|
43
|
+
def with_redirect_url_canceled(self, url: str) -> Self:
|
|
44
|
+
self._data["redirectUrlCanceled"] = url
|
|
45
|
+
return self
|
|
46
|
+
|
|
47
|
+
def with_metadata(self, metadata: Metadata | dict[str, Any] | None) -> Self:
|
|
48
|
+
self._data["metadata"] = (
|
|
49
|
+
metadata.model_dump(mode="json")
|
|
50
|
+
if isinstance(metadata, Metadata)
|
|
51
|
+
else deepcopy(metadata)
|
|
52
|
+
)
|
|
53
|
+
return self
|
|
54
|
+
|
|
55
|
+
def with_locale(self, locale: str | None) -> Self:
|
|
56
|
+
self._data["locale"] = locale
|
|
57
|
+
return self
|
|
58
|
+
|
|
59
|
+
def with_billing_address(self, address: BillingAddress | dict[str, Any]) -> Self:
|
|
60
|
+
self._data["billingAddress"] = (
|
|
61
|
+
address.model_dump(mode="json", by_alias=True, exclude_unset=True)
|
|
62
|
+
if isinstance(address, BillingAddress)
|
|
63
|
+
else deepcopy(address)
|
|
64
|
+
)
|
|
65
|
+
return self
|
|
66
|
+
|
|
67
|
+
def with_items(self, items: Sequence[CheckoutProduct | dict[str, Any]]) -> Self:
|
|
68
|
+
self._data["products"].extend(
|
|
69
|
+
item.model_dump(mode="json", by_alias=True, exclude_unset=True)
|
|
70
|
+
if isinstance(item, CheckoutProduct)
|
|
71
|
+
else deepcopy(item)
|
|
72
|
+
for item in items
|
|
73
|
+
)
|
|
74
|
+
return self
|
|
75
|
+
|
|
76
|
+
def with_testmode(self, testmode: bool) -> Self:
|
|
77
|
+
if testmode != (self._wiring.api.mode == "test"):
|
|
78
|
+
raise FluentError("Requested checkout mode does not match the API key")
|
|
79
|
+
return self
|
|
80
|
+
|
|
81
|
+
def in_testmode(self) -> Self:
|
|
82
|
+
return self.with_testmode(True)
|
|
83
|
+
|
|
84
|
+
def in_live_mode(self) -> Self:
|
|
85
|
+
return self.with_testmode(False)
|
|
86
|
+
|
|
87
|
+
def payload(self, overrides: dict[str, Any] | None = None) -> dict[str, Any]:
|
|
88
|
+
return deepcopy({**self._data, **(overrides or {})})
|
|
89
|
+
|
|
90
|
+
async def create(
|
|
91
|
+
self, overrides: dict[str, Any] | None = None, *, options: RequestOptions | None = None
|
|
92
|
+
) -> CheckoutResult:
|
|
93
|
+
records = required(self._wiring.checkouts, "checkouts") if self._entity else None
|
|
94
|
+
body = self.payload(overrides)
|
|
95
|
+
if (
|
|
96
|
+
not body.get("products")
|
|
97
|
+
or not body.get("redirectUrlSuccess")
|
|
98
|
+
or not body.get("redirectUrlCanceled")
|
|
99
|
+
):
|
|
100
|
+
raise FluentError("Products and both redirect URLs are required")
|
|
101
|
+
try:
|
|
102
|
+
request = CreateCheckoutRequest.model_validate(body)
|
|
103
|
+
except ValidationError as exc:
|
|
104
|
+
raise FluentError("Invalid checkout request") from exc
|
|
105
|
+
checkout = await self._wiring.api.checkouts.create(request, options=options)
|
|
106
|
+
if records is not None and self._entity is not None:
|
|
107
|
+
await records.record(CheckoutRecord(checkout.id, self._entity, checkout.testmode))
|
|
108
|
+
return CheckoutResult.model_validate(checkout.model_dump())
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class SubscriptionBuilder(CheckoutBuilder):
|
|
112
|
+
def __init__(self, wiring: Wiring, profile: CustomerProfile | None = None) -> None:
|
|
113
|
+
super().__init__(wiring, profile)
|
|
114
|
+
self._item: dict[str, Any] = {"id": "", "quantity": 1}
|
|
115
|
+
|
|
116
|
+
def to_plan(self, id: str) -> Self:
|
|
117
|
+
if not id:
|
|
118
|
+
raise FluentError("A subscription-plan ID is required")
|
|
119
|
+
self._item["id"] = id
|
|
120
|
+
return self
|
|
121
|
+
|
|
122
|
+
def with_quantity(self, quantity: int) -> Self:
|
|
123
|
+
if isinstance(quantity, bool) or not isinstance(quantity, int) or quantity < 1:
|
|
124
|
+
raise FluentError("Quantity must be a positive integer")
|
|
125
|
+
self._item["quantity"] = quantity
|
|
126
|
+
return self
|
|
127
|
+
|
|
128
|
+
def with_trial_days(self, days: int) -> Self:
|
|
129
|
+
if isinstance(days, bool) or not isinstance(days, int) or days < 1:
|
|
130
|
+
raise FluentError("Trial days must be a positive integer")
|
|
131
|
+
self._item["trialDays"] = days
|
|
132
|
+
return self
|
|
133
|
+
|
|
134
|
+
def with_trial_ends_at(self, date: datetime, *, now: datetime | None = None) -> Self:
|
|
135
|
+
current = now if now is not None else datetime.now(timezone.utc)
|
|
136
|
+
return self.with_trial_days(math.ceil((date - current).total_seconds() / 86400))
|
|
137
|
+
|
|
138
|
+
def payload(self, overrides: dict[str, Any] | None = None) -> dict[str, Any]:
|
|
139
|
+
return super().payload({"products": [self._item], **(overrides or {})})
|
vatly_fluent/client.py
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from vatly import RequestOptions, VatlyNotFoundError
|
|
8
|
+
from vatly.models import Order, Subscription
|
|
9
|
+
from vatly.resources import AsyncOneOffProducts, AsyncSubscriptionPlans, AsyncTestHelpers
|
|
10
|
+
|
|
11
|
+
from .builders import CheckoutBuilder, SubscriptionBuilder
|
|
12
|
+
from .contracts import CustomerProfile, FluentError, LocalSubscription, Wiring, required
|
|
13
|
+
from .customers import CustomerHandle, CustomerService
|
|
14
|
+
from .handles import OrderHandle, SubscriptionHandle
|
|
15
|
+
from .linkage import link_order
|
|
16
|
+
from .webhooks import WebhookProcessor
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class CheckoutResolution:
|
|
21
|
+
order: Order | None
|
|
22
|
+
subscriptions: tuple[Subscription, ...] = ()
|
|
23
|
+
pending_subscription_ids: tuple[str, ...] = ()
|
|
24
|
+
legacy_plan_ids: tuple[str, ...] = ()
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class TestHelpers:
|
|
28
|
+
def __init__(self, api: AsyncTestHelpers) -> None:
|
|
29
|
+
self._api = api
|
|
30
|
+
|
|
31
|
+
async def fast_forward_renewal(
|
|
32
|
+
self, id: str, body: dict[str, Any] | None = None, *, options: RequestOptions | None = None
|
|
33
|
+
) -> Subscription:
|
|
34
|
+
return await self._api.fast_forward_renewal(id, body or {}, options=options)
|
|
35
|
+
|
|
36
|
+
async def simulate_order_payment(
|
|
37
|
+
self, id: str, body: dict[str, Any], *, options: RequestOptions | None = None
|
|
38
|
+
) -> Order:
|
|
39
|
+
return await self._api.simulate_order_payment(id, body, options=options)
|
|
40
|
+
|
|
41
|
+
async def advance_renewal(
|
|
42
|
+
self, id: str, *, options: RequestOptions | None = None
|
|
43
|
+
) -> Subscription:
|
|
44
|
+
return await self.fast_forward_renewal(id, options=options)
|
|
45
|
+
|
|
46
|
+
async def force_renewal_paid(
|
|
47
|
+
self, id: str, *, options: RequestOptions | None = None
|
|
48
|
+
) -> Subscription:
|
|
49
|
+
return await self.fast_forward_renewal(id, {"paymentStatus": "paid"}, options=options)
|
|
50
|
+
|
|
51
|
+
async def force_renewal_failed(
|
|
52
|
+
self, id: str, failure_reason: str | None = None, *, options: RequestOptions | None = None
|
|
53
|
+
) -> Subscription:
|
|
54
|
+
body: dict[str, Any] = {"paymentStatus": "failed"}
|
|
55
|
+
if failure_reason is not None:
|
|
56
|
+
body["failureReason"] = failure_reason
|
|
57
|
+
return await self.fast_forward_renewal(id, body, options=options)
|
|
58
|
+
|
|
59
|
+
async def force_order_payment_paid(
|
|
60
|
+
self, id: str, *, options: RequestOptions | None = None
|
|
61
|
+
) -> Order:
|
|
62
|
+
return await self.simulate_order_payment(id, {"paymentStatus": "paid"}, options=options)
|
|
63
|
+
|
|
64
|
+
async def force_order_payment_failed(
|
|
65
|
+
self, id: str, failure_reason: str | None = None, *, options: RequestOptions | None = None
|
|
66
|
+
) -> Order:
|
|
67
|
+
body: dict[str, Any] = {"paymentStatus": "failed"}
|
|
68
|
+
if failure_reason is not None:
|
|
69
|
+
body["failureReason"] = failure_reason
|
|
70
|
+
return await self.simulate_order_payment(id, body, options=options)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class Vatly:
|
|
74
|
+
"""Composes an existing async SDK client; the caller owns its lifecycle."""
|
|
75
|
+
|
|
76
|
+
def __init__(self, wiring: Wiring) -> None:
|
|
77
|
+
self.wiring = wiring
|
|
78
|
+
self.api = wiring.api
|
|
79
|
+
self.customers = CustomerService(wiring)
|
|
80
|
+
|
|
81
|
+
def one_off_products(self) -> AsyncOneOffProducts:
|
|
82
|
+
return self.api.one_off_products
|
|
83
|
+
|
|
84
|
+
def subscription_plans(self) -> AsyncSubscriptionPlans:
|
|
85
|
+
return self.api.subscription_plans
|
|
86
|
+
|
|
87
|
+
def customer(self, id: str) -> CustomerHandle:
|
|
88
|
+
return CustomerHandle(self.wiring, id)
|
|
89
|
+
|
|
90
|
+
def checkout_builder(self, profile: CustomerProfile | None = None) -> CheckoutBuilder:
|
|
91
|
+
return CheckoutBuilder(self.wiring, profile)
|
|
92
|
+
|
|
93
|
+
def subscribe(self, profile: CustomerProfile | None = None) -> SubscriptionBuilder:
|
|
94
|
+
return SubscriptionBuilder(self.wiring, profile)
|
|
95
|
+
|
|
96
|
+
def subscription(self, record: LocalSubscription) -> SubscriptionHandle:
|
|
97
|
+
return SubscriptionHandle(self.wiring, record)
|
|
98
|
+
|
|
99
|
+
def order(self, id: str) -> OrderHandle:
|
|
100
|
+
return OrderHandle(self.wiring, id)
|
|
101
|
+
|
|
102
|
+
def webhook_processor(self) -> WebhookProcessor:
|
|
103
|
+
return WebhookProcessor(self.wiring)
|
|
104
|
+
|
|
105
|
+
def test_helpers(self) -> TestHelpers:
|
|
106
|
+
return TestHelpers(self.api.test_helpers)
|
|
107
|
+
|
|
108
|
+
async def customer_id_from_checkout(self, id: str) -> str | None:
|
|
109
|
+
"""Billing identity only. Never authorizes or assigns a host entity."""
|
|
110
|
+
try:
|
|
111
|
+
return (await self.api.checkouts.get(id)).customer_id
|
|
112
|
+
except VatlyNotFoundError:
|
|
113
|
+
return None
|
|
114
|
+
|
|
115
|
+
async def claim_customer_from_checkout(self, id: str, host_id: str) -> bool:
|
|
116
|
+
"""Call only after the host verifies checkout ownership."""
|
|
117
|
+
customer = await self.customer_id_from_checkout(id)
|
|
118
|
+
if not customer:
|
|
119
|
+
return False
|
|
120
|
+
await self.customers.attribute(customer, host_id)
|
|
121
|
+
return True
|
|
122
|
+
|
|
123
|
+
async def reconcile_checkout(self, id: str, *, attempts: int = 3) -> CheckoutResolution:
|
|
124
|
+
"""Explicit bounded reads for trial/initial-order IDs; does not grant access.
|
|
125
|
+
|
|
126
|
+
Caller authorizes the checkout and runs own-record writes in a transaction.
|
|
127
|
+
No customerId fallback and no plan->subscription guessing. A pending ID can
|
|
128
|
+
remain absent forever when the core deliberately skips subscription start.
|
|
129
|
+
"""
|
|
130
|
+
if isinstance(attempts, bool) or not isinstance(attempts, int) or not 1 <= attempts <= 10:
|
|
131
|
+
raise FluentError("attempts must be an integer between 1 and 10")
|
|
132
|
+
records = required(self.wiring.checkouts, "checkouts")
|
|
133
|
+
record = await records.find(id)
|
|
134
|
+
if record is None:
|
|
135
|
+
raise FluentError("No host-owned checkout record exists")
|
|
136
|
+
checkout = await self.api.checkouts.get(id)
|
|
137
|
+
if record.testmode != checkout.testmode or checkout.testmode != (self.api.mode == "test"):
|
|
138
|
+
raise FluentError("Checkout mode mismatch")
|
|
139
|
+
if not checkout.order_id:
|
|
140
|
+
return CheckoutResolution(None)
|
|
141
|
+
order = await self.api.orders.get(checkout.order_id)
|
|
142
|
+
await link_order(self.wiring, record, order)
|
|
143
|
+
found = []
|
|
144
|
+
pending = []
|
|
145
|
+
ids = dict.fromkeys(
|
|
146
|
+
line.product_id
|
|
147
|
+
for line in order.lines
|
|
148
|
+
if line.product_type == "subscription" and line.product_id
|
|
149
|
+
)
|
|
150
|
+
for sub_id in ids:
|
|
151
|
+
for attempt in range(attempts):
|
|
152
|
+
try:
|
|
153
|
+
subscription = await self.api.subscriptions.get(sub_id)
|
|
154
|
+
if subscription.testmode != record.testmode:
|
|
155
|
+
raise FluentError("Subscription mode mismatch")
|
|
156
|
+
found.append(subscription)
|
|
157
|
+
break
|
|
158
|
+
except VatlyNotFoundError:
|
|
159
|
+
if attempt == attempts - 1:
|
|
160
|
+
pending.append(sub_id)
|
|
161
|
+
else:
|
|
162
|
+
await asyncio.sleep(min(0.25 * 2**attempt, 2))
|
|
163
|
+
legacy = tuple(
|
|
164
|
+
dict.fromkeys(
|
|
165
|
+
line.product_id
|
|
166
|
+
for line in order.lines
|
|
167
|
+
if line.product_type == "subscription_plan" and line.product_id
|
|
168
|
+
)
|
|
169
|
+
)
|
|
170
|
+
return CheckoutResolution(order, tuple(found), tuple(pending), legacy)
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
"""Async, framework-neutral driver contracts. Hosts own storage and transactions."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Awaitable, Callable, Sequence
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from datetime import datetime, timezone
|
|
8
|
+
from typing import Any, Generic, Literal, Protocol, TypeVar
|
|
9
|
+
|
|
10
|
+
from pydantic import BaseModel, ConfigDict
|
|
11
|
+
from vatly import AsyncVatlyClient
|
|
12
|
+
from vatly.models import Chargeback, Order, Refund, Subscription
|
|
13
|
+
from vatly.webhooks import VatlyWebhookEvent
|
|
14
|
+
|
|
15
|
+
T = TypeVar("T")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class FluentError(Exception):
|
|
19
|
+
"""Invalid local input or missing wiring; SDK errors are not wrapped."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class EntityRef:
|
|
24
|
+
"""An authorized host billable: user, team, organization, purchase, etc."""
|
|
25
|
+
|
|
26
|
+
kind: str
|
|
27
|
+
id: str
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True)
|
|
31
|
+
class CustomerProfile:
|
|
32
|
+
vatly_id: str | None = None
|
|
33
|
+
email: str | None = None
|
|
34
|
+
name: str | None = None
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class Stored(BaseModel, Generic[T]):
|
|
38
|
+
model_config = ConfigDict(extra="forbid")
|
|
39
|
+
resource: T
|
|
40
|
+
entity: EntityRef | None = None
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class LocalSubscription(Stored[Subscription]):
|
|
44
|
+
ends_at: datetime | None = None
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def subscription_ends_at(
|
|
48
|
+
resource: Subscription, previous: datetime | None = None
|
|
49
|
+
) -> datetime | None:
|
|
50
|
+
"""Map lifecycle snapshots to access expiry, not cancellation request time.
|
|
51
|
+
|
|
52
|
+
Core's grace deadline is the trial/cycle end. canceledAt is raisedAt; the
|
|
53
|
+
internal ends_at is not exposed by the current API. Missing expiry fails
|
|
54
|
+
processing instead of silently granting unbounded access or ending it now.
|
|
55
|
+
"""
|
|
56
|
+
if resource.ended_at is not None:
|
|
57
|
+
return resource.ended_at
|
|
58
|
+
if resource.status == "on_grace_period":
|
|
59
|
+
# Historical dates and pre-fix cancellation timestamps are not deadlines.
|
|
60
|
+
cycle, renewed, trial, prior = (
|
|
61
|
+
end
|
|
62
|
+
if end is not None and (resource.canceled_at is None or end > resource.canceled_at)
|
|
63
|
+
else None
|
|
64
|
+
for end in (
|
|
65
|
+
resource.next_renewal_at,
|
|
66
|
+
resource.renewed_until,
|
|
67
|
+
resource.trial_until,
|
|
68
|
+
previous,
|
|
69
|
+
)
|
|
70
|
+
)
|
|
71
|
+
cycle = cycle or renewed
|
|
72
|
+
# Core chooses trial or cycle end using an onTrial flag absent from the API.
|
|
73
|
+
if trial is not None and cycle is not None and trial != cycle:
|
|
74
|
+
raise FluentError("Ambiguous grace deadline; reconcile before granting access")
|
|
75
|
+
if end := cycle or trial or prior:
|
|
76
|
+
return end
|
|
77
|
+
raise FluentError("Grace-period expiry is unavailable; reconcile before granting access")
|
|
78
|
+
return resource.canceled_at if resource.status == "canceled" else None
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@dataclass(frozen=True)
|
|
82
|
+
class CheckoutRecord:
|
|
83
|
+
checkout_id: str
|
|
84
|
+
entity: EntityRef
|
|
85
|
+
testmode: bool
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class CustomerBindings(Protocol):
|
|
89
|
+
"""Enforce uniqueness on both sides, scoped by tenant/storefront/mode."""
|
|
90
|
+
|
|
91
|
+
async def bind(self, vatly_id: str, host_id: str) -> None: ...
|
|
92
|
+
async def record(self, vatly_id: str) -> None: ...
|
|
93
|
+
async def vatly_customer_id_for(self, host_id: str) -> str | None: ...
|
|
94
|
+
async def host_customer_id_for(self, vatly_id: str) -> str | None: ...
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class CheckoutRecords(Protocol):
|
|
98
|
+
"""Immutable ownership from host records, NEVER inferred from customerId.
|
|
99
|
+
|
|
100
|
+
record/link must be idempotent for identical values and reject reassignment.
|
|
101
|
+
link and lookups are scoped to the wiring's tenant/storefront/mode.
|
|
102
|
+
"""
|
|
103
|
+
|
|
104
|
+
async def record(self, data: CheckoutRecord) -> None: ...
|
|
105
|
+
async def find(self, checkout_id: str) -> CheckoutRecord | None: ...
|
|
106
|
+
async def link(self, checkout_id: str, resource_type: str, resource_id: str) -> None: ...
|
|
107
|
+
async def find_for_resource(
|
|
108
|
+
self, resource_type: str, resource_id: str
|
|
109
|
+
) -> CheckoutRecord | None: ...
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class Repository(Protocol[T]):
|
|
113
|
+
async def find_by_vatly_id(self, id: str) -> T | None: ...
|
|
114
|
+
async def store(self, data: T) -> T | None:
|
|
115
|
+
"""Unique resource id required; None deliberately declines persistence."""
|
|
116
|
+
...
|
|
117
|
+
|
|
118
|
+
async def update(self, id: str, data: dict[str, Any]) -> T:
|
|
119
|
+
"""Omitted fields stay unchanged, explicit None clears a nullable field."""
|
|
120
|
+
...
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
class ReversalRepository(Repository[Stored[T]], Protocol[T]):
|
|
124
|
+
async def list_for_order(self, id: str) -> list[Stored[T]]: ...
|
|
125
|
+
async def list_for_customer(self, id: str) -> list[Stored[T]]: ...
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
@dataclass(frozen=True)
|
|
129
|
+
class LocalEvent:
|
|
130
|
+
event_name: Literal["local.order_created", "local.subscription_created"]
|
|
131
|
+
object: Stored[Order] | LocalSubscription
|
|
132
|
+
known: Literal[True] = True
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
DomainEvent = VatlyWebhookEvent | LocalEvent
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
class EventDispatcher(Protocol):
|
|
139
|
+
async def dispatch(self, event: DomainEvent) -> None: ...
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
class WebhookReaction(Protocol):
|
|
143
|
+
def supports(self, event: VatlyWebhookEvent) -> bool: ...
|
|
144
|
+
async def handle(self, event: VatlyWebhookEvent) -> None: ...
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
class WebhookCalls(Protocol):
|
|
148
|
+
async def process(self, event: VatlyWebhookEvent, work: Callable[[], Awaitable[None]]) -> bool:
|
|
149
|
+
"""Dedup signed id + retain envelope + run work + mark processed atomically.
|
|
150
|
+
|
|
151
|
+
Share the transaction with repositories, checkout records, bindings and
|
|
152
|
+
outbox. Return False for committed duplicates; rollback everything on error.
|
|
153
|
+
"""
|
|
154
|
+
...
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
@dataclass
|
|
158
|
+
class Wiring:
|
|
159
|
+
api: AsyncVatlyClient
|
|
160
|
+
redirect_url_success: str = ""
|
|
161
|
+
redirect_url_canceled: str = ""
|
|
162
|
+
webhook_secret: str | Sequence[str] | None = None
|
|
163
|
+
bindings: CustomerBindings | None = None
|
|
164
|
+
checkouts: CheckoutRecords | None = None
|
|
165
|
+
subscriptions: Repository[LocalSubscription] | None = None
|
|
166
|
+
orders: Repository[Stored[Order]] | None = None
|
|
167
|
+
refunds: ReversalRepository[Refund] | None = None
|
|
168
|
+
chargebacks: ReversalRepository[Chargeback] | None = None
|
|
169
|
+
webhook_calls: WebhookCalls | None = None
|
|
170
|
+
events: EventDispatcher | None = None
|
|
171
|
+
additional_webhook_reactions: Sequence[WebhookReaction] = field(default_factory=tuple)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def required(value: T | None, name: str) -> T:
|
|
175
|
+
if value is None:
|
|
176
|
+
raise FluentError(f"Missing wiring: {name}")
|
|
177
|
+
return value
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
@dataclass(frozen=True)
|
|
181
|
+
class SubscriptionState:
|
|
182
|
+
cancelled: bool
|
|
183
|
+
on_grace_period: bool
|
|
184
|
+
active: bool
|
|
185
|
+
valid: bool
|
|
186
|
+
recurring: bool
|
|
187
|
+
ended: bool
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def subscription_state(ends_at: datetime | None, now: datetime | None = None) -> SubscriptionState:
|
|
191
|
+
"""PHP endsAt predicates, NOT an entitlement policy or substitute for status."""
|
|
192
|
+
current = now if now is not None else datetime.now(timezone.utc)
|
|
193
|
+
cancelled = ends_at is not None
|
|
194
|
+
grace = ends_at is not None and ends_at > current
|
|
195
|
+
return SubscriptionState(
|
|
196
|
+
cancelled,
|
|
197
|
+
grace,
|
|
198
|
+
not cancelled or grace,
|
|
199
|
+
not cancelled or grace,
|
|
200
|
+
not cancelled,
|
|
201
|
+
cancelled and not grace,
|
|
202
|
+
)
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import AsyncIterator
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from typing_extensions import Self
|
|
7
|
+
from vatly import RequestOptions
|
|
8
|
+
from vatly.models import CreatePortalSessionRequest, Customer, PortalSession, UpdateCustomerRequest
|
|
9
|
+
|
|
10
|
+
from .contracts import CustomerProfile, FluentError, Wiring, required
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class CustomerHandle:
|
|
14
|
+
def __init__(self, wiring: Wiring, id: str) -> None:
|
|
15
|
+
self._wiring = wiring
|
|
16
|
+
self.id = id
|
|
17
|
+
self._cached: Customer | None = None
|
|
18
|
+
|
|
19
|
+
async def model(self) -> Customer:
|
|
20
|
+
if self._cached is None:
|
|
21
|
+
self._cached = await self._wiring.api.customers.get(self.id)
|
|
22
|
+
return self._cached
|
|
23
|
+
|
|
24
|
+
async def name(self) -> str | None:
|
|
25
|
+
return (await self.model()).name
|
|
26
|
+
|
|
27
|
+
async def email(self) -> str:
|
|
28
|
+
return (await self.model()).email
|
|
29
|
+
|
|
30
|
+
async def identity(self) -> dict[str, str | None]:
|
|
31
|
+
customer = await self.model()
|
|
32
|
+
return {"name": customer.name, "email": customer.email}
|
|
33
|
+
|
|
34
|
+
async def sync(self) -> Self:
|
|
35
|
+
self._cached = await self._wiring.api.customers.get(self.id)
|
|
36
|
+
return self
|
|
37
|
+
|
|
38
|
+
async def update(
|
|
39
|
+
self, data: UpdateCustomerRequest | dict[str, Any], *, options: RequestOptions | None = None
|
|
40
|
+
) -> Self:
|
|
41
|
+
self._cached = await self._wiring.api.customers.update(self.id, data, options=options)
|
|
42
|
+
return self
|
|
43
|
+
|
|
44
|
+
async def portal_session(
|
|
45
|
+
self,
|
|
46
|
+
body: CreatePortalSessionRequest | dict[str, Any] | None = None,
|
|
47
|
+
*,
|
|
48
|
+
options: RequestOptions | None = None,
|
|
49
|
+
) -> PortalSession:
|
|
50
|
+
return await self._wiring.api.customers.create_portal_session(
|
|
51
|
+
self.id, body or {}, options=options
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class CustomerService:
|
|
56
|
+
def __init__(self, wiring: Wiring) -> None:
|
|
57
|
+
self._wiring = wiring
|
|
58
|
+
|
|
59
|
+
async def _create(
|
|
60
|
+
self, profile: CustomerProfile, extra: dict[str, Any] | None, options: RequestOptions | None
|
|
61
|
+
) -> Customer:
|
|
62
|
+
body = {"name": profile.name, **(extra or {})}
|
|
63
|
+
body["email"] = body.get("email") or profile.email
|
|
64
|
+
if not body["email"]:
|
|
65
|
+
raise FluentError("An email is required to create a customer")
|
|
66
|
+
return await self._wiring.api.customers.create(body, options=options)
|
|
67
|
+
|
|
68
|
+
async def create_for(
|
|
69
|
+
self,
|
|
70
|
+
host_id: str,
|
|
71
|
+
profile: CustomerProfile,
|
|
72
|
+
extra: dict[str, Any] | None = None,
|
|
73
|
+
*,
|
|
74
|
+
options: RequestOptions | None = None,
|
|
75
|
+
) -> Customer:
|
|
76
|
+
bindings = required(self._wiring.bindings, "bindings")
|
|
77
|
+
if await bindings.vatly_customer_id_for(host_id):
|
|
78
|
+
raise FluentError("Host customer is already bound")
|
|
79
|
+
customer = await self._create(profile, extra, options)
|
|
80
|
+
await self.attribute(customer.id, host_id)
|
|
81
|
+
return customer
|
|
82
|
+
|
|
83
|
+
async def create_unattributed(
|
|
84
|
+
self,
|
|
85
|
+
profile: CustomerProfile,
|
|
86
|
+
extra: dict[str, Any] | None = None,
|
|
87
|
+
*,
|
|
88
|
+
options: RequestOptions | None = None,
|
|
89
|
+
) -> Customer:
|
|
90
|
+
bindings = required(self._wiring.bindings, "bindings")
|
|
91
|
+
customer = await self._create(profile, extra, options)
|
|
92
|
+
await bindings.record(customer.id)
|
|
93
|
+
return customer
|
|
94
|
+
|
|
95
|
+
async def attribute(self, vatly_id: str, host_id: str) -> None:
|
|
96
|
+
bindings = required(self._wiring.bindings, "bindings")
|
|
97
|
+
old_vatly = await bindings.vatly_customer_id_for(host_id)
|
|
98
|
+
old_host = await bindings.host_customer_id_for(vatly_id)
|
|
99
|
+
if (old_vatly and old_vatly != vatly_id) or (old_host and old_host != host_id):
|
|
100
|
+
raise FluentError("Customer is already bound to a different identity")
|
|
101
|
+
await bindings.bind(vatly_id, host_id)
|
|
102
|
+
|
|
103
|
+
async def find_by_host_customer_id(self, host_id: str) -> Customer | None:
|
|
104
|
+
id = await required(self._wiring.bindings, "bindings").vatly_customer_id_for(host_id)
|
|
105
|
+
return await self._wiring.api.customers.get(id) if id else None
|
|
106
|
+
|
|
107
|
+
async def find_by_vatly_customer_id(self, id: str) -> Customer:
|
|
108
|
+
return await self._wiring.api.customers.get(id)
|
|
109
|
+
|
|
110
|
+
def find_by_email(
|
|
111
|
+
self, email: str, params: dict[str, Any] | None = None
|
|
112
|
+
) -> AsyncIterator[Customer]:
|
|
113
|
+
return self._wiring.api.customers.list_all({**(params or {}), "email": email})
|
|
114
|
+
|
|
115
|
+
async def find_one_by_email(self, email: str) -> Customer | None:
|
|
116
|
+
async for customer in self.find_by_email(email):
|
|
117
|
+
return customer
|
|
118
|
+
return None
|
|
119
|
+
|
|
120
|
+
async def identity(self, id: str) -> dict[str, str | None]:
|
|
121
|
+
return await CustomerHandle(self._wiring, id).identity()
|
|
122
|
+
|
|
123
|
+
async def update(
|
|
124
|
+
self,
|
|
125
|
+
id: str,
|
|
126
|
+
body: UpdateCustomerRequest | dict[str, Any],
|
|
127
|
+
*,
|
|
128
|
+
options: RequestOptions | None = None,
|
|
129
|
+
) -> Customer:
|
|
130
|
+
return await self._wiring.api.customers.update(id, body, options=options)
|
|
131
|
+
|
|
132
|
+
async def host_customer_id_for(self, id: str) -> str | None:
|
|
133
|
+
return await required(self._wiring.bindings, "bindings").host_customer_id_for(id)
|
vatly_fluent/handles.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Sequence
|
|
4
|
+
from decimal import Decimal
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from typing_extensions import Self
|
|
8
|
+
from vatly import RequestOptions
|
|
9
|
+
from vatly.models import Chargeback, Order, OrderLine, Refund, Subscription
|
|
10
|
+
|
|
11
|
+
from .contracts import (
|
|
12
|
+
LocalSubscription,
|
|
13
|
+
Stored,
|
|
14
|
+
SubscriptionState,
|
|
15
|
+
Wiring,
|
|
16
|
+
required,
|
|
17
|
+
subscription_ends_at,
|
|
18
|
+
subscription_state,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class SubscriptionHandle:
|
|
23
|
+
def __init__(self, wiring: Wiring, record: LocalSubscription) -> None:
|
|
24
|
+
self._wiring = wiring
|
|
25
|
+
self._record = record
|
|
26
|
+
|
|
27
|
+
def model(self) -> LocalSubscription:
|
|
28
|
+
return self._record
|
|
29
|
+
|
|
30
|
+
def state(self) -> SubscriptionState:
|
|
31
|
+
return subscription_state(self._record.ends_at)
|
|
32
|
+
|
|
33
|
+
async def _save(self, resource: Subscription) -> Self:
|
|
34
|
+
self._record = await required(self._wiring.subscriptions, "subscriptions").update(
|
|
35
|
+
self._record.resource.id,
|
|
36
|
+
{"resource": resource, "ends_at": subscription_ends_at(resource, self._record.ends_at)},
|
|
37
|
+
)
|
|
38
|
+
return self
|
|
39
|
+
|
|
40
|
+
async def swap(
|
|
41
|
+
self,
|
|
42
|
+
plan_id: str,
|
|
43
|
+
body: dict[str, Any] | None = None,
|
|
44
|
+
*,
|
|
45
|
+
options: RequestOptions | None = None,
|
|
46
|
+
) -> Self:
|
|
47
|
+
required(self._wiring.subscriptions, "subscriptions")
|
|
48
|
+
response = await self._wiring.api.subscriptions.update(
|
|
49
|
+
self._record.resource.id,
|
|
50
|
+
{**(body or {}), "subscriptionPlanId": plan_id},
|
|
51
|
+
options=options,
|
|
52
|
+
)
|
|
53
|
+
return await self._save(response)
|
|
54
|
+
|
|
55
|
+
async def swap_and_invoice(
|
|
56
|
+
self,
|
|
57
|
+
plan_id: str,
|
|
58
|
+
body: dict[str, Any] | None = None,
|
|
59
|
+
*,
|
|
60
|
+
options: RequestOptions | None = None,
|
|
61
|
+
) -> Self:
|
|
62
|
+
return await self.swap(
|
|
63
|
+
plan_id,
|
|
64
|
+
{**(body or {}), "applyImmediately": True, "invoiceImmediately": True},
|
|
65
|
+
options=options,
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
async def swap_without_charge(
|
|
69
|
+
self,
|
|
70
|
+
plan_id: str,
|
|
71
|
+
body: dict[str, Any] | None = None,
|
|
72
|
+
*,
|
|
73
|
+
options: RequestOptions | None = None,
|
|
74
|
+
) -> Self:
|
|
75
|
+
return await self.swap(
|
|
76
|
+
plan_id,
|
|
77
|
+
{**(body or {}), "applyImmediately": True, "prorationCharge": False},
|
|
78
|
+
options=options,
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
async def resume(self, *, options: RequestOptions | None = None) -> Self:
|
|
82
|
+
required(self._wiring.subscriptions, "subscriptions")
|
|
83
|
+
response = await self._wiring.api.subscriptions.resume(
|
|
84
|
+
self._record.resource.id, options=options
|
|
85
|
+
)
|
|
86
|
+
return await self._save(response)
|
|
87
|
+
|
|
88
|
+
async def cancel(
|
|
89
|
+
self, *, immediately: bool | None = None, options: RequestOptions | None = None
|
|
90
|
+
) -> None:
|
|
91
|
+
params = {"immediately": immediately} if immediately is not None else {}
|
|
92
|
+
await self._wiring.api.subscriptions.cancel(
|
|
93
|
+
self._record.resource.id, params, options=options
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
async def sync(self) -> Self:
|
|
97
|
+
required(self._wiring.subscriptions, "subscriptions")
|
|
98
|
+
response = await self._wiring.api.subscriptions.get(self._record.resource.id)
|
|
99
|
+
return await self._save(response)
|
|
100
|
+
|
|
101
|
+
async def scheduled_update(self) -> Any:
|
|
102
|
+
return (await self._wiring.api.subscriptions.get(self._record.resource.id)).scheduled_update
|
|
103
|
+
|
|
104
|
+
async def has_scheduled_update(self) -> bool:
|
|
105
|
+
return (await self.scheduled_update()) is not None
|
|
106
|
+
|
|
107
|
+
async def cancellation_reason(self) -> str | None:
|
|
108
|
+
return (
|
|
109
|
+
await self._wiring.api.subscriptions.get(self._record.resource.id)
|
|
110
|
+
).cancellation_reason
|
|
111
|
+
|
|
112
|
+
async def update_billing(
|
|
113
|
+
self, body: dict[str, Any] | None = None, *, options: RequestOptions | None = None
|
|
114
|
+
) -> str:
|
|
115
|
+
payload = {
|
|
116
|
+
"redirectUrlSuccess": self._wiring.redirect_url_success,
|
|
117
|
+
"redirectUrlCanceled": self._wiring.redirect_url_canceled,
|
|
118
|
+
**(body or {}),
|
|
119
|
+
}
|
|
120
|
+
from .contracts import FluentError
|
|
121
|
+
|
|
122
|
+
if not payload["redirectUrlSuccess"] or not payload["redirectUrlCanceled"]:
|
|
123
|
+
raise FluentError("Both billing redirect URLs are required")
|
|
124
|
+
return (
|
|
125
|
+
await self._wiring.api.subscriptions.create_billing_update_link(
|
|
126
|
+
self._record.resource.id, payload, options=options
|
|
127
|
+
)
|
|
128
|
+
).href
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
class OrderHandle:
|
|
132
|
+
def __init__(self, wiring: Wiring, id: str) -> None:
|
|
133
|
+
self._wiring = wiring
|
|
134
|
+
self.id = id
|
|
135
|
+
self._cached: Order | None = None
|
|
136
|
+
|
|
137
|
+
async def model(self) -> Order:
|
|
138
|
+
if self._cached is None:
|
|
139
|
+
self._cached = await self._wiring.api.orders.get(self.id)
|
|
140
|
+
return self._cached
|
|
141
|
+
|
|
142
|
+
async def sync(self) -> Self:
|
|
143
|
+
self._cached = await self._wiring.api.orders.get(self.id)
|
|
144
|
+
return self
|
|
145
|
+
|
|
146
|
+
async def invoice_url(self) -> str | None:
|
|
147
|
+
link = (await self.model()).links.customer_invoice
|
|
148
|
+
return link.href if link else None
|
|
149
|
+
|
|
150
|
+
async def reversed_subtotal(self) -> Decimal:
|
|
151
|
+
return Decimal((await self.model()).reversed_subtotal.root.value)
|
|
152
|
+
|
|
153
|
+
async def refundable_subtotal(self) -> Decimal:
|
|
154
|
+
return Decimal((await self.model()).refundable_subtotal.root.value)
|
|
155
|
+
|
|
156
|
+
async def is_reversed(self) -> bool:
|
|
157
|
+
return await self.reversed_subtotal() > 0
|
|
158
|
+
|
|
159
|
+
async def is_fully_reversed(self) -> bool:
|
|
160
|
+
return await self.is_reversed() and await self.refundable_subtotal() == 0
|
|
161
|
+
|
|
162
|
+
async def is_partially_reversed(self) -> bool:
|
|
163
|
+
return await self.is_reversed() and not await self.is_fully_reversed()
|
|
164
|
+
|
|
165
|
+
async def refunds(self) -> list[Stored[Refund]]:
|
|
166
|
+
return await self._wiring.refunds.list_for_order(self.id) if self._wiring.refunds else []
|
|
167
|
+
|
|
168
|
+
async def chargebacks(self) -> list[Stored[Chargeback]]:
|
|
169
|
+
return (
|
|
170
|
+
await self._wiring.chargebacks.list_for_order(self.id)
|
|
171
|
+
if self._wiring.chargebacks
|
|
172
|
+
else []
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
async def lines(self) -> Sequence[OrderLine]:
|
|
176
|
+
return (await self.model()).lines
|
vatly_fluent/linkage.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Own-record linkage, shared by signed reactions and explicit reconciliation."""
|
|
2
|
+
|
|
3
|
+
from vatly.models import Order
|
|
4
|
+
|
|
5
|
+
from .contracts import CheckoutRecord, EntityRef, FluentError, Wiring, required
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def preserve_entity(existing: EntityRef | None, candidate: EntityRef | None) -> EntityRef | None:
|
|
9
|
+
if existing is not None and candidate is not None and existing != candidate:
|
|
10
|
+
raise FluentError("Refusing to reassign a billing resource to another entity")
|
|
11
|
+
return existing if existing is not None else candidate
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
async def checkout_for(wiring: Wiring, resource_type: str, id: str) -> CheckoutRecord | None:
|
|
15
|
+
if wiring.checkouts is None:
|
|
16
|
+
return None
|
|
17
|
+
record = await wiring.checkouts.find_for_resource(resource_type, id)
|
|
18
|
+
if record is not None and record.testmode != (wiring.api.mode == "test"):
|
|
19
|
+
raise FluentError("Checkout record mode does not match the API key")
|
|
20
|
+
return record
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
async def link_order(wiring: Wiring, record: CheckoutRecord, order: Order) -> None:
|
|
24
|
+
if record.testmode != order.testmode or order.testmode != (wiring.api.mode == "test"):
|
|
25
|
+
raise FluentError("Order and checkout record modes do not match")
|
|
26
|
+
records = required(wiring.checkouts, "checkouts")
|
|
27
|
+
await records.link(record.checkout_id, "order", order.id)
|
|
28
|
+
if wiring.orders:
|
|
29
|
+
existing = await wiring.orders.find_by_vatly_id(order.id)
|
|
30
|
+
if existing:
|
|
31
|
+
await wiring.orders.update(
|
|
32
|
+
order.id, {"entity": preserve_entity(existing.entity, record.entity)}
|
|
33
|
+
)
|
|
34
|
+
for line in order.lines:
|
|
35
|
+
# Never mistake historical subscription_plan IDs for subscription IDs.
|
|
36
|
+
if line.product_type != "subscription" or not line.product_id:
|
|
37
|
+
continue
|
|
38
|
+
await records.link(record.checkout_id, "subscription", line.product_id)
|
|
39
|
+
if wiring.subscriptions:
|
|
40
|
+
sub = await wiring.subscriptions.find_by_vatly_id(line.product_id)
|
|
41
|
+
if sub:
|
|
42
|
+
await wiring.subscriptions.update(
|
|
43
|
+
line.product_id, {"entity": preserve_entity(sub.entity, record.entity)}
|
|
44
|
+
)
|
vatly_fluent/py.typed
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# PEP 561: inline type information is included.
|
vatly_fluent/webhooks.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
"""Verified signed snapshots only: built-in reactions never perform API reads."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, TypeVar
|
|
6
|
+
|
|
7
|
+
from vatly.models import Chargeback, Checkout, Order, Refund, Subscription
|
|
8
|
+
from vatly.webhooks import KnownWebhookEvent, construct_webhook_event
|
|
9
|
+
|
|
10
|
+
from .contracts import (
|
|
11
|
+
FluentError,
|
|
12
|
+
LocalEvent,
|
|
13
|
+
LocalSubscription,
|
|
14
|
+
Repository,
|
|
15
|
+
Stored,
|
|
16
|
+
Wiring,
|
|
17
|
+
required,
|
|
18
|
+
subscription_ends_at,
|
|
19
|
+
)
|
|
20
|
+
from .linkage import checkout_for, link_order, preserve_entity
|
|
21
|
+
|
|
22
|
+
R = TypeVar("R", Order, Refund, Chargeback)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class WebhookProcessor:
|
|
26
|
+
def __init__(self, wiring: Wiring) -> None:
|
|
27
|
+
self._wiring = wiring
|
|
28
|
+
required(wiring.webhook_secret, "webhook_secret")
|
|
29
|
+
required(wiring.webhook_calls, "webhook_calls")
|
|
30
|
+
|
|
31
|
+
async def handle(
|
|
32
|
+
self,
|
|
33
|
+
raw_body: bytes | str,
|
|
34
|
+
signature_header: str | None,
|
|
35
|
+
*,
|
|
36
|
+
tolerance: float = 300,
|
|
37
|
+
now: float | None = None,
|
|
38
|
+
) -> bool:
|
|
39
|
+
event = construct_webhook_event(
|
|
40
|
+
raw_body,
|
|
41
|
+
signature_header,
|
|
42
|
+
required(self._wiring.webhook_secret, "webhook_secret"),
|
|
43
|
+
tolerance=tolerance,
|
|
44
|
+
now=now,
|
|
45
|
+
)
|
|
46
|
+
if event.testmode != (self._wiring.api.mode == "test"):
|
|
47
|
+
raise FluentError("Webhook mode does not match the API key")
|
|
48
|
+
|
|
49
|
+
async def work() -> None:
|
|
50
|
+
if event.known:
|
|
51
|
+
await self._react(event)
|
|
52
|
+
for reaction in self._wiring.additional_webhook_reactions:
|
|
53
|
+
if reaction.supports(event):
|
|
54
|
+
await reaction.handle(event)
|
|
55
|
+
if self._wiring.events:
|
|
56
|
+
await self._wiring.events.dispatch(event)
|
|
57
|
+
|
|
58
|
+
return await required(self._wiring.webhook_calls, "webhook_calls").process(event, work)
|
|
59
|
+
|
|
60
|
+
async def _persist(
|
|
61
|
+
self, repository: Repository[Stored[R]], resource: R, resource_type: str
|
|
62
|
+
) -> tuple[bool, Stored[R] | None]:
|
|
63
|
+
checkout = await checkout_for(self._wiring, resource_type, resource.id)
|
|
64
|
+
if isinstance(resource, (Refund, Chargeback)):
|
|
65
|
+
checkout = await checkout_for(self._wiring, "order", resource.original_order_id)
|
|
66
|
+
candidate = checkout.entity if checkout else None
|
|
67
|
+
existing = await repository.find_by_vatly_id(resource.id)
|
|
68
|
+
if existing:
|
|
69
|
+
return False, await repository.update(
|
|
70
|
+
resource.id,
|
|
71
|
+
{"resource": resource, "entity": preserve_entity(existing.entity, candidate)},
|
|
72
|
+
)
|
|
73
|
+
record = await repository.store(Stored[R](resource=resource, entity=candidate))
|
|
74
|
+
return record is not None, record
|
|
75
|
+
|
|
76
|
+
async def _react(self, event: KnownWebhookEvent) -> None:
|
|
77
|
+
wiring = self._wiring
|
|
78
|
+
resource = event.object
|
|
79
|
+
name = event.event_name
|
|
80
|
+
# Pydantic narrows object by resource, not by the envelope entityType.
|
|
81
|
+
if name.startswith("subscription."):
|
|
82
|
+
if not isinstance(resource, Subscription):
|
|
83
|
+
raise FluentError("Subscription event has a non-subscription object")
|
|
84
|
+
if not wiring.subscriptions or name == "subscription.update_scheduled":
|
|
85
|
+
return
|
|
86
|
+
existing = await wiring.subscriptions.find_by_vatly_id(resource.id)
|
|
87
|
+
if existing is None and name != "subscription.started":
|
|
88
|
+
return
|
|
89
|
+
checkout = await checkout_for(wiring, "subscription", resource.id)
|
|
90
|
+
entity = checkout.entity if checkout else None
|
|
91
|
+
if existing:
|
|
92
|
+
# Match JS's incremental mandate semantics; sync() reconciles removal.
|
|
93
|
+
snapshot = (
|
|
94
|
+
resource
|
|
95
|
+
if resource.mandate is not None
|
|
96
|
+
else resource.model_copy(update={"mandate": existing.resource.mandate})
|
|
97
|
+
)
|
|
98
|
+
fields: dict[str, Any] = {
|
|
99
|
+
"resource": snapshot,
|
|
100
|
+
"entity": preserve_entity(existing.entity, entity),
|
|
101
|
+
"ends_at": subscription_ends_at(resource, existing.ends_at),
|
|
102
|
+
}
|
|
103
|
+
await wiring.subscriptions.update(resource.id, fields)
|
|
104
|
+
else:
|
|
105
|
+
local = await wiring.subscriptions.store(
|
|
106
|
+
LocalSubscription(
|
|
107
|
+
resource=resource,
|
|
108
|
+
entity=entity,
|
|
109
|
+
ends_at=subscription_ends_at(resource),
|
|
110
|
+
)
|
|
111
|
+
)
|
|
112
|
+
if local and wiring.events:
|
|
113
|
+
await wiring.events.dispatch(LocalEvent("local.subscription_created", local))
|
|
114
|
+
elif name in {"order.paid", "order.payment_failed", "order.canceled"}:
|
|
115
|
+
if not isinstance(resource, Order):
|
|
116
|
+
raise FluentError("Order event has a non-order object")
|
|
117
|
+
checkout = await checkout_for(wiring, "order", resource.id)
|
|
118
|
+
if checkout:
|
|
119
|
+
await link_order(wiring, checkout, resource)
|
|
120
|
+
if not wiring.orders:
|
|
121
|
+
return
|
|
122
|
+
if name == "order.canceled":
|
|
123
|
+
existing_order = await wiring.orders.find_by_vatly_id(resource.id)
|
|
124
|
+
if existing_order:
|
|
125
|
+
await wiring.orders.update(resource.id, {"resource": resource})
|
|
126
|
+
else:
|
|
127
|
+
created, record = await self._persist(wiring.orders, resource, "order")
|
|
128
|
+
if created and record and name == "order.paid" and wiring.events:
|
|
129
|
+
await wiring.events.dispatch(LocalEvent("local.order_created", record))
|
|
130
|
+
elif name.startswith("refund."):
|
|
131
|
+
if not isinstance(resource, Refund):
|
|
132
|
+
raise FluentError("Refund event has a non-refund object")
|
|
133
|
+
if wiring.refunds:
|
|
134
|
+
await self._persist(wiring.refunds, resource, "refund")
|
|
135
|
+
elif name in {"order.chargeback_received", "order.chargeback_reversed"}:
|
|
136
|
+
if not isinstance(resource, Chargeback):
|
|
137
|
+
raise FluentError("Chargeback event has a non-chargeback object")
|
|
138
|
+
if wiring.chargebacks:
|
|
139
|
+
await self._persist(wiring.chargebacks, resource, "chargeback")
|
|
140
|
+
elif name == "checkout.paid":
|
|
141
|
+
if not isinstance(resource, Checkout):
|
|
142
|
+
raise FluentError("Checkout event has a non-checkout object")
|
|
143
|
+
if not wiring.checkouts or not resource.order_id:
|
|
144
|
+
return
|
|
145
|
+
checkout_record = await wiring.checkouts.find(resource.id)
|
|
146
|
+
if checkout_record is None:
|
|
147
|
+
return
|
|
148
|
+
if checkout_record.testmode != resource.testmode:
|
|
149
|
+
raise FluentError("Checkout record mode mismatch")
|
|
150
|
+
await wiring.checkouts.link(resource.id, "order", resource.order_id)
|
|
151
|
+
if wiring.orders:
|
|
152
|
+
order = await wiring.orders.find_by_vatly_id(resource.order_id)
|
|
153
|
+
if order:
|
|
154
|
+
await link_order(wiring, checkout_record, order.resource)
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: vatly-fluent-python
|
|
3
|
+
Version: 0.1.0a2
|
|
4
|
+
Summary: Framework-independent fluent billing integrations built on the Vatly Python SDK
|
|
5
|
+
Project-URL: Homepage, https://github.com/vatly/vatly-fluent-python
|
|
6
|
+
Project-URL: Documentation, https://docs.vatly.com
|
|
7
|
+
Project-URL: Issues, https://github.com/vatly/vatly-fluent-python/issues
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Typing :: Typed
|
|
13
|
+
Requires-Python: >=3.10
|
|
14
|
+
Requires-Dist: vatly-api-python==0.1.0a2
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
|
|
17
|
+
# Vatly Fluent for Python
|
|
18
|
+
|
|
19
|
+
> **Alpha — under active development. Every alpha release may include breaking changes. Pin exact versions during alpha.**
|
|
20
|
+
|
|
21
|
+
Integrate Vatly billing without tying your application to a framework or database.
|
|
22
|
+
Fluent adds chainable checkout/subscription builders, customer and subscription
|
|
23
|
+
handles, pluggable persistence, and a signed webhook-to-domain-event pipeline on
|
|
24
|
+
top of `vatly-api-python`. Your application owns authentication, entitlements, storage,
|
|
25
|
+
transactions and jobs. Python 3.10+, fully typed, **async-first**.
|
|
26
|
+
|
|
27
|
+
## Install
|
|
28
|
+
|
|
29
|
+
Once both packages are published:
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
pip install vatly-fluent-python==0.1.0a2 vatly-api-python==0.1.0a2
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Nothing is published yet. For development, run `.agents/setup` or `uv sync --locked`.
|
|
36
|
+
The versioned wheel under `vendor/` bootstraps the unpublished SDK for uv only;
|
|
37
|
+
normal package metadata depends on the exact SDK version from PyPI. It is not
|
|
38
|
+
copied into Fluent's wheel. See [provenance](vendor/README.md).
|
|
39
|
+
|
|
40
|
+
## First checkout
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
from vatly import AsyncVatlyClient, RequestOptions
|
|
44
|
+
from vatly_fluent import Vatly, Wiring
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
async def start_subscription(plan_id: str, purchase_id: str):
|
|
48
|
+
async with AsyncVatlyClient() as api: # reads VATLY_API_KEY
|
|
49
|
+
vatly = Vatly(
|
|
50
|
+
Wiring(
|
|
51
|
+
api=api,
|
|
52
|
+
redirect_url_success="https://app.example.com/billing/return",
|
|
53
|
+
redirect_url_canceled="https://app.example.com/billing/canceled",
|
|
54
|
+
)
|
|
55
|
+
)
|
|
56
|
+
checkout = await (
|
|
57
|
+
vatly.subscribe()
|
|
58
|
+
.to_plan(plan_id)
|
|
59
|
+
.with_quantity(3)
|
|
60
|
+
.with_trial_days(14)
|
|
61
|
+
.with_metadata({"purchaseId": purchase_id})
|
|
62
|
+
.create(options=RequestOptions(idempotency_key=f"subscribe:{purchase_id}"))
|
|
63
|
+
)
|
|
64
|
+
return checkout.get_url()
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
This creates a **checkout**, not a subscription. Confirm payment through signed
|
|
68
|
+
webhooks, not redirects. No API calls happen until `create()`. Use a new builder
|
|
69
|
+
per purchase and persist a stable operation ID before sending. SDK errors pass
|
|
70
|
+
through unchanged; `FluentError` means invalid local input or missing wiring.
|
|
71
|
+
|
|
72
|
+
## Connect your own entities and storage
|
|
73
|
+
|
|
74
|
+
Wire `CheckoutRecords`, `Repository[LocalSubscription]`, `Repository[Stored[Order]]`,
|
|
75
|
+
and `WebhookCalls` to your application's database. For entity-linked checkouts:
|
|
76
|
+
|
|
77
|
+
```python
|
|
78
|
+
from vatly_fluent import EntityRef
|
|
79
|
+
|
|
80
|
+
# In an authorized handler, with vatly.wiring.checkouts configured:
|
|
81
|
+
builder = vatly.subscribe().to_plan(plan_id).for_entity(EntityRef("team", team_id))
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Ownership follows **your stored checkout → order → subscription links**. It never
|
|
85
|
+
falls back to `customerId`, which is only billing identity and may be shared or null.
|
|
86
|
+
Metadata is correlation data, not authorization. A signed webhook authenticates
|
|
87
|
+
Vatly's snapshot; it does not authorize a browser-provided entity ID.
|
|
88
|
+
|
|
89
|
+
Initial order lines may carry `productType="subscription"` and the intended
|
|
90
|
+
subscription ID (core PR #2910). Historical `subscription_plan` lines remain plan
|
|
91
|
+
references. Fluent never guesses a subscription from a plan or quantity.
|
|
92
|
+
`reconcile_checkout()` handles bounded 404 recovery and returns unresolved IDs;
|
|
93
|
+
an intended ID alone is not evidence of active service.
|
|
94
|
+
|
|
95
|
+
## Learn the integration
|
|
96
|
+
|
|
97
|
+
- [Getting started](docs/README.md) and [configuration](docs/Configuration.md)
|
|
98
|
+
- [Checkouts](docs/Checkouts.md), [customers](docs/Customers.md), [customer portal](docs/CustomerPortal.md)
|
|
99
|
+
- [Subscriptions](docs/Subscriptions.md) and [orders](docs/Orders.md)
|
|
100
|
+
- [Driver contracts](docs/CoreConcepts.md) and [transactional webhooks](docs/Webhooks.md)
|
|
101
|
+
- [Testing](docs/Testing.md), [porting decisions](PORTING.md), [release notes](CHANGELOG.md)
|
|
102
|
+
- [SQLite driver example](examples/sqlite_driver.py), with atomic dedup, rollback and outbox tests
|
|
103
|
+
|
|
104
|
+
## Develop
|
|
105
|
+
|
|
106
|
+
```bash
|
|
107
|
+
uv sync --locked
|
|
108
|
+
uv run ruff check .
|
|
109
|
+
uv run ruff format --check .
|
|
110
|
+
uv run mypy
|
|
111
|
+
uv run pytest
|
|
112
|
+
uv build
|
|
113
|
+
uv run twine check dist/*
|
|
114
|
+
uv run python scripts/check_package.py
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
CI runs these checks across Python 3.10–3.14. Release workflows are prepared but
|
|
118
|
+
require PyPI trusted-publisher configuration and an explicitly published GitHub
|
|
119
|
+
release. No release is triggered by pushing `main`.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
vatly_fluent/__init__.py,sha256=Ddwt04pRKSMG3sz7_SNkUBSxdBPIU_yKZXjiKNeRLbs,1474
|
|
2
|
+
vatly_fluent/builders.py,sha256=lMMp2Zl5N04O8u924u6kLVmLAeQFFwS_ABQ8y3ltB4E,5460
|
|
3
|
+
vatly_fluent/client.py,sha256=9uj9pz_PR62FQWJNY040PFYY1URBrWcqr_6qN4KAmF4,7036
|
|
4
|
+
vatly_fluent/contracts.py,sha256=ckqIx8UjtQJoPF-_INE_Ob8nSDZ5X4kA8ztpIjyLnwE,6828
|
|
5
|
+
vatly_fluent/customers.py,sha256=p8fPmSzCCiTgthQVuaz2SILkEG2FFqA6cluRFuOLmRY,4991
|
|
6
|
+
vatly_fluent/handles.py,sha256=ShdMn5Y_npbit5G-6pLRMbDnjh-BLY2NPut-u25k9Qg,5999
|
|
7
|
+
vatly_fluent/linkage.py,sha256=m0NfuwZAABLDdSoIZONSaTkRxuzdhnrGTT4a-P8IK6I,2106
|
|
8
|
+
vatly_fluent/py.typed,sha256=tc5JXk4VYZ8tnN0wyF81ld4VcYEESJaH--LRtuJjR4M,48
|
|
9
|
+
vatly_fluent/webhooks.py,sha256=ShyEyaAAcgfUf6PW2_HarPPAd61AFs3AxIqFS2HHq6w,6931
|
|
10
|
+
vatly_fluent_python-0.1.0a2.dist-info/METADATA,sha256=1qrLgpsJ6F6HGsNYqgZr_ap3xdH7XXzuAwBgZ-2_jmU,4845
|
|
11
|
+
vatly_fluent_python-0.1.0a2.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
|
12
|
+
vatly_fluent_python-0.1.0a2.dist-info/licenses/LICENSE,sha256=CkjDnWn3u8SlJD-QfG6Bd_2O7ZtuzM0nzfpy9E-AQsw,1062
|
|
13
|
+
vatly_fluent_python-0.1.0a2.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Vatly
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|