summaryrefslogtreecommitdiff
path: root/jimbrella/routine.py
blob: e120517f21fa5da7d9e5add973fa2ccf2466615b (plain)
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
from datetime import datetime, timedelta
from dateutil.parser import isoparse
import logging
from .umbrellas import Umbrellas
from .jform import JForm
from .sms import SMS
from .exceptions import *
from .config import config
from .utils import human_datetime, CST

"""A set of routine methods, run at an interval (somewhere from ten minutes to one hour), to:
- sync JImbrella's databse against data pulled from jForm
- check if any umbrella is now overdue
- send an SMS where applicable, to a user or an admin
"""


def chronological_merge(*sheet_lists) -> list:
    """Merges all lists answer sheets passed in, in chronological order, into a single list.

    All lists of sheets in sheet_lists MUST be already in chronological order.
    By "chronological", we mean sorting by the value under key "date".
    """
    chronicle = []
    while any(sheet_lists):  # at least one list in `sheet_lists` is non-empty
        # for each list of sheets, read date from its first element, then find the earliest
        # is an instance of datetime.datetime
        # only pass non-empty lists to min():
        earliest_date = min(
            [sheet_list[0]["date"] for sheet_list in filter(None, sheet_lists)]
        )
        for idx, sheet_list in enumerate(sheet_lists):
            if not sheet_list:  # is empty
                continue
            if sheet_list[0]["date"] == earliest_date:
                # remove the first element and append it to `chronicle`, if it is the earliest
                chronicle.append(sheet_lists[idx].pop(0))
                # we do not directly break here because there exists a tiny chance
                # two answer sheets were submitted at the exact same millisecond
    return chronicle


def sync_jform(takeaway: JForm, giveback: JForm, db: Umbrellas, sms: SMS):
    takeaway_unread = takeaway.get_unread()
    giveback_unread = giveback.get_unread()
    logging.info(
        "Sync jForm: found %d unread takeaway sheet(s) and %d unread giveback sheet(s)",
        len(takeaway_unread),
        len(giveback_unread),
    )
    unread = chronological_merge(takeaway_unread, giveback_unread)
    # NOTE: beyond this point `takeaway_unread` and `giveback_unread` are empty
    #       because chronological_merge popped all their elements
    for sheet in unread:
        sheet["date_str"] = sheet["date"].isoformat(timespec="milliseconds")
        tenant_identity = "{name} (ID: {id}, phone: {phone})".format(**sheet)
        if sheet["jform_name"] == "takeaway":
            try:
                db.take_away(
                    sheet["key"],
                    sheet["date"],
                    sheet["name"],
                    sheet["id"],
                    sheet["phone"],
                )
                sms.borrow_success(
                    sheet["phone"],
                    sheet["name"],
                    human_datetime(sheet["date"]),
                    sheet["key"],
                )
            except (UmbrellaStatusError, UmbrellaNotFoundError):
                logging.warning(
                    tenant_identity
                    + " attempted to borrow umbrella #{key} at {date_str}".format(
                        **sheet
                    )
                )
        elif sheet["jform_name"] == "giveback":
            try:
                db.give_back(sheet["key"], sheet["date"], sheet["name"], sheet["id"])
                logging.info(
                    tenant_identity
                    + " returned umbrella #{key} at {date_str}".format(**sheet)
                )
                sms.return_success(
                    sheet["phone"],
                    sheet["name"],
                    human_datetime(sheet["date"]),
                    sheet["key"],
                )
            except (UmbrellaStatusError, UmbrellaNotFoundError):
                logging.warning(
                    tenant_identity
                    + " attempted to return umbrella #{key} at {date_str}".format(
                        **sheet
                    )
                )
            except TenantIdentityError as e:
                logging.warning(
                    tenant_identity
                    + " attempted to return umbrella #{key} at {date_str}, expecting tenant {expected}".format(
                        expected=e.expected, **sheet
                    )
                )


def process_overdue(db: Umbrellas):
    """mark and log umbrellas that were not, but just became overdue"""
    umbrellas = db.read()
    now = datetime.now().astimezone(CST)
    for umb in umbrellas:
        if umb["status"] == "lent":
            try:
                lent_at = isoparse(umb["lent_at"])
            except ValueError:
                logging.error(
                    "Invalid lent_at in umbrella #%d: %s", umb["id"], umb["lent_at"]
                )
                continue

            if now - lent_at > timedelta(hours=config.getint("general", "due_hours")):
                db.mark_overdue(umb["id"])
                logging.warning(
                    "Umbrella #{id} is now overdue, tenant: {tenant_name} (ID: {tenant_id}, phone: {tenant_phone})".format(
                        **umb
                    )
                )
                sms.remind_overdue(
                    umb["tenant_phone"],
                    umb["tenant_name"],
                    human_datetime(isoparse(umb["lent_at"])),
                    umb["id"],
                )


if __name__ == "__main__":
    takeaway = JForm(
        "takeaway",
        config.get("jform", "takeaway_url"),
        config.get("jform", "bookmark_dir"),
    )
    giveback = JForm(
        "giveback",
        config.get("jform", "giveback_url"),
        config.get("jform", "bookmark_dir"),
    )
    db = Umbrellas(config.get("general", "db_path"))
    sms = SMS()
    sync_jform(takeaway, giveback, db, sms)
    process_overdue(db)