-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmakerspaceapi.py
More file actions
187 lines (163 loc) · 5.85 KB
/
makerspaceapi.py
File metadata and controls
187 lines (163 loc) · 5.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
#!/opt/kasse/venv/bin/python3
"""
MakerSpaceAPI client for NFCKasse.
Configure via settings.py:
api_url = 'http://localhost:8000'
api_token = '<checkout-box machine Bearer token>'
"""
import requests
import settings
import logging
logger = logging.getLogger(__name__)
def _headers():
return {"Authorization": f"Bearer {settings.api_token}"}
def _base():
return settings.api_url.rstrip("/") + "/api/v1"
class MakerSpaceAPI:
"""REST API client for the NFCKasse checkout hardware."""
def __init__(self, **kwargs):
pass
def ping(self):
try:
r = requests.get(
f"{_base()}/products",
headers=_headers(),
timeout=3,
)
return r.ok
except requests.RequestException:
return False
# ------------------------------------------------------------------ #
# Card / user operations #
# ------------------------------------------------------------------ #
def addCard(self, uid):
"""Register a new NFC card (uid is a raw integer)."""
try:
r = requests.post(
f"{_base()}/users",
headers=_headers(),
json={"id": uid},
timeout=5,
)
return r.ok
except requests.RequestException:
logger.exception("addCard failed")
return False
def getCard(self, uid):
"""Return balance for card uid, or None if not registered."""
try:
r = requests.get(
f"{_base()}/users/nfc/{uid}",
headers=_headers(),
timeout=5,
)
if r.ok:
return (
round(float(r.json().get("balance", 0)), 2),
r.json().get("oidc_sub", None) is not None,
)
if r.status_code == 404:
return None, False
return None, False
except requests.RequestException:
logger.exception("getCard failed")
return None, False
# ------------------------------------------------------------------ #
# Product operations #
# ------------------------------------------------------------------ #
def getAlias(self, ean):
"""Resolve an alias EAN to the primary product EAN."""
try:
r = requests.get(
f"{_base()}/products/{ean}",
headers=_headers(),
timeout=5,
)
if r.ok:
return r.json().get("ean", ean)
return ean
except requests.RequestException:
return ean
def getProduct(self, ean):
"""Return product dict {ean, name, price, stock} or None."""
try:
r = requests.get(
f"{_base()}/products/{ean}",
headers=_headers(),
timeout=5,
)
if r.ok:
d = r.json()
return {
"ean": d.get("ean"),
"name": d.get("name"),
"price": float(d.get("price", 0)),
"stock": d.get("stock"),
}
return None
except requests.RequestException:
logger.exception("getProduct failed")
return None
def getProducts(self):
"""Return list of all active products (sorted by category, name)."""
try:
r = requests.get(
f"{_base()}/products",
headers=_headers(),
timeout=5,
)
if r.ok:
products = []
for d in r.json():
products.append(
{
"ean": d.get("ean"),
"name": d.get("name"),
"price": float(d.get("price", 0)),
"stock": d.get("stock"),
"category": d.get("category"),
}
)
return products
except requests.RequestException:
logger.exception("getProducts failed")
return []
def buyProduct(self, uid, ean):
"""Deduct product price from card, reduce stock, record transaction."""
try:
r = requests.post(
f"{_base()}/products/{ean}/purchase",
headers=_headers(),
json={"nfc_id": uid},
timeout=5,
)
return r.ok
except requests.RequestException:
logger.exception("buyProduct failed")
return False
def getConnectLink(self, uid):
"""Generate a short-lived OIDC linking URL for a card.
Returns the URL string, or None on error or if already linked (409)."""
try:
r = requests.post(
f"{_base()}/users/{uid}/connect-link",
headers=_headers(),
timeout=5,
)
if r.ok:
return r.json().get("url")
if r.status_code == 409:
return None # already linked
return None
except requests.RequestException:
logger.exception("getConnectLink failed")
return None
# ------------------------------------------------------------------ #
# Topup codes - not yet supported in MakerSpaceAPI #
# ------------------------------------------------------------------ #
def checkTopUp(self, code):
"""Topup codes are not supported in MakerSpaceAPI. Returns (None, None)."""
return None, None
def topUpCard(self, uid, code):
"""Topup codes are not supported in MakerSpaceAPI. Returns False."""
return False