bucli 0.6.0__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.
- bucli/__init__.py +52 -0
- bucli/_version.py +1 -0
- bucli/client.py +274 -0
- bucli/constants.py +92 -0
- bucli/contrib/__init__.py +1 -0
- bucli/contrib/django/__init__.py +6 -0
- bucli/contrib/django/access.py +99 -0
- bucli/contrib/django/admin.py +19 -0
- bucli/contrib/django/apps.py +8 -0
- bucli/contrib/django/conf.py +140 -0
- bucli/contrib/django/exceptions.py +17 -0
- bucli/contrib/django/management/__init__.py +0 -0
- bucli/contrib/django/management/commands/__init__.py +0 -0
- bucli/contrib/django/management/commands/bucli_flush_usage.py +18 -0
- bucli/contrib/django/management/commands/bucli_sync.py +66 -0
- bucli/contrib/django/metering.py +137 -0
- bucli/contrib/django/migrations/0001_initial.py +102 -0
- bucli/contrib/django/migrations/0002_billingaccount_bucli_updated_at.py +15 -0
- bucli/contrib/django/migrations/0003_pendingusage.py +40 -0
- bucli/contrib/django/migrations/__init__.py +0 -0
- bucli/contrib/django/models.py +122 -0
- bucli/contrib/django/services.py +617 -0
- bucli/contrib/django/signals.py +22 -0
- bucli/contrib/django/urls.py +11 -0
- bucli/contrib/django/views.py +50 -0
- bucli/contrib/django/webhooks.py +236 -0
- bucli/errors.py +193 -0
- bucli/keys.py +18 -0
- bucli/metering.py +331 -0
- bucli/objects.py +168 -0
- bucli/py.typed +0 -0
- bucli/resources.py +1002 -0
- bucli/webhook.py +136 -0
- bucli-0.6.0.dist-info/METADATA +541 -0
- bucli-0.6.0.dist-info/RECORD +37 -0
- bucli-0.6.0.dist-info/WHEEL +4 -0
- bucli-0.6.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,617 @@
|
|
|
1
|
+
"""What the SaaS calls: subscribe, open the portal, change plan, cancel, sync.
|
|
2
|
+
|
|
3
|
+
Every function takes the SaaS's account (an instance of ``BUCLI_ACCOUNT_MODEL``)
|
|
4
|
+
and talks to Bucli OUTSIDE any database transaction; the local copy is written
|
|
5
|
+
only by ``store_subscription``, from an object Bucli just answered.
|
|
6
|
+
|
|
7
|
+
Nothing here activates a plan from ``success_url``: the activation comes from
|
|
8
|
+
the webhook (``views.BucliWebhookView``) or from ``sync``.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import datetime
|
|
14
|
+
import logging
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from django.apps import apps
|
|
18
|
+
from django.core.exceptions import ValidationError
|
|
19
|
+
from django.db import transaction
|
|
20
|
+
from django.utils import timezone
|
|
21
|
+
|
|
22
|
+
from bucli.client import Bucli
|
|
23
|
+
from bucli.constants import ENDED_STATUSES, RUNNING_STATUSES
|
|
24
|
+
from bucli.contrib.django import conf
|
|
25
|
+
from bucli.contrib.django.exceptions import AlreadySubscribed, NotSubscribed, UnknownPrice
|
|
26
|
+
from bucli.contrib.django.models import BillingAccount
|
|
27
|
+
from bucli.contrib.django.signals import subscription_changed
|
|
28
|
+
from bucli.errors import InvalidRequestError
|
|
29
|
+
from bucli.objects import BucliObject
|
|
30
|
+
|
|
31
|
+
logger = logging.getLogger("bucli.contrib.django")
|
|
32
|
+
|
|
33
|
+
#: The fields of the local copy whose change fires ``subscription_changed``.
|
|
34
|
+
TRACKED_FIELDS = (
|
|
35
|
+
"bucli_subscription_id",
|
|
36
|
+
"bucli_customer_id",
|
|
37
|
+
"status",
|
|
38
|
+
"price_id",
|
|
39
|
+
"plan",
|
|
40
|
+
"pending_price_id",
|
|
41
|
+
"current_period_end",
|
|
42
|
+
"trial_end",
|
|
43
|
+
"cancel_at_period_end",
|
|
44
|
+
"items",
|
|
45
|
+
"livemode",
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
# ---------------------------------------------------------------------------
|
|
50
|
+
# Helpers
|
|
51
|
+
# ---------------------------------------------------------------------------
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def ref(value: Any) -> str:
|
|
55
|
+
"""The id of a related field, expanded (``{"id": ...}``) or not."""
|
|
56
|
+
if isinstance(value, dict):
|
|
57
|
+
return value.get("id") or ""
|
|
58
|
+
return value or ""
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def parse_datetime(value: Any) -> datetime.datetime | None:
|
|
62
|
+
if not value:
|
|
63
|
+
return None
|
|
64
|
+
if isinstance(value, datetime.datetime):
|
|
65
|
+
return value
|
|
66
|
+
if isinstance(value, int | float):
|
|
67
|
+
return datetime.datetime.fromtimestamp(value, tz=datetime.UTC)
|
|
68
|
+
parsed = datetime.datetime.fromisoformat(str(value).replace("Z", "+00:00"))
|
|
69
|
+
if timezone.is_naive(parsed):
|
|
70
|
+
parsed = parsed.replace(tzinfo=datetime.UTC)
|
|
71
|
+
return parsed
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
#: The metadata key that names the SaaS account on Bucli's objects
|
|
75
|
+
#: (``"tenants.tenant:42"``): the customers and checkouts ``start_checkout``
|
|
76
|
+
#: creates carry it, and an import file should put it on each subscription.
|
|
77
|
+
ACCOUNT_METADATA_KEY = "bucli_account"
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def account_label(account) -> str:
|
|
81
|
+
return f"{account._meta.label_lower}:{account.pk}"
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def account_from_label(label: str):
|
|
85
|
+
"""The SaaS account a ``bucli_account`` label names, or ``None``."""
|
|
86
|
+
model_label, sep, pk = (label or "").rpartition(":")
|
|
87
|
+
if not sep or not pk or model_label != conf.account_model_label().lower():
|
|
88
|
+
return None
|
|
89
|
+
model = apps.get_model(conf.account_model_label())
|
|
90
|
+
try:
|
|
91
|
+
return model._default_manager.filter(pk=pk).first()
|
|
92
|
+
except (ValueError, TypeError, ValidationError):
|
|
93
|
+
return None
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _client(client: Bucli | None) -> Bucli:
|
|
97
|
+
return client or conf.get_client()
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def get_billing_account(account) -> BillingAccount:
|
|
101
|
+
"""The ``BillingAccount`` of ``account`` (or itself), created when missing."""
|
|
102
|
+
if isinstance(account, BillingAccount):
|
|
103
|
+
return account
|
|
104
|
+
try:
|
|
105
|
+
# The instance cached on ``account.bucli_billing``, re-read: what the
|
|
106
|
+
# services store on it is what ``access.has_access(account)`` reads next.
|
|
107
|
+
billing = account.bucli_billing
|
|
108
|
+
billing.refresh_from_db()
|
|
109
|
+
except BillingAccount.DoesNotExist:
|
|
110
|
+
billing, _ = BillingAccount.objects.get_or_create(account=account)
|
|
111
|
+
account.bucli_billing = billing
|
|
112
|
+
return billing
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def subscription_items(subscription: dict) -> list[dict]:
|
|
116
|
+
items = subscription.get("items") or {}
|
|
117
|
+
return list(items.get("data") or []) if isinstance(items, dict) else []
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def base_item(subscription: dict, plans: dict[str, str] | None = None) -> tuple[dict | None, str]:
|
|
121
|
+
"""``(item, price_id)`` of the item that sets the plan: the first whose price is
|
|
122
|
+
in ``BUCLI_PRICE_PLANS``, else the subscription's ``price`` (its first item)."""
|
|
123
|
+
plans = conf.price_plans() if plans is None else plans
|
|
124
|
+
items = subscription_items(subscription)
|
|
125
|
+
for item in items:
|
|
126
|
+
price_id = ref(item.get("price"))
|
|
127
|
+
if price_id in plans:
|
|
128
|
+
return item, price_id
|
|
129
|
+
first = items[0] if items else None
|
|
130
|
+
return first, ref(subscription.get("price")) or (ref(first.get("price")) if first else "")
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _snapshot(billing: BillingAccount) -> dict[str, Any]:
|
|
134
|
+
return {field: getattr(billing, field) for field in TRACKED_FIELDS}
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _should_track(billing: BillingAccount, subscription: dict) -> bool:
|
|
138
|
+
"""A subscription other than the tracked one replaces it only when it runs,
|
|
139
|
+
or when the tracked one is over (an old canceled subscription never
|
|
140
|
+
overwrites the active one)."""
|
|
141
|
+
current = billing.bucli_subscription_id
|
|
142
|
+
if not current or current == subscription.get("id"):
|
|
143
|
+
return True
|
|
144
|
+
if subscription.get("status") in RUNNING_STATUSES:
|
|
145
|
+
return True
|
|
146
|
+
return billing.status in ENDED_STATUSES or not billing.status
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _apply(billing: BillingAccount, subscription: dict) -> None:
|
|
150
|
+
plans = conf.price_plans()
|
|
151
|
+
_item, price_id = base_item(subscription, plans)
|
|
152
|
+
billing.bucli_subscription_id = subscription.get("id") or ""
|
|
153
|
+
billing.bucli_customer_id = ref(subscription.get("customer")) or billing.bucli_customer_id
|
|
154
|
+
billing.status = subscription.get("status") or ""
|
|
155
|
+
billing.price_id = price_id
|
|
156
|
+
billing.plan = plans.get(price_id, "")
|
|
157
|
+
if price_id and price_id not in plans:
|
|
158
|
+
logger.warning("Bucli: price %s of subscription %s is not in BUCLI_PRICE_PLANS", price_id, billing.pk)
|
|
159
|
+
billing.pending_price_id = ref(subscription.get("pending_price"))
|
|
160
|
+
billing.current_period_end = parse_datetime(subscription.get("current_period_end"))
|
|
161
|
+
billing.trial_end = parse_datetime(subscription.get("trial_end"))
|
|
162
|
+
billing.cancel_at_period_end = bool(subscription.get("cancel_at_period_end"))
|
|
163
|
+
billing.livemode = bool(subscription.get("livemode"))
|
|
164
|
+
billing.bucli_updated_at = parse_datetime(subscription.get("updated"))
|
|
165
|
+
billing.items = [
|
|
166
|
+
{
|
|
167
|
+
"id": item.get("id"),
|
|
168
|
+
"price": ref(item.get("price")),
|
|
169
|
+
"quantity": item.get("quantity"),
|
|
170
|
+
"plan": plans.get(ref(item.get("price"))),
|
|
171
|
+
}
|
|
172
|
+
for item in subscription_items(subscription)
|
|
173
|
+
]
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
# ---------------------------------------------------------------------------
|
|
177
|
+
# The one writer of the local copy
|
|
178
|
+
# ---------------------------------------------------------------------------
|
|
179
|
+
|
|
180
|
+
#: ``store_subscription`` outcomes.
|
|
181
|
+
APPLIED = "applied"
|
|
182
|
+
UNCHANGED = "unchanged"
|
|
183
|
+
STALE = "stale"
|
|
184
|
+
NOT_TRACKED = "not_tracked"
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _freshness(billing: BillingAccount, subscription: dict) -> int | None:
|
|
188
|
+
"""How ``subscription`` compares with the local copy of the SAME
|
|
189
|
+
subscription by Bucli's ``updated``: ``1`` newer, ``0`` same moment,
|
|
190
|
+
``-1`` older; ``None`` when it cannot be told (another subscription, or a
|
|
191
|
+
side without ``updated``)."""
|
|
192
|
+
if not billing.bucli_subscription_id or billing.bucli_subscription_id != subscription.get("id"):
|
|
193
|
+
return None
|
|
194
|
+
try:
|
|
195
|
+
incoming = parse_datetime(subscription.get("updated"))
|
|
196
|
+
except (TypeError, ValueError):
|
|
197
|
+
return None
|
|
198
|
+
stored = billing.bucli_updated_at
|
|
199
|
+
if incoming is None or stored is None:
|
|
200
|
+
return None
|
|
201
|
+
return (incoming > stored) - (incoming < stored)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def store_subscription(billing: BillingAccount, subscription: dict, *, sequence: int | None = None) -> str:
|
|
205
|
+
"""Write ``subscription`` (fresh from Bucli) on the local copy, under the row's lock.
|
|
206
|
+
|
|
207
|
+
Bucli's ``updated`` orders the copies of one subscription: one OLDER than
|
|
208
|
+
the local copy is ``STALE`` — never overwrites it, from an event or from
|
|
209
|
+
a sync —, a newer one always applies. When ``updated`` cannot tell (the
|
|
210
|
+
same second, another subscription, an answer without it), ``sequence``
|
|
211
|
+
does: an event older than the last applied one is ``STALE`` (the stored
|
|
212
|
+
copy was fetched after a later event, so it already includes this
|
|
213
|
+
change). A sync passes no sequence. Fires ``subscription_changed`` after
|
|
214
|
+
the commit when something changed."""
|
|
215
|
+
now = timezone.now()
|
|
216
|
+
with transaction.atomic():
|
|
217
|
+
locked = BillingAccount.objects.select_for_update().get(pk=billing.pk)
|
|
218
|
+
freshness = _freshness(locked, subscription)
|
|
219
|
+
if freshness == -1:
|
|
220
|
+
return STALE
|
|
221
|
+
if freshness != 1 and sequence is not None and sequence < locked.last_event_sequence:
|
|
222
|
+
return STALE
|
|
223
|
+
if not _should_track(locked, subscription):
|
|
224
|
+
return NOT_TRACKED
|
|
225
|
+
before = _snapshot(locked)
|
|
226
|
+
_apply(locked, subscription)
|
|
227
|
+
if sequence is not None:
|
|
228
|
+
locked.last_event_sequence = max(sequence, locked.last_event_sequence)
|
|
229
|
+
locked.last_event_at = now
|
|
230
|
+
locked.last_synced_at = now
|
|
231
|
+
locked.save()
|
|
232
|
+
after = _snapshot(locked)
|
|
233
|
+
for field in (
|
|
234
|
+
*TRACKED_FIELDS,
|
|
235
|
+
"bucli_updated_at",
|
|
236
|
+
"last_event_sequence",
|
|
237
|
+
"last_event_at",
|
|
238
|
+
"last_synced_at",
|
|
239
|
+
"updated_at",
|
|
240
|
+
):
|
|
241
|
+
setattr(billing, field, getattr(locked, field))
|
|
242
|
+
if before == after:
|
|
243
|
+
return UNCHANGED
|
|
244
|
+
|
|
245
|
+
def notify() -> None:
|
|
246
|
+
results = subscription_changed.send_robust(
|
|
247
|
+
sender=BillingAccount,
|
|
248
|
+
account=locked.account,
|
|
249
|
+
billing_account=locked,
|
|
250
|
+
previous_status=before["status"],
|
|
251
|
+
status=after["status"],
|
|
252
|
+
previous_plan=before["plan"],
|
|
253
|
+
plan=after["plan"],
|
|
254
|
+
)
|
|
255
|
+
for receiver, result in results:
|
|
256
|
+
if isinstance(result, Exception):
|
|
257
|
+
logger.error("Bucli: subscription_changed receiver %r failed: %s", receiver, result)
|
|
258
|
+
|
|
259
|
+
transaction.on_commit(notify)
|
|
260
|
+
return APPLIED
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
# ---------------------------------------------------------------------------
|
|
264
|
+
# What the SaaS calls
|
|
265
|
+
# ---------------------------------------------------------------------------
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _check_price(price_id: str) -> None:
|
|
269
|
+
if price_id not in conf.price_plans():
|
|
270
|
+
raise UnknownPrice(f"El precio {price_id} no está en BUCLI_PRICE_PLANS.")
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _find_customer(api: Bucli, *, external_id: str | None, email: str) -> str:
|
|
274
|
+
"""The id of the customer with that ``external_id`` or, without one, that
|
|
275
|
+
e-mail — or ``""``."""
|
|
276
|
+
found = (
|
|
277
|
+
api.customers.list(external_id=external_id, limit=1)
|
|
278
|
+
if external_id
|
|
279
|
+
else api.customers.list(email=email, limit=1)
|
|
280
|
+
)
|
|
281
|
+
return found.data[0]["id"] if found.data else ""
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def ensure_customer(
|
|
285
|
+
account,
|
|
286
|
+
email: str,
|
|
287
|
+
*,
|
|
288
|
+
name: str | None = None,
|
|
289
|
+
external_id: str | None = None,
|
|
290
|
+
phone: str | None = None,
|
|
291
|
+
fiscal: dict[str, Any] | None = None,
|
|
292
|
+
client: Bucli | None = None,
|
|
293
|
+
) -> BillingAccount:
|
|
294
|
+
"""The account's Bucli customer: the linked one, the one found (by
|
|
295
|
+
``external_id`` when given — one customer per account, two companies of
|
|
296
|
+
one owner never mixed — else by e-mail) or a new one. Saves the link.
|
|
297
|
+
|
|
298
|
+
``fiscal`` is the customer's data for the electronic invoice (see
|
|
299
|
+
``DATOS-DEL-CLIENTE.md``): sent when the customer is created; an existing
|
|
300
|
+
customer gets it with ``sync_customer``."""
|
|
301
|
+
billing = get_billing_account(account)
|
|
302
|
+
if billing.bucli_customer_id:
|
|
303
|
+
return billing
|
|
304
|
+
if external_id is not None:
|
|
305
|
+
external_id = str(external_id)
|
|
306
|
+
api = _client(client)
|
|
307
|
+
customer_id = _find_customer(api, external_id=external_id, email=email)
|
|
308
|
+
if not customer_id:
|
|
309
|
+
metadata = {ACCOUNT_METADATA_KEY: account_label(billing.account)}
|
|
310
|
+
try:
|
|
311
|
+
customer_id = api.customers.create(
|
|
312
|
+
email=email, name=name, external_id=external_id, phone=phone, fiscal=fiscal, metadata=metadata
|
|
313
|
+
)["id"]
|
|
314
|
+
except InvalidRequestError as error:
|
|
315
|
+
if error.code != "resource_already_exists":
|
|
316
|
+
raise
|
|
317
|
+
customer_id = _find_customer(api, external_id=external_id, email=email)
|
|
318
|
+
if not customer_id:
|
|
319
|
+
raise
|
|
320
|
+
BillingAccount.objects.filter(pk=billing.pk).update(bucli_customer_id=customer_id, updated_at=timezone.now())
|
|
321
|
+
billing.bucli_customer_id = customer_id
|
|
322
|
+
return billing
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
#: What ``sync_customer`` may change on the Bucli customer.
|
|
326
|
+
CUSTOMER_FIELDS = ("email", "name", "phone", "fiscal")
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def sync_customer(account, *, client: Bucli | None = None, **fields: Any) -> BucliObject | None:
|
|
330
|
+
"""Send the account's current data to its Bucli customer: ``email``,
|
|
331
|
+
``name``, ``phone`` and ``fiscal`` (whole: it replaces the previous one).
|
|
332
|
+
``None`` = not sent (an account whose fiscal data are still incomplete
|
|
333
|
+
sends no ``fiscal``). Call it after the account's billing data change
|
|
334
|
+
(from a task, after the commit). Without a linked customer it does
|
|
335
|
+
nothing (``ensure_customer`` sends the data when the customer is
|
|
336
|
+
created)."""
|
|
337
|
+
unknown = sorted(set(fields) - set(CUSTOMER_FIELDS))
|
|
338
|
+
if unknown:
|
|
339
|
+
raise ValueError(f"sync_customer no envía «{unknown[0]}»: solo {', '.join(CUSTOMER_FIELDS)}.")
|
|
340
|
+
billing = get_billing_account(account)
|
|
341
|
+
if not billing.bucli_customer_id or not fields:
|
|
342
|
+
return None
|
|
343
|
+
params = {key: value for key, value in fields.items() if value is not None}
|
|
344
|
+
if not params:
|
|
345
|
+
return None
|
|
346
|
+
return _client(client).customers.update(billing.bucli_customer_id, **params)
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def _line_items(items: Any) -> list[dict[str, Any]]:
|
|
350
|
+
"""``items`` as Bucli's ``line_items``: ``"price_…"``, ``("price_…", 3)`` or
|
|
351
|
+
``{"price": "price_…", "quantity": 3}`` each (quantity 1 by default)."""
|
|
352
|
+
lines = []
|
|
353
|
+
for item in items:
|
|
354
|
+
if isinstance(item, str):
|
|
355
|
+
price, quantity = item, None
|
|
356
|
+
elif isinstance(item, dict):
|
|
357
|
+
price, quantity = item.get("price"), item.get("quantity")
|
|
358
|
+
else:
|
|
359
|
+
price, quantity = item
|
|
360
|
+
if not price:
|
|
361
|
+
raise ValueError("Cada ítem necesita su price (price_…).")
|
|
362
|
+
lines.append({"price": price, **({"quantity": quantity} if quantity is not None else {})})
|
|
363
|
+
if not lines:
|
|
364
|
+
raise ValueError("Envía al menos un ítem.")
|
|
365
|
+
return lines
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def start_checkout(
|
|
369
|
+
account,
|
|
370
|
+
price_id: str | None = None,
|
|
371
|
+
success_url: str | None = None,
|
|
372
|
+
cancel_url: str | None = None,
|
|
373
|
+
email: str | None = None,
|
|
374
|
+
*,
|
|
375
|
+
items: list[Any] | None = None,
|
|
376
|
+
quantity: int | None = None,
|
|
377
|
+
name: str | None = None,
|
|
378
|
+
external_id: str | None = None,
|
|
379
|
+
phone: str | None = None,
|
|
380
|
+
fiscal: dict[str, Any] | None = None,
|
|
381
|
+
customer_fields: list[str] | None = None,
|
|
382
|
+
trial_days: int | None = None,
|
|
383
|
+
metadata: dict[str, str] | None = None,
|
|
384
|
+
subscription_metadata: dict[str, str] | None = None,
|
|
385
|
+
client: Bucli | None = None,
|
|
386
|
+
) -> BucliObject:
|
|
387
|
+
"""The «Suscribirme» button: creates (or reuses) the Bucli customer and a
|
|
388
|
+
checkout session; redirect the user to ``session.url``.
|
|
389
|
+
|
|
390
|
+
One plan (``price_id``, + ``quantity``) or several items
|
|
391
|
+
(``items=[("price_pro", 1), {"price": "price_seat", "quantity": 3}]``: the plan,
|
|
392
|
+
extra seats, add-ons; at least one price must be in ``BUCLI_PRICE_PLANS``).
|
|
393
|
+
The subscription it creates carries ``metadata.bucli_account`` (plus
|
|
394
|
+
``subscription_metadata``), so a webhook or ``discover`` finds the account.
|
|
395
|
+
|
|
396
|
+
The account is NOT activated here, nor at ``success_url``: the webhook does
|
|
397
|
+
it when Bucli says the subscription runs."""
|
|
398
|
+
if not success_url or not email:
|
|
399
|
+
raise ValueError("start_checkout necesita success_url y email.")
|
|
400
|
+
if (price_id is None) == (items is None):
|
|
401
|
+
raise ValueError("Envía price_id o items, uno de los dos.")
|
|
402
|
+
if items is not None:
|
|
403
|
+
if quantity is not None:
|
|
404
|
+
raise ValueError("Con items, cada ítem lleva su quantity.")
|
|
405
|
+
lines = _line_items(items)
|
|
406
|
+
plans = conf.price_plans()
|
|
407
|
+
if not any(line["price"] in plans for line in lines):
|
|
408
|
+
raise UnknownPrice("Ninguno de los precios de items está en BUCLI_PRICE_PLANS.")
|
|
409
|
+
else:
|
|
410
|
+
_check_price(price_id)
|
|
411
|
+
lines = None
|
|
412
|
+
billing = get_billing_account(account)
|
|
413
|
+
if billing.is_running:
|
|
414
|
+
raise AlreadySubscribed("La cuenta ya tiene una suscripción en curso: cambia el plan o abre el portal.")
|
|
415
|
+
linked = bool(get_billing_account(account).bucli_customer_id)
|
|
416
|
+
billing = ensure_customer(
|
|
417
|
+
account, email, name=name, external_id=external_id, phone=phone, fiscal=fiscal, client=client
|
|
418
|
+
)
|
|
419
|
+
if linked:
|
|
420
|
+
# An account linked earlier: its customer gets what it brings now.
|
|
421
|
+
sync_customer(account, phone=phone, fiscal=fiscal, client=client)
|
|
422
|
+
label = {ACCOUNT_METADATA_KEY: account_label(billing.account)}
|
|
423
|
+
return _client(client).checkout_sessions.create(
|
|
424
|
+
price=price_id,
|
|
425
|
+
quantity=quantity,
|
|
426
|
+
line_items=lines,
|
|
427
|
+
success_url=success_url,
|
|
428
|
+
cancel_url=cancel_url,
|
|
429
|
+
customer=billing.bucli_customer_id,
|
|
430
|
+
customer_fields=customer_fields,
|
|
431
|
+
trial_days=trial_days,
|
|
432
|
+
client_reference_id=str(billing.account.pk),
|
|
433
|
+
metadata={**label, **(metadata or {})},
|
|
434
|
+
subscription_data={"metadata": {**(subscription_metadata or {}), **label}},
|
|
435
|
+
)
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def portal_url(account, return_url: str | None = None, *, client: Bucli | None = None) -> str:
|
|
439
|
+
"""The customer portal (card, invoices, data, cancel); valid one hour — create it per click."""
|
|
440
|
+
billing = get_billing_account(account)
|
|
441
|
+
if not billing.bucli_customer_id:
|
|
442
|
+
raise NotSubscribed("La cuenta todavía no tiene cliente en Bucli.")
|
|
443
|
+
return _client(client).portal_sessions.create(customer=billing.bucli_customer_id, return_url=return_url)["url"]
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
def _running_subscription(billing: BillingAccount) -> str:
|
|
447
|
+
if not billing.bucli_subscription_id or billing.is_ended:
|
|
448
|
+
raise NotSubscribed("La cuenta no tiene una suscripción en curso.")
|
|
449
|
+
return billing.bucli_subscription_id
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
PRORATE = "create_prorations"
|
|
453
|
+
NO_PRORATION = "none"
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
def preview_plan_change(account, price_id: str, *, client: Bucli | None = None) -> BucliObject:
|
|
457
|
+
"""What changing the plan to ``price_id`` costs NOW (a ``subscription_quote``):
|
|
458
|
+
show its ``amount`` and lines, then call ``change_plan(...,
|
|
459
|
+
proration_behavior="create_prorations", expected_amount=quote["amount"])``.
|
|
460
|
+
Nothing changes."""
|
|
461
|
+
_check_price(price_id)
|
|
462
|
+
billing = get_billing_account(account)
|
|
463
|
+
api = _client(client)
|
|
464
|
+
subscription = api.subscriptions.retrieve(_running_subscription(billing))
|
|
465
|
+
items = subscription_items(subscription)
|
|
466
|
+
if len(items) <= 1:
|
|
467
|
+
return api.subscriptions.preview(subscription["id"], price=price_id)
|
|
468
|
+
item, _current = base_item(subscription)
|
|
469
|
+
if item is None or not item.get("id"):
|
|
470
|
+
raise NotSubscribed("No se encontró el ítem del plan en la suscripción.")
|
|
471
|
+
target = [
|
|
472
|
+
{"id": row["id"], "price": price_id if row.get("id") == item["id"] else ref(row.get("price"))}
|
|
473
|
+
| ({"quantity": row["quantity"]} if row.get("quantity") is not None else {})
|
|
474
|
+
for row in items
|
|
475
|
+
]
|
|
476
|
+
return api.subscriptions.preview(subscription["id"], items=target)
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
def change_plan(
|
|
480
|
+
account,
|
|
481
|
+
price_id: str,
|
|
482
|
+
*,
|
|
483
|
+
proration_behavior: str = NO_PRORATION,
|
|
484
|
+
expected_amount: int | None = None,
|
|
485
|
+
client: Bucli | None = None,
|
|
486
|
+
) -> BillingAccount:
|
|
487
|
+
"""Change the plan (the item whose price is in ``BUCLI_PRICE_PLANS``).
|
|
488
|
+
|
|
489
|
+
``proration_behavior="none"`` (the default): it applies now and is billed
|
|
490
|
+
from the next period. ``"create_prorations"`` with ``expected_amount`` (the
|
|
491
|
+
``amount`` of ``preview_plan_change``): an upgrade is charged now, prorated,
|
|
492
|
+
and applies when Wompi approves it (the webhook updates the account; a
|
|
493
|
+
failure arrives as ``subscription.update_failed``); a downgrade waits for the
|
|
494
|
+
renewal. A stale amount raises ``bucli.InvalidRequestError`` with
|
|
495
|
+
``code == "quote_changed"`` and the new quote in ``error.quote``."""
|
|
496
|
+
_check_price(price_id)
|
|
497
|
+
if proration_behavior not in (NO_PRORATION, PRORATE):
|
|
498
|
+
raise ValueError('proration_behavior es "none" o "create_prorations".')
|
|
499
|
+
if proration_behavior == PRORATE and expected_amount is None:
|
|
500
|
+
raise ValueError("Con create_prorations envía expected_amount: el amount de preview_plan_change.")
|
|
501
|
+
change = {"proration_behavior": proration_behavior}
|
|
502
|
+
if proration_behavior == PRORATE:
|
|
503
|
+
change["expected_amount"] = expected_amount
|
|
504
|
+
billing = get_billing_account(account)
|
|
505
|
+
api = _client(client)
|
|
506
|
+
subscription = api.subscriptions.retrieve(_running_subscription(billing))
|
|
507
|
+
items = subscription_items(subscription)
|
|
508
|
+
if len(items) <= 1:
|
|
509
|
+
updated = api.subscriptions.update(subscription["id"], price=price_id, **change)
|
|
510
|
+
# Only a subscription is ever stored: an answer of another kind (a pending
|
|
511
|
+
# change) is followed by the subscription as it is now.
|
|
512
|
+
is_subscription = isinstance(updated, dict) and updated.get("object") == "subscription"
|
|
513
|
+
subscription = updated if is_subscription else api.subscriptions.retrieve(subscription["id"])
|
|
514
|
+
else:
|
|
515
|
+
item, current = base_item(subscription)
|
|
516
|
+
if item is None or not item.get("id"):
|
|
517
|
+
raise NotSubscribed("No se encontró el ítem del plan en la suscripción.")
|
|
518
|
+
if current != price_id:
|
|
519
|
+
api.subscription_items.update(item["id"], price=price_id, **change)
|
|
520
|
+
subscription = api.subscriptions.retrieve(subscription["id"])
|
|
521
|
+
store_subscription(billing, subscription)
|
|
522
|
+
return billing
|
|
523
|
+
|
|
524
|
+
|
|
525
|
+
def cancel(
|
|
526
|
+
account,
|
|
527
|
+
at_period_end: bool = True,
|
|
528
|
+
*,
|
|
529
|
+
reason: str | None = None,
|
|
530
|
+
comment: str | None = None,
|
|
531
|
+
client: Bucli | None = None,
|
|
532
|
+
) -> BillingAccount:
|
|
533
|
+
"""Cancel at the end of the period (default) or now."""
|
|
534
|
+
billing = get_billing_account(account)
|
|
535
|
+
subscription = _client(client).subscriptions.cancel(
|
|
536
|
+
_running_subscription(billing), at_period_end=at_period_end, reason=reason, comment=comment
|
|
537
|
+
)
|
|
538
|
+
store_subscription(billing, subscription)
|
|
539
|
+
return billing
|
|
540
|
+
|
|
541
|
+
|
|
542
|
+
def reactivate(account, *, client: Bucli | None = None) -> BillingAccount:
|
|
543
|
+
"""Undo a cancellation scheduled for the end of the period."""
|
|
544
|
+
billing = get_billing_account(account)
|
|
545
|
+
subscription = _client(client).subscriptions.update(_running_subscription(billing), cancel_at_period_end=False)
|
|
546
|
+
store_subscription(billing, subscription)
|
|
547
|
+
return billing
|
|
548
|
+
|
|
549
|
+
|
|
550
|
+
def _pick(candidates: list[dict], tracked: str) -> dict | None:
|
|
551
|
+
"""The subscription the account should follow: a running one (the tracked
|
|
552
|
+
first), else the tracked one, else the newest."""
|
|
553
|
+
running = [sub for sub in candidates if sub.get("status") in RUNNING_STATUSES]
|
|
554
|
+
for sub in running:
|
|
555
|
+
if sub.get("id") == tracked:
|
|
556
|
+
return sub
|
|
557
|
+
if running:
|
|
558
|
+
return running[0]
|
|
559
|
+
for sub in candidates:
|
|
560
|
+
if sub.get("id") == tracked:
|
|
561
|
+
return sub
|
|
562
|
+
return candidates[0] if candidates else None
|
|
563
|
+
|
|
564
|
+
|
|
565
|
+
def sync(account, *, client: Bucli | None = None) -> BillingAccount:
|
|
566
|
+
"""Read the account's subscription(s) again from Bucli and store the right one.
|
|
567
|
+
|
|
568
|
+
For missed webhooks, a migration or a support case (``manage.py bucli_sync``)."""
|
|
569
|
+
billing = get_billing_account(account)
|
|
570
|
+
api = _client(client)
|
|
571
|
+
candidates: list[dict] = []
|
|
572
|
+
if billing.bucli_customer_id:
|
|
573
|
+
candidates = list(api.subscriptions.list(customer=billing.bucli_customer_id, limit=20).auto_paging_iter())
|
|
574
|
+
if billing.bucli_subscription_id and not any(c.get("id") == billing.bucli_subscription_id for c in candidates):
|
|
575
|
+
try:
|
|
576
|
+
candidates.append(api.subscriptions.retrieve(billing.bucli_subscription_id))
|
|
577
|
+
except InvalidRequestError as error:
|
|
578
|
+
if error.code != "resource_missing":
|
|
579
|
+
raise
|
|
580
|
+
chosen = _pick(candidates, billing.bucli_subscription_id)
|
|
581
|
+
if chosen is None:
|
|
582
|
+
BillingAccount.objects.filter(pk=billing.pk).update(last_synced_at=timezone.now())
|
|
583
|
+
return billing
|
|
584
|
+
store_subscription(billing, chosen)
|
|
585
|
+
return billing
|
|
586
|
+
|
|
587
|
+
|
|
588
|
+
def link(account, *, customer_id: str, subscription_id: str = "", client: Bucli | None = None) -> BillingAccount:
|
|
589
|
+
"""Tie an account to an existing Bucli customer (and subscription), then sync.
|
|
590
|
+
|
|
591
|
+
For customers migrated with ``import_subscriptions`` whose subscriptions do
|
|
592
|
+
not carry ``metadata.bucli_account``: use the ids of the import report."""
|
|
593
|
+
billing = get_billing_account(account)
|
|
594
|
+
fields = {"bucli_customer_id": customer_id, "updated_at": timezone.now()}
|
|
595
|
+
if subscription_id:
|
|
596
|
+
fields["bucli_subscription_id"] = subscription_id
|
|
597
|
+
BillingAccount.objects.filter(pk=billing.pk).update(**fields)
|
|
598
|
+
billing.refresh_from_db()
|
|
599
|
+
return sync(billing, client=client)
|
|
600
|
+
|
|
601
|
+
|
|
602
|
+
def discover(*, client: Bucli | None = None) -> dict[str, int]:
|
|
603
|
+
"""Walk every Bucli subscription and store those whose ``metadata.bucli_account``
|
|
604
|
+
names an account of the SaaS (``manage.py bucli_sync --discover``): how the
|
|
605
|
+
migrated customers get their ``BillingAccount`` without a webhook."""
|
|
606
|
+
counts = {"seen": 0, "linked": 0, "skipped": 0}
|
|
607
|
+
for subscription in _client(client).subscriptions.list(limit=100).auto_paging_iter():
|
|
608
|
+
counts["seen"] += 1
|
|
609
|
+
metadata = subscription.get("metadata") or {}
|
|
610
|
+
account = account_from_label(metadata.get(ACCOUNT_METADATA_KEY, ""))
|
|
611
|
+
if account is None:
|
|
612
|
+
counts["skipped"] += 1
|
|
613
|
+
continue
|
|
614
|
+
billing = get_billing_account(account)
|
|
615
|
+
outcome = store_subscription(billing, subscription)
|
|
616
|
+
counts["linked" if outcome in (APPLIED, UNCHANGED) else "skipped"] += 1
|
|
617
|
+
return counts
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""Signals, sent AFTER the transaction that stored the change commits
|
|
2
|
+
(``send_robust``: a failing receiver is logged, never undoes the update).
|
|
3
|
+
|
|
4
|
+
``subscription_changed(sender=BillingAccount, account, billing_account,
|
|
5
|
+
previous_status, status, previous_plan, plan)``
|
|
6
|
+
The local copy changed (status, plan, period, cancellation…). ``account``
|
|
7
|
+
is the instance of ``BUCLI_ACCOUNT_MODEL``.
|
|
8
|
+
|
|
9
|
+
``event_processed(sender=BillingAccount, event, account, billing_account,
|
|
10
|
+
invoice, outcome)``
|
|
11
|
+
Once per verified webhook event (``event`` is the delivered event,
|
|
12
|
+
``invoice`` the fresh invoice for ``invoice.*`` and ``charge.refunded``
|
|
13
|
+
events, or ``None``). Use it for e-mails on ``invoice.payment_failed``, to
|
|
14
|
+
keep the DIAN PDF of ``invoice.fiscal_document.issued``, to put a
|
|
15
|
+
``notice.sent`` in the account's bell (``event["data"]["object"]``) or to
|
|
16
|
+
tell the user that a prorated change failed (``subscription.update_failed``).
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from django.dispatch import Signal
|
|
20
|
+
|
|
21
|
+
subscription_changed = Signal()
|
|
22
|
+
event_processed = Signal()
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""``path("webhooks/bucli/", include("bucli.contrib.django.urls"))`` → ``POST /webhooks/bucli/``."""
|
|
2
|
+
|
|
3
|
+
from django.urls import path
|
|
4
|
+
|
|
5
|
+
from bucli.contrib.django.views import BucliWebhookView
|
|
6
|
+
|
|
7
|
+
app_name = "bucli_billing"
|
|
8
|
+
|
|
9
|
+
urlpatterns = [
|
|
10
|
+
path("", BucliWebhookView.as_view(), name="webhook"),
|
|
11
|
+
]
|