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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
|
import sqlite3
from datetime import datetime, timezone, timedelta
from dateutil.parser import isoparse
from typing import Union
from .logger import Logger
from .utils import human_datetime, human_timedelta, CST
from .exceptions import *
STATUSES = ["available", "lent", "overdue", "maintenance", "unknown"]
class Umbrellas:
def __init__(self, path):
"""A database of all umbrellas and their current state.
Currently, the data are represented in a SQLite database. Only admins have access to the
database, and have the power to modify it arbitrarily.
An SQL row for an umbrella consists of these columns:
- id | int. unique identifier for the umbrella.
- status | string. possible values:
| available : is in service on the stand
| lent : is in temporary possession of a user
| overdue : is in overly prolonged possession of a user
| maintenance : is out of service
| unknown : none of the above
- tenant_name | string. the person in temporary possession of the umbrella.
- tenant_id | string. student or faculty ID.
- tenant_phone | string. phone number via which to contact tenant when the lease is due.
- tenant_email | string. for future compatibility. always None for the time being.
- lent_at | an ISO 8601 datetime string if status is "lent" or "overdue", empty string
| otherwise.
Schema:
CREATE TABLE Umbrellas(
id INT PRIMARY KEY,
status TEXT,
tenant_name TEXT,
tenant_id TEXT,
tenant_phone TEXT,
tenant_email TEXT,
lent_at TEXT
);
"""
self.path = path
self.logger = Logger(path)
def read(self, umbid=None) -> Union[dict, list]:
"""Read umbrella data from database.
If umbid is an integer, returns dict pertaining to umbrella #<umbid>, or None if not found.
If umbid is None, returns list of dicts for all umbrellas.
"""
db = sqlite3.connect(self.path)
db.row_factory = sqlite3.Row
if umbid is None:
data = db.execute("SELECT * FROM Umbrellas").fetchall()
else:
data = db.execute(
"SELECT * FROM Umbrellas WHERE id = ?", (umbid,)
).fetchone()
db.close()
return data
def update(self, umb) -> None:
"""Update Umbrella table with new data given in `umb`.
Not all fields in an umbrella dict need to be present in `umb`. Only `id` is required.
If an optional field is not found, its value is left untouched. If an optional field is
present but its value is an empty string, it will be erased.
Invalid values are rejected as an UmbrellaValueError.
If `status` is not "lent" or "overdue", `tenant_*` and `lent_at` are automatically erased.
`lent_at` may be either an ISO 8601 string or a datetime.datetime object. If no timezone is
supplied, UTC+8 is assumed.
Returns a dict of <field>: (<prior_value>, <updated_value>) for each updated field unless
its erasure can be inferred. For AdminLog.
"""
# `id` must be specified.
try:
umb["id"] = int(umb["id"])
except (KeyError, ValueError):
raise UmbrellaValueError("id")
db = sqlite3.connect(self.path)
db.row_factory = sqlite3.Row
# check if umbrella #<id> exists in database
umbid = umb["id"]
umb_in_db = db.execute(
"SELECT * FROM Umbrellas WHERE id = ?", (umbid,)
).fetchone()
if umb_in_db is None:
raise UmbrellaNotFoundError(umbid)
status = umb_in_db["status"]
if "status" in umb:
if umb["status"] in STATUSES:
status = umb["status"]
db.execute(
"UPDATE Umbrellas SET status = ? WHERE id = ?", (status, umbid)
)
else:
raise UmbrellaValueError("status")
if status in ("lent", "overdue"):
for col in (
"tenant_name",
"tenant_id",
"tenant_phone",
"tenant_email",
):
if col in umb:
db.execute(
f"UPDATE Umbrellas SET {col} = ? WHERE id = ?",
(
umb[col],
umbid,
),
)
if "lent_at" in umb:
try:
# lent_at could be a string, in which case it is parsed
lent_at = isoparse(umb["lent_at"])
except TypeError:
# or it could be a datetime.datetime
lent_at = umb["lent_at"]
except ValueError:
# anything else is invalid
raise UmbrellaValueError("lent_at")
if lent_at.tzinfo is None:
lent_at = lent_at.replace(tzinfo=CST)
db.execute(
"UPDATE Umbrellas SET lent_at = ? WHERE id = ?",
(
lent_at.isoformat(timespec="milliseconds"),
umbid,
),
)
else:
# discard unneeded fields
for col in (
"tenant_name",
"tenant_id",
"tenant_phone",
"tenant_email",
"lent_at",
):
db.execute(f"UPDATE Umbrellas SET {col} = '' WHERE id = ?", (umbid,))
# now that new data are validated, commit the SQL transaction
db.commit()
db.close()
def admin_modify(self, actor: str, umb: dict, note="") -> None:
"""Update db with `umb`, and also keep a log with AdminLog.
Similar to AdminLog.log, this method does no authentication either.
"""
try:
umbid = umb["id"]
except KeyError:
raise UmbrellaValueError("id")
umb_old = dict(self.read(umbid))
if umb_old is None:
raise UmbrellaNotFoundError(umbid)
self.update(umb)
umb_new = dict(self.read(umbid))
if umb_old != umb_new:
self.logger.log_admin(
datetime.now(tz=CST).isoformat(timespec="milliseconds"),
actor,
umbid,
umb_old,
umb_new,
note,
)
def take_away(
self, umbid, date, tenant_name, tenant_id, tenant_phone="", tenant_email=""
) -> None:
"""When a user has borrowed an umbrella."""
umb = self.read(umbid)
if umb is None:
raise UmbrellaNotFoundError(umbid)
if umb["status"] != "available":
raise UmbrellaStatusError
umb = {
"id": umbid,
"status": "lent",
"tenant_name": tenant_name,
"tenant_id": tenant_id,
"tenant_phone": tenant_phone,
"tenant_email": tenant_email,
"lent_at": date.isoformat(timespec="milliseconds"),
}
self.update(umb)
self.logger.log_tenant(
date.isoformat(timespec="milliseconds"), "borrow", umbid, umb
)
def give_back(self, umbid, date, tenant_name, tenant_id) -> None:
"""When a user has returned an umbrella.
`tenant_name` and `tenant_id` are used to verify if the umbrella is returned by the same
person who borrowed it.
"""
umb = dict(self.read(umbid))
if umb is None:
raise UmbrellaNotFoundError(umbid)
if umb["status"] not in ("lent", "overdue"):
raise UmbrellaStatusError
if umb["tenant_name"] != tenant_name or umb["tenant_id"] != tenant_id:
raise TenantIdentityError(umb["tenant_name"], tenant_name)
self.update(
{
"id": umbid,
"status": "available",
}
)
self.logger.log_tenant(
date.isoformat(timespec="milliseconds"), "return", umbid, umb
)
def mark_overdue(self, umbid) -> None:
"""When an umbrella is overdue, change its status to "overdue"."""
umb = dict(self.read(umbid))
if umb is None:
raise UmbrellaNotFoundError(umbid)
elif umb["status"] != "lent":
raise UmbrellaStatusError
self.update({"id": umbid, "status": "overdue"})
self.logger.log_tenant(
datetime.now(tz=CST).isoformat(timespec="milliseconds"),
"overdue",
umbid,
umb,
)
|