Coverage for benefits/enrollment_init/api.py: 100%
87 statements
« prev ^ index » next coverage.py v7.17.5, created at 2026-11-23 20:53 +0000
« prev ^ index » next coverage.py v7.17.5, created at 2026-11-23 20:53 +0000
1import base64
2from dataclasses import asdict, dataclass
3from datetime import datetime
5import requests
6from django.conf import settings
8from benefits.enrollment.api import BaseDataClass
11@dataclass
12class TransitAccountResponse(BaseDataClass):
13 """
14 Represents the properties we are interested in from a TransitAccount.
15 """
17 Id: int
18 CardholderId: int
21@dataclass
22class CardholderUpdateModel(BaseDataClass):
23 """
24 Represents the body parameters that can be sent when updating a Cardholder.
25 """
27 FirstName: str | None = None
28 MiddleName: str | None = None
29 LastName: str | None = None
30 PhoneNumber: str | None = None
31 DateOfBirth: str | None = None
32 Email: str | None = None
33 CellPhoneNumber: str | None = None
34 FaxNumber: str | None = None
35 Gender: str | None = None
36 Identifier: str | None = None
37 FareCategory: int | None = None
38 FareCategoryExpiry: datetime | None = None
39 TransitAccountId: int | None = None
40 PersonalCareAssistant: bool | None = None
43@dataclass
44class CardholderResponse(BaseDataClass):
45 """
46 Represents the response properties we are interested in from a Cardholder.
48 FareCategory and FareCategoryExpiry are the main properties of interest to us.
49 The rest of the properties are for preserving existing values when we update a Cardholder.
50 """
52 Id: int
53 FirstName: str | None = None
54 MiddleName: str | None = None
55 LastName: str | None = None
56 PhoneNumber: str | None = None
57 DateOfBirth: str | None = None
58 Email: str | None = None
59 CellPhoneNumber: str | None = None
60 FaxNumber: str | None = None
61 Gender: str | None = None
62 Identifier: str | None = None
63 FareCategory: int | None = None
64 FareCategoryExpiry: datetime | None = None
65 TransitAccountId: int | None = None
66 PersonalCareAssistant: bool | None = None
67 # there are more fields that can be returned, but we don't need them and they're not in the PUT parameters
69 def __post_init__(self):
70 """Parses any date parameters into aware Python datetime objects.
72 For @dataclasses with a generated __init__ function, this function is called automatically.
74 https://docs.python.org/3.12/library/datetime.html#datetime.datetime.fromisoformat
75 """
76 if self.FareCategoryExpiry:
77 self.FareCategoryExpiry = datetime.fromisoformat(self.FareCategoryExpiry)
80class Client:
81 def __init__(self, api_url, username, password):
82 self.api_url = api_url.strip("/")
84 encoded_bytes = base64.b64encode(bytes(f"{username}:{password}", "utf-8"))
85 self.authorization_header_value = f"Basic {encoded_bytes.decode()}"
87 def _endpoint_url(self, endpoint):
88 return f"{self.api_url}/api/{endpoint}"
90 def _authorization_header(self):
91 return {"Authorization": self.authorization_header_value}
93 def get_transit_account(self, banking_service_token, timeout=settings.REQUESTS_TIMEOUT) -> TransitAccountResponse:
94 """
95 Gets a TransitAccount given a BankingServiceToken. May return None.
96 """
97 url = self._endpoint_url("TransitAccounts")
98 response = requests.get(
99 url,
100 params={
101 "BankingServiceToken": banking_service_token,
102 },
103 headers=self._authorization_header(),
104 timeout=timeout,
105 )
107 response.raise_for_status()
109 response_json = response.json()
110 total_count = response_json["TotalCount"]
111 results = response_json["Result"]
113 if total_count == 1:
114 return TransitAccountResponse.from_kwargs(**results[0])
115 elif total_count == 0:
116 return None
117 else:
118 raise ValueError(f"Unexpectedly received more than 1 TransitAccount for token {banking_service_token}")
120 def get_cardholder(self, cardholder_id: int, timeout=settings.REQUESTS_TIMEOUT) -> CardholderResponse:
121 """
122 Gets a Cardholder by ID. Raises an error if ID does not match a Cardholder.
123 """
124 url = self._endpoint_url("Cardholders") + f"/{cardholder_id}"
125 response = requests.get(
126 url,
127 headers=self._authorization_header(),
128 timeout=timeout,
129 )
131 response.raise_for_status()
133 response_json = response.json()
135 if "Id" in response_json and response_json["Id"] == cardholder_id:
136 return CardholderResponse.from_kwargs(**response_json)
137 else:
138 raise ValueError(f"Unexpected response when querying for cardholder {cardholder_id}: {response_json}")
140 def post_cardholder(
141 self, fare_category: int, transit_account_id: int, timeout=settings.REQUESTS_TIMEOUT
142 ) -> CardholderResponse:
143 """
144 Creates a new Cardholder linked to the given Fare Category and Transit Account ID.
145 """
146 url = self._endpoint_url("Cardholders")
147 request_body = {
148 "FareCategory": fare_category,
149 "TransitAccountId": transit_account_id,
150 }
151 response = requests.post(
152 url,
153 json=request_body,
154 headers=self._authorization_header(),
155 timeout=timeout,
156 )
158 response.raise_for_status()
160 return CardholderResponse.from_kwargs(**response.json())
162 def put_cardholder(
163 self, cardholder_id: int, cardholder_update_model: CardholderUpdateModel, timeout=settings.REQUESTS_TIMEOUT
164 ) -> CardholderResponse:
165 """
166 Updates the Cardholder identified by cardholder_id.
168 FareCategory and (optionally) FareCategoryExpiry are the properties we actually want to update.
169 All the other properties are included so that they do not get cleared out.
170 """
171 url = self._endpoint_url("Cardholders") + f"/{cardholder_id}"
172 request_body = asdict(cardholder_update_model)
173 response = requests.put(
174 url,
175 json=request_body,
176 headers=self._authorization_header(),
177 timeout=timeout,
178 )
180 response.raise_for_status()
182 return CardholderResponse.from_kwargs(**response.json())