models.py

Python SDK · 5.6 KB · 155 lines

1import re
2from dataclasses import dataclass, field
3from datetime import datetime, timezone
4from decimal import Decimal
5from typing import Any, Dict, List, Optional
6
7
8def _dec(value: Any) -> Optional[Decimal]:
9 return None if value is None else value if isinstance(value, Decimal) else Decimal(str(value))
10
11
12_ISO = re.compile(r"^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d+))?(Z|[+-]\d{2}:\d{2})?$")
13
14
15def _time(value: Optional[str]) -> Optional[datetime]:
16 """Parses .NET's ISO 8601 (up to 7 fractional digits, 'Z' or an offset, or none = UTC)."""
17 if not value:
18 return None
19 m = _ISO.match(value)
20 if not m:
21 return datetime.fromisoformat(value)
22 base, fraction, zone = m.groups()
23 text = base + ("." + (fraction + "000000")[:6] if fraction else "")
24 if zone and zone != "Z":
25 text += zone
26 parsed = datetime.fromisoformat(text)
27 return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)
28
29
30@dataclass(frozen=True)
31class Payment:
32 """A payment (or a refund, ``type == "refund"``), as ``get_payment`` returns it."""
33
34 id: str # "tx_…": a random string, not a number
35 type: str
36 amount: Decimal
37 currency: str
38 status: str # pending, completed or aborted
39 description: str
40 reference: Optional[str]
41 payment_code: Optional[str]
42 refunded: Decimal
43 refundable: Decimal
44 refund_of: Optional[str]
45 subscription_id: Optional[str]
46 raw: Dict[str, Any]
47 # Every subscription this payment belongs to: the one it charged, or all those a checkout of several started.
48 subscription_ids: List[str] = field(default_factory=list)
49
50 @property
51 def completed(self) -> bool:
52 return self.status == "completed"
53
54 @classmethod
55 def from_json(cls, d: Dict[str, Any]) -> "Payment":
56 return cls(id=d["id"], type=d.get("type", "payment"), amount=_dec(d["amount"]), currency=d["currency"],
57 status=d["status"], description=d.get("description") or "", reference=d.get("reference"),
58 payment_code=d.get("payment_code"), refunded=_dec(d.get("refunded", 0)),
59 refundable=_dec(d.get("refundable", 0)), refund_of=d.get("refund_of"),
60 subscription_id=d.get("subscription_id"), raw=d,
61 subscription_ids=list(d.get("subscription_ids")
62 or ([d["subscription_id"]] if d.get("subscription_id") else [])))
63
64
65@dataclass(frozen=True)
66class PaymentCode:
67 """A QR code for a pending payment: put ``url`` in a QR code, or show the ready-made SVG at ``qr_svg``."""
68
69 code: str
70 url: str
71 qr_svg: str
72
73
74@dataclass(frozen=True)
75class Refund:
76 id: str
77 amount: Decimal
78 currency: str
79 reference: str
80 reason: Optional[str]
81
82
83@dataclass(frozen=True)
84class RefundResult:
85 refund: Refund
86 payment: Payment # the refunded payment, with updated ``refunded`` / ``refundable``
87
88
89@dataclass(frozen=True)
90class Subscription:
91 id: str # "sub_…": a random string, not a number
92 status: str # offered, active or canceled
93 active_period: bool # within a paid period: give access while this is true
94 amount: Decimal
95 currency: str
96 interval: str # day, week, month or year
97 interval_count: int
98 description: Optional[str]
99 url: str
100 qr_svg: str
101 subscribed_at: Optional[datetime]
102 subscribed_for_days: Optional[int]
103 subscribed_for_seconds: Optional[int]
104 canceled: bool
105 canceled_at: Optional[datetime]
106 canceled_by: Optional[str] # customer, merchant, bank or schedule
107 current_period_start: Optional[datetime]
108 current_period_end: Optional[datetime]
109 next_charge_at: Optional[datetime]
110 ends_at: Optional[datetime]
111 last_day: Optional[datetime]
112 charges: int
113 last_error: Optional[str]
114 customer_name: Optional[str]
115 raw: Dict[str, Any]
116
117 @classmethod
118 def from_json(cls, d: Dict[str, Any]) -> "Subscription":
119 return cls(id=d["id"], status=d["status"], active_period=bool(d.get("active_period")), amount=_dec(d["amount"]),
120 currency=d["currency"], interval=d["interval"], interval_count=d.get("interval_count", 1),
121 description=d.get("description"), url=d["url"], qr_svg=d["qr_svg"],
122 subscribed_at=_time(d.get("subscribed_at")), subscribed_for_days=d.get("subscribed_for_days"),
123 subscribed_for_seconds=d.get("subscribed_for_seconds"), canceled=bool(d.get("canceled")),
124 canceled_at=_time(d.get("canceled_at")), canceled_by=d.get("canceled_by"),
125 current_period_start=_time(d.get("current_period_start")),
126 current_period_end=_time(d.get("current_period_end")),
127 next_charge_at=_time(d.get("next_charge_at")), ends_at=_time(d.get("ends_at")),
128 last_day=_time(d.get("last_day")), charges=d.get("charges") or 0, last_error=d.get("last_error"),
129 customer_name=(d.get("customer") or {}).get("name"), raw=d)
130
131
132@dataclass(frozen=True)
133class SubscriptionCheckout:
134 """The first payment of a subscription: hand ``transaction_id`` to the pay button / hosted checkout."""
135
136 transaction_id: str
137 subscription: Subscription
138
139
140@dataclass(frozen=True)
141class SubscriptionsCheckout:
142 """One first payment for several subscriptions: hand ``transaction_id`` to the pay button / hosted checkout.
143 Paying it starts all of ``subscriptions`` (in the order you listed them)."""
144
145 transaction_id: str
146 subscriptions: List[Subscription]
147
148
149@dataclass(frozen=True)
150class Rate:
151 to_rate: Decimal # converts currency_from into currency_to
152 from_rate: Decimal # the other way
153
154
155SubscriptionList = List[Subscription]