aboutsummaryrefslogtreecommitdiffstats
path: root/hommaexceli_py/parser.py
blob: b4abb46f9318bb57f71582d5753b50c4c911c37b (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
import datetime
import logging
import re
from sheets_client import SheetsRow

INTERVAL_ABBREVS = {
    "pv": datetime.timedelta(days=1),
    "vk": datetime.timedelta(days=7),
    "kk": datetime.timedelta(days=30),
    "v": datetime.timedelta(days=365),
}


def _calculate_interval(interval_str: str):
    match = re.search(r"(\d+)(\w+)", interval_str)
    number = int(match[1])
    abbrev = match[2]

    try:
        interval = INTERVAL_ABBREVS[abbrev]
    except KeyError:
        raise Exception(f'"{interval_str}" is an invalid interval string!')

    total_interval = datetime.timedelta(seconds=interval.total_seconds() * number)
    return total_interval


def _timestamp_to_date(timestamp: str):
    return datetime.datetime.strptime(timestamp, "%Y-%m-%d")


def _date_to_timestamp(date):
    return datetime.datetime.strftime(date, "%Y-%m-%d")


def _process_row(row: SheetsRow):
    interval = _calculate_interval(row.interval)
    last_done_date = _timestamp_to_date(row.last_done)
    next_date = last_done_date + interval
    next_date_str = _date_to_timestamp(next_date)
    return (row.last_done, row.interval, next_date_str, row.name)


def process_rows(rows: list[SheetsRow]):
    return map(_process_row, rows)