From fa3f7bad8a21e83618cf528db4c38bbfbdb5d7ad Mon Sep 17 00:00:00 2001 From: Frederick Yin Date: Wed, 20 Oct 2021 15:41:34 +0800 Subject: Move database utilities to database.py It may not be a good idea to scatter database utilities around utils.py. With this in mind, I moved them to database.py as static methods under the class Database. --- jimbrella/database.py | 41 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 38 insertions(+), 3 deletions(-) (limited to 'jimbrella/database.py') diff --git a/jimbrella/database.py b/jimbrella/database.py index 3d835a8..7f10c55 100644 --- a/jimbrella/database.py +++ b/jimbrella/database.py @@ -1,6 +1,8 @@ import csv import os -from datetime import datetime +from datetime import datetime, timedelta +from .utils import human_timedelta +from .config import DUE_HOURS class Database: @@ -154,8 +156,41 @@ class Database: return umb def read(self) -> list: - """Currently an alias for `_read()`.""" - return self._read() + """An interface to `_read()` with supplemental data included. + + All exposed methods with a return value should use this method instead of `_read()`. + + Supplemental data: + - lent_time_ago: time since umbrella was taken away by tenant. if umbrella is not + taken away, its value is None. + - lent_time_ago_str: lent_time_ago as a string representation. + """ + umbrellas = self._read() + now = datetime.now() + for idx, umb in enumerate(umbrellas): + if umb["status"] == "lent": + lent_time_ago = now - umb["lent_at"] + umbrellas[idx]["lent_time_ago"] = lent_time_ago + umbrellas[idx]["lent_time_ago_str"] = human_timedelta(lent_time_ago) + return umbrellas + + def group_by_status(umbrellas) -> dict: + """(static method) Returns umbrellas grouped into a dict by their status.""" + keys = set([umb["status"] for umb in umbrellas]) + statuses = {} + for key in keys: + statuses[key] = [umb for umb in umbrellas if umb["status"] == key] + return statuses + + def find_overdue(umbrellas) -> list: + """(static method) Returns umbrellas in possession of their tenant for too long.""" + now = datetime.now() + return [ + umb + for umb in umbrellas + if umb["lent_at"] is not None + and now - umb["lent_at"] > timedelta(hours=DUE_HOURS) + ] def take_away( self, serial, tenant_name, tenant_id, tenant_phone="", tenant_email="" -- cgit v1.2.3