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,140 @@
|
|
|
1
|
+
"""The settings of ``bucli.contrib.django``, read in one place.
|
|
2
|
+
|
|
3
|
+
Required:
|
|
4
|
+
``BUCLI_SECRET_KEY`` ``sk_test_…`` (staging) or ``sk_live_…`` (production).
|
|
5
|
+
``BUCLI_WEBHOOK_SECRET`` The ``whsec_…`` of your endpoint in Bucli (a list during your own rotation).
|
|
6
|
+
``BUCLI_PRICE_PLANS`` ``{"price_…": "pro", ...}``: Bucli's prices → your internal plans.
|
|
7
|
+
``BUCLI_ACCOUNT_MODEL`` ``"tenants.Tenant"``: the model that owns a subscription.
|
|
8
|
+
|
|
9
|
+
Optional:
|
|
10
|
+
``BUCLI_GRACE`` How long ``past_due`` keeps full access after ``current_period_end``
|
|
11
|
+
(``timedelta`` or days). ``None`` (default): while Bucli keeps retrying.
|
|
12
|
+
``BUCLI_LAPSED_ACCESS`` ``"free"`` (default) or ``"read_only"``: what ``paused``, ``canceled``,
|
|
13
|
+
``incomplete_expired`` (and no subscription) get.
|
|
14
|
+
``BUCLI_FREE_PLAN`` Your free plan's name (default ``"free"``).
|
|
15
|
+
``BUCLI_API_BASE_URL``, ``BUCLI_API_VERSION``, ``BUCLI_TIMEOUT``, ``BUCLI_MAX_RETRIES``,
|
|
16
|
+
``BUCLI_WEBHOOK_TOLERANCE`` (seconds, default 300).
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import datetime
|
|
22
|
+
from functools import lru_cache
|
|
23
|
+
|
|
24
|
+
from django.conf import settings
|
|
25
|
+
from django.core.exceptions import ImproperlyConfigured
|
|
26
|
+
|
|
27
|
+
from bucli.client import Bucli
|
|
28
|
+
from bucli.constants import API_VERSION, DEFAULT_BASE_URL, SIGNATURE_TOLERANCE_SECONDS
|
|
29
|
+
|
|
30
|
+
LAPSED_FREE = "free"
|
|
31
|
+
LAPSED_READ_ONLY = "read_only"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _setting(name: str, default=None):
|
|
35
|
+
return getattr(settings, name, default)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def secret_key() -> str:
|
|
39
|
+
value = _setting("BUCLI_SECRET_KEY")
|
|
40
|
+
if not value:
|
|
41
|
+
raise ImproperlyConfigured("Falta BUCLI_SECRET_KEY (sk_test_… o sk_live_…).")
|
|
42
|
+
return value
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def webhook_secrets() -> list[str]:
|
|
46
|
+
value = _setting("BUCLI_WEBHOOK_SECRET")
|
|
47
|
+
values = [value] if isinstance(value, str) else list(value or [])
|
|
48
|
+
values = [item for item in values if item]
|
|
49
|
+
if not values:
|
|
50
|
+
raise ImproperlyConfigured("Falta BUCLI_WEBHOOK_SECRET (el whsec_… de tu endpoint en Bucli).")
|
|
51
|
+
return values
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def webhook_tolerance() -> int:
|
|
55
|
+
return int(_setting("BUCLI_WEBHOOK_TOLERANCE", SIGNATURE_TOLERANCE_SECONDS))
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def price_plans() -> dict[str, str]:
|
|
59
|
+
value = _setting("BUCLI_PRICE_PLANS") or {}
|
|
60
|
+
if not isinstance(value, dict):
|
|
61
|
+
raise ImproperlyConfigured("BUCLI_PRICE_PLANS debe ser un dict {price_id: plan}.")
|
|
62
|
+
return dict(value)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def account_model_label() -> str:
|
|
66
|
+
value = _setting("BUCLI_ACCOUNT_MODEL")
|
|
67
|
+
if not value or value.count(".") != 1:
|
|
68
|
+
raise ImproperlyConfigured('BUCLI_ACCOUNT_MODEL debe ser "app_label.Modelo" (p. ej. "tenants.Tenant").')
|
|
69
|
+
return value
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def grace() -> datetime.timedelta | None:
|
|
73
|
+
value = _setting("BUCLI_GRACE")
|
|
74
|
+
if value in (None, ""):
|
|
75
|
+
return None
|
|
76
|
+
if isinstance(value, datetime.timedelta):
|
|
77
|
+
return value
|
|
78
|
+
if isinstance(value, int | float):
|
|
79
|
+
return datetime.timedelta(days=value)
|
|
80
|
+
raise ImproperlyConfigured("BUCLI_GRACE debe ser un timedelta o un número de días.")
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def lapsed_access() -> str:
|
|
84
|
+
value = _setting("BUCLI_LAPSED_ACCESS", LAPSED_FREE)
|
|
85
|
+
if value not in (LAPSED_FREE, LAPSED_READ_ONLY):
|
|
86
|
+
raise ImproperlyConfigured('BUCLI_LAPSED_ACCESS debe ser "free" o "read_only".')
|
|
87
|
+
return value
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def free_plan() -> str:
|
|
91
|
+
return _setting("BUCLI_FREE_PLAN", "free")
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
@lru_cache(maxsize=8)
|
|
95
|
+
def _client(key: str, base_url: str, api_version: str, timeout: float, max_retries: int) -> Bucli:
|
|
96
|
+
return Bucli(key, base_url=base_url, api_version=api_version, timeout=timeout, max_retries=max_retries)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def get_client() -> Bucli:
|
|
100
|
+
"""The client of ``BUCLI_SECRET_KEY`` (one per configuration, reused)."""
|
|
101
|
+
return _client(
|
|
102
|
+
secret_key(),
|
|
103
|
+
_setting("BUCLI_API_BASE_URL", DEFAULT_BASE_URL),
|
|
104
|
+
_setting("BUCLI_API_VERSION", API_VERSION),
|
|
105
|
+
float(_setting("BUCLI_TIMEOUT", 15.0)),
|
|
106
|
+
int(_setting("BUCLI_MAX_RETRIES", 2)),
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
# -- metering (``bucli.contrib.django.metering``) -------------------------------------
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def meter_on_unavailable() -> str | dict[str, str]:
|
|
114
|
+
value = _setting("BUCLI_METER_ON_UNAVAILABLE", "deny")
|
|
115
|
+
allowed = ("allow", "deny")
|
|
116
|
+
if isinstance(value, dict):
|
|
117
|
+
if any(policy not in allowed for policy in value.values()):
|
|
118
|
+
raise ImproperlyConfigured('BUCLI_METER_ON_UNAVAILABLE: cada medidor es "allow" o "deny".')
|
|
119
|
+
return dict(value)
|
|
120
|
+
if value not in allowed:
|
|
121
|
+
raise ImproperlyConfigured('BUCLI_METER_ON_UNAVAILABLE debe ser "allow", "deny" o {medidor: política}.')
|
|
122
|
+
return value
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def meter_keys() -> list[str]:
|
|
126
|
+
"""The meters named in the settings (to drop a customer's cached balances)."""
|
|
127
|
+
value = _setting("BUCLI_METER_ON_UNAVAILABLE", "deny")
|
|
128
|
+
return list(value) if isinstance(value, dict) else list(_setting("BUCLI_METERS", []))
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def meter_timeout() -> float:
|
|
132
|
+
return float(_setting("BUCLI_METER_TIMEOUT", 2.0))
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def meter_cache_seconds() -> int:
|
|
136
|
+
return int(_setting("BUCLI_METER_CACHE_SECONDS", 300))
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def meter_max_report_attempts() -> int:
|
|
140
|
+
return int(_setting("BUCLI_METER_MAX_REPORT_ATTEMPTS", 20))
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""Refusals of the Django services (the API's own errors stay ``bucli.BucliError``)."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class BillingStateError(ValueError):
|
|
5
|
+
"""The account is not in a state that allows this action."""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class AlreadySubscribed(BillingStateError): # noqa: N818 — reads as a state, like Django's DoesNotExist
|
|
9
|
+
"""It already has a running subscription: change its plan or open the portal instead."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class NotSubscribed(BillingStateError): # noqa: N818
|
|
13
|
+
"""It has no Bucli customer or subscription yet."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class UnknownPrice(BillingStateError): # noqa: N818
|
|
17
|
+
"""The price is not in ``BUCLI_PRICE_PLANS``."""
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""``manage.py bucli_flush_usage`` — report to Bucli the metered units let
|
|
2
|
+
through while it did not answer (``on_unavailable: allow``). Run it every
|
|
3
|
+
minute (cron or your task queue); what fails stays queued."""
|
|
4
|
+
|
|
5
|
+
from django.core.management.base import BaseCommand
|
|
6
|
+
|
|
7
|
+
from bucli.contrib.django.metering import guard
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Command(BaseCommand):
|
|
11
|
+
help = "Reporta a Bucli los consumos que pasaron mientras no respondía."
|
|
12
|
+
|
|
13
|
+
def add_arguments(self, parser):
|
|
14
|
+
parser.add_argument("--limit", type=int, default=500, help="Cuántos reportar en esta corrida.")
|
|
15
|
+
|
|
16
|
+
def handle(self, *args, **options):
|
|
17
|
+
counts = guard().flush(limit=options["limit"])
|
|
18
|
+
self.stdout.write(f"Reportados: {counts['reported']} · fallidos: {counts['failed']}")
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""``manage.py bucli_sync <pk> [<pk> ...]``, ``--all`` or ``--discover``.
|
|
2
|
+
|
|
3
|
+
Reads each account's subscription again from Bucli and stores it: for missed
|
|
4
|
+
webhooks or a support case. Accounts are the SaaS's (``BUCLI_ACCOUNT_MODEL``)
|
|
5
|
+
primary keys. ``--discover`` walks every Bucli subscription and links those
|
|
6
|
+
whose ``metadata.bucli_account`` names an account (after ``import_subscriptions``).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from django.apps import apps
|
|
10
|
+
from django.core.management.base import BaseCommand, CommandError
|
|
11
|
+
|
|
12
|
+
from bucli.contrib.django import conf, services
|
|
13
|
+
from bucli.contrib.django.models import BillingAccount
|
|
14
|
+
from bucli.errors import BucliError
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Command(BaseCommand):
|
|
18
|
+
help = "Vuelve a copiar desde Bucli la suscripción de una o varias cuentas."
|
|
19
|
+
|
|
20
|
+
def add_arguments(self, parser):
|
|
21
|
+
parser.add_argument("accounts", nargs="*", help="pk de las cuentas (BUCLI_ACCOUNT_MODEL).")
|
|
22
|
+
parser.add_argument("--all", action="store_true", help="Todas las cuentas con cliente en Bucli.")
|
|
23
|
+
parser.add_argument(
|
|
24
|
+
"--discover",
|
|
25
|
+
action="store_true",
|
|
26
|
+
help="Recorre las suscripciones de Bucli y vincula las que traen metadata.bucli_account.",
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
def handle(self, *args, **options):
|
|
30
|
+
if options["discover"]:
|
|
31
|
+
try:
|
|
32
|
+
counts = services.discover()
|
|
33
|
+
except BucliError as error:
|
|
34
|
+
raise CommandError(f"No se pudo leer Bucli: {error}") from error
|
|
35
|
+
self.stdout.write(
|
|
36
|
+
f"Suscripciones vistas: {counts['seen']} · vinculadas: {counts['linked']} · "
|
|
37
|
+
f"saltadas: {counts['skipped']}"
|
|
38
|
+
)
|
|
39
|
+
return
|
|
40
|
+
if options["all"] == bool(options["accounts"]):
|
|
41
|
+
raise CommandError("Indica las cuentas, --all o --discover.")
|
|
42
|
+
if options["all"]:
|
|
43
|
+
targets = list(BillingAccount.objects.exclude(bucli_customer_id="").select_related("account"))
|
|
44
|
+
else:
|
|
45
|
+
model = apps.get_model(conf.account_model_label())
|
|
46
|
+
targets = []
|
|
47
|
+
for pk in options["accounts"]:
|
|
48
|
+
account = model._default_manager.filter(pk=pk).first()
|
|
49
|
+
if account is None:
|
|
50
|
+
self.stderr.write(f"! {pk}: no existe esa cuenta.")
|
|
51
|
+
continue
|
|
52
|
+
targets.append(account)
|
|
53
|
+
synced = failed = 0
|
|
54
|
+
for target in targets:
|
|
55
|
+
label = getattr(target, "account", target)
|
|
56
|
+
try:
|
|
57
|
+
billing = services.sync(target)
|
|
58
|
+
except BucliError as error:
|
|
59
|
+
failed += 1
|
|
60
|
+
self.stderr.write(f"! {label}: {error}")
|
|
61
|
+
continue
|
|
62
|
+
synced += 1
|
|
63
|
+
self.stdout.write(f"+ {label}: {billing.plan or '-'} · {billing.status or 'sin suscripción'}")
|
|
64
|
+
self.stdout.write(f"Sincronizadas: {synced} · errores: {failed}")
|
|
65
|
+
if failed:
|
|
66
|
+
raise CommandError(f"{failed} cuenta(s) no se pudieron sincronizar.")
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"""The metering guard for a Django SaaS: the queue in the database
|
|
2
|
+
(``PendingUsage``), the balances in Django's cache.
|
|
3
|
+
|
|
4
|
+
from bucli.contrib.django.metering import guard
|
|
5
|
+
|
|
6
|
+
reservation = guard().reserve("documents", customer=account.bucli_customer_id,
|
|
7
|
+
idempotency_key=f"doc-{document.pk}")
|
|
8
|
+
if not reservation.allowed:
|
|
9
|
+
raise QuotaExhausted(reservation.refusal)
|
|
10
|
+
|
|
11
|
+
Call ``reserve`` OUTSIDE your business transaction (or with ``ATOMIC_REQUESTS``
|
|
12
|
+
off for that view): a unit let through is queued in the database, and a
|
|
13
|
+
rollback of the caller's transaction would take the queued unit with it.
|
|
14
|
+
|
|
15
|
+
Settings: ``BUCLI_METER_ON_UNAVAILABLE`` (``"allow"``, ``"deny"`` or
|
|
16
|
+
``{"documents": "allow"}``; default ``deny``), ``BUCLI_METER_TIMEOUT``
|
|
17
|
+
(seconds, default 2), ``BUCLI_METER_CACHE_SECONDS`` (default 300) and
|
|
18
|
+
``BUCLI_METER_MAX_REPORT_ATTEMPTS`` (default 20). Report the queue with
|
|
19
|
+
``manage.py bucli_flush_usage`` (a cron every minute, or your task queue).
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
from django.core.cache import cache
|
|
25
|
+
from django.db import IntegrityError, transaction
|
|
26
|
+
from django.db.models import F
|
|
27
|
+
from django.utils import timezone
|
|
28
|
+
|
|
29
|
+
from bucli.contrib.django import conf
|
|
30
|
+
from bucli.contrib.django.models import PendingUsage
|
|
31
|
+
from bucli.metering import DENY, MAX_REPORT_ATTEMPTS, PendingUnit, UsageGuard, aware
|
|
32
|
+
|
|
33
|
+
CACHE_PREFIX = "bucli:meter:"
|
|
34
|
+
INDEX_PREFIX = "bucli:meter-index:"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _cache_key(meter: str, customer: str) -> str:
|
|
38
|
+
return f"{CACHE_PREFIX}{meter}:{customer}"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _index_key(customer: str) -> str:
|
|
42
|
+
return f"{INDEX_PREFIX}{customer}"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _occurred(value):
|
|
46
|
+
"""A stored moment with its zone (``USE_TZ = False`` stores it naive, in local time)."""
|
|
47
|
+
if timezone.is_naive(value):
|
|
48
|
+
return aware(timezone.make_aware(value))
|
|
49
|
+
return value
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class DatabaseUsageStore:
|
|
53
|
+
"""``UsageStore`` on the database (queue) and Django's cache (balances)."""
|
|
54
|
+
|
|
55
|
+
def __init__(self, max_attempts: int = MAX_REPORT_ATTEMPTS) -> None:
|
|
56
|
+
self.max_attempts = max_attempts
|
|
57
|
+
|
|
58
|
+
def enqueue(self, unit: PendingUnit) -> None:
|
|
59
|
+
try:
|
|
60
|
+
with transaction.atomic():
|
|
61
|
+
PendingUsage.objects.create(
|
|
62
|
+
meter=unit.meter,
|
|
63
|
+
customer=unit.customer,
|
|
64
|
+
idempotency_key=unit.idempotency_key,
|
|
65
|
+
quantity=unit.quantity,
|
|
66
|
+
billable=unit.billable,
|
|
67
|
+
metadata=unit.metadata,
|
|
68
|
+
occurred_at=unit.occurred_at,
|
|
69
|
+
)
|
|
70
|
+
except IntegrityError:
|
|
71
|
+
pass # already queued: the same unit
|
|
72
|
+
|
|
73
|
+
def pending(self, limit: int) -> list[PendingUnit]:
|
|
74
|
+
rows = PendingUsage.objects.filter(reported_at__isnull=True, attempts__lt=self.max_attempts)[:limit]
|
|
75
|
+
return [
|
|
76
|
+
PendingUnit(
|
|
77
|
+
meter=row.meter,
|
|
78
|
+
customer=row.customer,
|
|
79
|
+
idempotency_key=row.idempotency_key,
|
|
80
|
+
quantity=row.quantity,
|
|
81
|
+
occurred_at=_occurred(row.occurred_at),
|
|
82
|
+
billable=row.billable,
|
|
83
|
+
metadata=row.metadata or {},
|
|
84
|
+
attempts=row.attempts,
|
|
85
|
+
)
|
|
86
|
+
for row in rows
|
|
87
|
+
]
|
|
88
|
+
|
|
89
|
+
def _row(self, unit: PendingUnit):
|
|
90
|
+
return PendingUsage.objects.filter(
|
|
91
|
+
meter=unit.meter, customer=unit.customer, idempotency_key=unit.idempotency_key
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
def done(self, unit: PendingUnit) -> None:
|
|
95
|
+
self._row(unit).update(reported_at=timezone.now(), last_error="")
|
|
96
|
+
|
|
97
|
+
def failed(self, unit: PendingUnit, error: str) -> None:
|
|
98
|
+
self._row(unit).update(attempts=F("attempts") + 1, last_error=error[:255])
|
|
99
|
+
unit.attempts += 1
|
|
100
|
+
|
|
101
|
+
def discard(self, meter: str, customer: str, idempotency_key: str) -> bool:
|
|
102
|
+
deleted, _ = PendingUsage.objects.filter(
|
|
103
|
+
meter=meter, customer=customer, idempotency_key=idempotency_key, reported_at__isnull=True
|
|
104
|
+
).delete()
|
|
105
|
+
return bool(deleted)
|
|
106
|
+
|
|
107
|
+
def remember(self, meter: str, customer: str, remaining: int | None) -> None:
|
|
108
|
+
if remaining is None:
|
|
109
|
+
cache.delete(_cache_key(meter, customer))
|
|
110
|
+
return
|
|
111
|
+
seconds = conf.meter_cache_seconds()
|
|
112
|
+
cache.set(_cache_key(meter, customer), remaining, timeout=seconds)
|
|
113
|
+
meters = set(cache.get(_index_key(customer)) or ())
|
|
114
|
+
if meter not in meters:
|
|
115
|
+
cache.set(_index_key(customer), sorted({*meters, meter}), timeout=seconds)
|
|
116
|
+
|
|
117
|
+
def remaining(self, meter: str, customer: str, max_age: float) -> int | None:
|
|
118
|
+
return cache.get(_cache_key(meter, customer))
|
|
119
|
+
|
|
120
|
+
def forget(self, meter: str | None, customer: str) -> None:
|
|
121
|
+
if meter is not None:
|
|
122
|
+
cache.delete(_cache_key(meter, customer))
|
|
123
|
+
return
|
|
124
|
+
for key in {*(cache.get(_index_key(customer)) or ()), *conf.meter_keys()}:
|
|
125
|
+
cache.delete(_cache_key(key, customer))
|
|
126
|
+
cache.delete(_index_key(customer))
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def guard() -> UsageGuard:
|
|
130
|
+
"""The guard configured from the settings."""
|
|
131
|
+
return UsageGuard(
|
|
132
|
+
conf.get_client(),
|
|
133
|
+
on_unavailable=conf.meter_on_unavailable() or DENY,
|
|
134
|
+
store=DatabaseUsageStore(max_attempts=conf.meter_max_report_attempts()),
|
|
135
|
+
timeout=conf.meter_timeout(),
|
|
136
|
+
cache_seconds=conf.meter_cache_seconds(),
|
|
137
|
+
)
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
from django.db import migrations, models
|
|
2
|
+
from django.db.models import deletion
|
|
3
|
+
|
|
4
|
+
from bucli.contrib.django.conf import account_model_label
|
|
5
|
+
|
|
6
|
+
#: ``BUCLI_ACCOUNT_MODEL`` (the SaaS model that owns a subscription), read when
|
|
7
|
+
#: the migration loads, as ``AUTH_USER_MODEL`` is. Do not change it once migrated.
|
|
8
|
+
ACCOUNT_MODEL = account_model_label()
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Migration(migrations.Migration):
|
|
12
|
+
initial = True
|
|
13
|
+
|
|
14
|
+
dependencies = [
|
|
15
|
+
migrations.swappable_dependency(ACCOUNT_MODEL),
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
operations = [
|
|
19
|
+
migrations.CreateModel(
|
|
20
|
+
name="BillingAccount",
|
|
21
|
+
fields=[
|
|
22
|
+
("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
|
|
23
|
+
(
|
|
24
|
+
"bucli_customer_id",
|
|
25
|
+
models.CharField(
|
|
26
|
+
blank=True, db_index=True, default="", max_length=64, verbose_name="Cliente en Bucli"
|
|
27
|
+
),
|
|
28
|
+
),
|
|
29
|
+
(
|
|
30
|
+
"bucli_subscription_id",
|
|
31
|
+
models.CharField(
|
|
32
|
+
blank=True, db_index=True, default="", max_length=64, verbose_name="Suscripción en Bucli"
|
|
33
|
+
),
|
|
34
|
+
),
|
|
35
|
+
("price_id", models.CharField(blank=True, default="", max_length=64, verbose_name="Precio del plan")),
|
|
36
|
+
("plan", models.CharField(blank=True, default="", max_length=64, verbose_name="Plan")),
|
|
37
|
+
(
|
|
38
|
+
"pending_price_id",
|
|
39
|
+
models.CharField(
|
|
40
|
+
blank=True, default="", max_length=64, verbose_name="Precio desde el próximo ciclo"
|
|
41
|
+
),
|
|
42
|
+
),
|
|
43
|
+
("status", models.CharField(blank=True, default="", max_length=32, verbose_name="Estado")),
|
|
44
|
+
("current_period_end", models.DateTimeField(blank=True, null=True, verbose_name="Fin del periodo")),
|
|
45
|
+
("trial_end", models.DateTimeField(blank=True, null=True, verbose_name="Fin de la prueba")),
|
|
46
|
+
(
|
|
47
|
+
"cancel_at_period_end",
|
|
48
|
+
models.BooleanField(default=False, verbose_name="Se cancela al fin del periodo"),
|
|
49
|
+
),
|
|
50
|
+
("items", models.JSONField(blank=True, default=list, verbose_name="Ítems")),
|
|
51
|
+
("livemode", models.BooleanField(default=False, verbose_name="Producción")),
|
|
52
|
+
("last_event_sequence", models.BigIntegerField(default=0, verbose_name="Último sequence aplicado")),
|
|
53
|
+
("last_event_at", models.DateTimeField(blank=True, null=True, verbose_name="Último evento aplicado")),
|
|
54
|
+
(
|
|
55
|
+
"last_synced_at",
|
|
56
|
+
models.DateTimeField(blank=True, null=True, verbose_name="Última copia desde Bucli"),
|
|
57
|
+
),
|
|
58
|
+
("created_at", models.DateTimeField(auto_now_add=True)),
|
|
59
|
+
("updated_at", models.DateTimeField(auto_now=True)),
|
|
60
|
+
(
|
|
61
|
+
"account",
|
|
62
|
+
models.OneToOneField(
|
|
63
|
+
on_delete=deletion.CASCADE,
|
|
64
|
+
related_name="bucli_billing",
|
|
65
|
+
to=ACCOUNT_MODEL,
|
|
66
|
+
verbose_name="Cuenta",
|
|
67
|
+
),
|
|
68
|
+
),
|
|
69
|
+
],
|
|
70
|
+
options={
|
|
71
|
+
"verbose_name": "Cuenta de cobro (Bucli)",
|
|
72
|
+
"verbose_name_plural": "Cuentas de cobro (Bucli)",
|
|
73
|
+
},
|
|
74
|
+
),
|
|
75
|
+
migrations.CreateModel(
|
|
76
|
+
name="ProcessedEvent",
|
|
77
|
+
fields=[
|
|
78
|
+
("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
|
|
79
|
+
("event_id", models.CharField(max_length=64, unique=True, verbose_name="Evento")),
|
|
80
|
+
("type", models.CharField(max_length=100, verbose_name="Tipo")),
|
|
81
|
+
("sequence", models.BigIntegerField(blank=True, null=True, verbose_name="Sequence")),
|
|
82
|
+
("livemode", models.BooleanField(default=False, verbose_name="Producción")),
|
|
83
|
+
("outcome", models.CharField(blank=True, default="", max_length=32, verbose_name="Resultado")),
|
|
84
|
+
("received_at", models.DateTimeField(auto_now_add=True, db_index=True, verbose_name="Recibido")),
|
|
85
|
+
(
|
|
86
|
+
"billing_account",
|
|
87
|
+
models.ForeignKey(
|
|
88
|
+
blank=True,
|
|
89
|
+
null=True,
|
|
90
|
+
on_delete=deletion.SET_NULL,
|
|
91
|
+
related_name="processed_events",
|
|
92
|
+
to="bucli_billing.billingaccount",
|
|
93
|
+
),
|
|
94
|
+
),
|
|
95
|
+
],
|
|
96
|
+
options={
|
|
97
|
+
"verbose_name": "Evento procesado (Bucli)",
|
|
98
|
+
"verbose_name_plural": "Eventos procesados (Bucli)",
|
|
99
|
+
"ordering": ["-received_at"],
|
|
100
|
+
},
|
|
101
|
+
),
|
|
102
|
+
]
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
from django.db import migrations, models
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class Migration(migrations.Migration):
|
|
5
|
+
dependencies = [
|
|
6
|
+
("bucli_billing", "0001_initial"),
|
|
7
|
+
]
|
|
8
|
+
|
|
9
|
+
operations = [
|
|
10
|
+
migrations.AddField(
|
|
11
|
+
model_name="billingaccount",
|
|
12
|
+
name="bucli_updated_at",
|
|
13
|
+
field=models.DateTimeField(blank=True, null=True, verbose_name="Último cambio en Bucli"),
|
|
14
|
+
),
|
|
15
|
+
]
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
from django.db import migrations, models
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class Migration(migrations.Migration):
|
|
5
|
+
dependencies = [
|
|
6
|
+
("bucli_billing", "0002_billingaccount_bucli_updated_at"),
|
|
7
|
+
]
|
|
8
|
+
|
|
9
|
+
operations = [
|
|
10
|
+
migrations.CreateModel(
|
|
11
|
+
name="PendingUsage",
|
|
12
|
+
fields=[
|
|
13
|
+
("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")),
|
|
14
|
+
("meter", models.CharField(max_length=60, verbose_name="Medidor")),
|
|
15
|
+
("customer", models.CharField(max_length=64, verbose_name="Cliente en Bucli")),
|
|
16
|
+
("idempotency_key", models.CharField(max_length=255, verbose_name="Llave de la unidad")),
|
|
17
|
+
("quantity", models.PositiveIntegerField(default=1, verbose_name="Cantidad")),
|
|
18
|
+
("billable", models.BooleanField(default=True, verbose_name="Gasta cupo")),
|
|
19
|
+
("metadata", models.JSONField(blank=True, default=dict, verbose_name="Metadata")),
|
|
20
|
+
("occurred_at", models.DateTimeField(verbose_name="Ocurrió el")),
|
|
21
|
+
("attempts", models.PositiveSmallIntegerField(default=0, verbose_name="Intentos de reporte")),
|
|
22
|
+
("last_error", models.CharField(blank=True, default="", max_length=255, verbose_name="Último error")),
|
|
23
|
+
(
|
|
24
|
+
"reported_at",
|
|
25
|
+
models.DateTimeField(blank=True, db_index=True, null=True, verbose_name="Reportado el"),
|
|
26
|
+
),
|
|
27
|
+
("created_at", models.DateTimeField(auto_now_add=True)),
|
|
28
|
+
],
|
|
29
|
+
options={
|
|
30
|
+
"verbose_name": "Consumo por reportar (Bucli)",
|
|
31
|
+
"verbose_name_plural": "Consumos por reportar (Bucli)",
|
|
32
|
+
"ordering": ["occurred_at", "id"],
|
|
33
|
+
"constraints": [
|
|
34
|
+
models.UniqueConstraint(
|
|
35
|
+
fields=("meter", "customer", "idempotency_key"), name="bucli_pending_usage_one_per_unit"
|
|
36
|
+
)
|
|
37
|
+
],
|
|
38
|
+
},
|
|
39
|
+
),
|
|
40
|
+
]
|
|
File without changes
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""The local copy of Bucli's state: one ``BillingAccount`` per account of the SaaS.
|
|
2
|
+
|
|
3
|
+
It is a COPY, to decide access without calling Bucli on every request. Only
|
|
4
|
+
``services.store_subscription`` writes it, from an object Bucli just answered
|
|
5
|
+
(a webhook followed by a ``GET``, or a sync) — never from a redirect to
|
|
6
|
+
``success_url``.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from django.db import models
|
|
12
|
+
|
|
13
|
+
from bucli.constants import ENDED_STATUSES, RUNNING_STATUSES
|
|
14
|
+
from bucli.contrib.django import conf
|
|
15
|
+
|
|
16
|
+
ACCOUNT_MODEL = conf.account_model_label()
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class BillingAccount(models.Model):
|
|
20
|
+
account = models.OneToOneField(
|
|
21
|
+
ACCOUNT_MODEL,
|
|
22
|
+
on_delete=models.CASCADE,
|
|
23
|
+
related_name="bucli_billing",
|
|
24
|
+
verbose_name="Cuenta",
|
|
25
|
+
)
|
|
26
|
+
bucli_customer_id = models.CharField("Cliente en Bucli", max_length=64, blank=True, default="", db_index=True)
|
|
27
|
+
bucli_subscription_id = models.CharField(
|
|
28
|
+
"Suscripción en Bucli", max_length=64, blank=True, default="", db_index=True
|
|
29
|
+
)
|
|
30
|
+
price_id = models.CharField("Precio del plan", max_length=64, blank=True, default="")
|
|
31
|
+
plan = models.CharField("Plan", max_length=64, blank=True, default="")
|
|
32
|
+
pending_price_id = models.CharField("Precio desde el próximo ciclo", max_length=64, blank=True, default="")
|
|
33
|
+
status = models.CharField("Estado", max_length=32, blank=True, default="")
|
|
34
|
+
current_period_end = models.DateTimeField("Fin del periodo", null=True, blank=True)
|
|
35
|
+
trial_end = models.DateTimeField("Fin de la prueba", null=True, blank=True)
|
|
36
|
+
cancel_at_period_end = models.BooleanField("Se cancela al fin del periodo", default=False)
|
|
37
|
+
items = models.JSONField("Ítems", default=list, blank=True)
|
|
38
|
+
livemode = models.BooleanField("Producción", default=False)
|
|
39
|
+
#: The subscription's ``updated`` in Bucli when it was copied: a copy
|
|
40
|
+
#: older than this one never overwrites it (``store_subscription``).
|
|
41
|
+
bucli_updated_at = models.DateTimeField("Último cambio en Bucli", null=True, blank=True)
|
|
42
|
+
last_event_sequence = models.BigIntegerField("Último sequence aplicado", default=0)
|
|
43
|
+
last_event_at = models.DateTimeField("Último evento aplicado", null=True, blank=True)
|
|
44
|
+
last_synced_at = models.DateTimeField("Última copia desde Bucli", null=True, blank=True)
|
|
45
|
+
created_at = models.DateTimeField(auto_now_add=True)
|
|
46
|
+
updated_at = models.DateTimeField(auto_now=True)
|
|
47
|
+
|
|
48
|
+
class Meta:
|
|
49
|
+
app_label = "bucli_billing"
|
|
50
|
+
verbose_name = "Cuenta de cobro (Bucli)"
|
|
51
|
+
verbose_name_plural = "Cuentas de cobro (Bucli)"
|
|
52
|
+
|
|
53
|
+
def __str__(self) -> str:
|
|
54
|
+
return f"{self.account} · {self.plan or '-'} · {self.status or 'sin suscripción'}"
|
|
55
|
+
|
|
56
|
+
@property
|
|
57
|
+
def is_running(self) -> bool:
|
|
58
|
+
"""The subscription still bills (trialing, active, past_due)."""
|
|
59
|
+
return self.status in RUNNING_STATUSES
|
|
60
|
+
|
|
61
|
+
@property
|
|
62
|
+
def is_ended(self) -> bool:
|
|
63
|
+
return self.status in ENDED_STATUSES
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class ProcessedEvent(models.Model):
|
|
67
|
+
"""Every Bucli event already handled: a redelivery (same ``id``) answers 200 and does nothing."""
|
|
68
|
+
|
|
69
|
+
event_id = models.CharField("Evento", max_length=64, unique=True)
|
|
70
|
+
type = models.CharField("Tipo", max_length=100)
|
|
71
|
+
sequence = models.BigIntegerField("Sequence", null=True, blank=True)
|
|
72
|
+
livemode = models.BooleanField("Producción", default=False)
|
|
73
|
+
billing_account = models.ForeignKey(
|
|
74
|
+
BillingAccount,
|
|
75
|
+
on_delete=models.SET_NULL,
|
|
76
|
+
null=True,
|
|
77
|
+
blank=True,
|
|
78
|
+
related_name="processed_events",
|
|
79
|
+
)
|
|
80
|
+
outcome = models.CharField("Resultado", max_length=32, blank=True, default="")
|
|
81
|
+
received_at = models.DateTimeField("Recibido", auto_now_add=True, db_index=True)
|
|
82
|
+
|
|
83
|
+
class Meta:
|
|
84
|
+
app_label = "bucli_billing"
|
|
85
|
+
verbose_name = "Evento procesado (Bucli)"
|
|
86
|
+
verbose_name_plural = "Eventos procesados (Bucli)"
|
|
87
|
+
ordering = ["-received_at"]
|
|
88
|
+
|
|
89
|
+
def __str__(self) -> str:
|
|
90
|
+
return f"{self.event_id} {self.type} ({self.outcome})"
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class PendingUsage(models.Model):
|
|
94
|
+
"""A metered unit let through while Bucli did not answer (``on_unavailable:
|
|
95
|
+
allow``), waiting for ``bucli_flush_usage`` to report it
|
|
96
|
+
(``bucli.contrib.django.metering.DatabaseUsageStore``)."""
|
|
97
|
+
|
|
98
|
+
meter = models.CharField("Medidor", max_length=60)
|
|
99
|
+
customer = models.CharField("Cliente en Bucli", max_length=64)
|
|
100
|
+
idempotency_key = models.CharField("Llave de la unidad", max_length=255)
|
|
101
|
+
quantity = models.PositiveIntegerField("Cantidad", default=1)
|
|
102
|
+
billable = models.BooleanField("Gasta cupo", default=True)
|
|
103
|
+
metadata = models.JSONField("Metadata", default=dict, blank=True)
|
|
104
|
+
occurred_at = models.DateTimeField("Ocurrió el")
|
|
105
|
+
attempts = models.PositiveSmallIntegerField("Intentos de reporte", default=0)
|
|
106
|
+
last_error = models.CharField("Último error", max_length=255, blank=True, default="")
|
|
107
|
+
reported_at = models.DateTimeField("Reportado el", null=True, blank=True, db_index=True)
|
|
108
|
+
created_at = models.DateTimeField(auto_now_add=True)
|
|
109
|
+
|
|
110
|
+
class Meta:
|
|
111
|
+
app_label = "bucli_billing"
|
|
112
|
+
verbose_name = "Consumo por reportar (Bucli)"
|
|
113
|
+
verbose_name_plural = "Consumos por reportar (Bucli)"
|
|
114
|
+
ordering = ["occurred_at", "id"]
|
|
115
|
+
constraints = [
|
|
116
|
+
models.UniqueConstraint(
|
|
117
|
+
fields=["meter", "customer", "idempotency_key"], name="bucli_pending_usage_one_per_unit"
|
|
118
|
+
),
|
|
119
|
+
]
|
|
120
|
+
|
|
121
|
+
def __str__(self) -> str:
|
|
122
|
+
return f"{self.meter} · {self.customer} · {self.idempotency_key}"
|