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
|
import sqlite3
from datetime import datetime, timedelta
from .utils import human_datetime, human_timedelta
from .config import DUE_HOURS, ADMIN_LOG_PATH
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 date string "YYYY-MM-DDThh:mm:ss.mmm+08:00" if status is
| "lent" or "overdue. is None 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
def read(self) -> list:
db = sqlite3.connect(self.path)
db.row_factory = sqlite.Row
umbrellas = db.execute("SELECT * FROM Umbrellas").fetchall()
db.close()
return umbrellas
def update(self, umb) -> dict:
"""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 or None, the old datum will become NULL.
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. Must be UTC+8.
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 = sqlite.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)
diff = {}
status = umb_in_db["status"]
if "status" in umb:
if umb["status"] in STATUSES:
status = umb["status"]
if umb_in_db["status"] != umb["status"]:
diff["status"] = (umb_in_db["status"], umb["status"])
db.execute("UPDATE Umbrellas SET status = ? WHERE id = ?", status, umbid)
else:
raise UmbrellaValueError("status")
if status in ("lent", "overdue"):
for key in (
"tenant_name",
"tenant_id",
"tenant_phone",
"tenant_email",
):
if col in umb:
if umb_in_db[col] != umb[col]:
diff[col] = (umb_in_db[col], umb[col])
db.execute(
"UPDATE Umbrellas SET ? = ? WHERE id = ?",
col,
umb[col],
umbid,
)
if "lent_at" in umb:
try:
# lent_at could be a string, in which case it is parsed
lent_at = datetime.fromisoformat(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.utcoffset(None).seconds != 28800:
# timezone must be +08:00
raise UmbrellaValueError("lent_at")
diff["lent_at"] = (umb_in_db["lent_at"], lent_at.isoformat(timespec="milliseconds"))
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("UPDATE Umbrellas SET ? = NULL WHERE id = ?", col, umbid)
# now that new data are validated, commit the SQL transaction
db.commit()
db.close()
return diff
def take_away(
self, umbid, date, tenant_name, tenant_id, tenant_phone="", tenant_email=""
) -> None:
"""When a user has borrowed an umbrella."""
db = sqlite3.connect(self.path)
db.row_factory = sqlite3.Row
umb = db.execute("SELECT * FROM Umbrellas WHERE id = ?", umbid)
db.close()
if umb is None:
raise UmbrellaNotFoundError(umbid)
if umb["status"] != "available":
raise UmbrellaStatusError
self.update(
{
"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"),
}
)
def give_back(self, umbid, 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.
"""
db = sqlite3.connect(self.path)
db.row_factory = sqlite3.Row
umb = db.execute("SELECT * FROM Umbrellas WHERE id = ?", umbid)
db.close()
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",
}
)
def mark_overdue(self, umbid) -> None:
"""When an umbrella is overdue, change its status to "overdue"."""
db = sqlite3.connect(self.path)
db.row_factory = sqlite3.Row
umb = db.execute("SELECT * FROM Umbrellas WHERE id = ?", umbid)
if umb is None:
raise UmbrellaNotFoundError(umbid)
elif umb["status"] != "lent":
raise UmbrellaStatusError
self.update({"id": umbid, "status": "overdue"})
|