aboutsummaryrefslogtreecommitdiffstats
path: root/hommaexceli_py/sheets_client.py
diff options
context:
space:
mode:
authorJan Tuomi <jan.tuomi@valuemotive.com>2021-02-14 17:01:19 +0200
committerJan Tuomi <jan.tuomi@valuemotive.com>2021-02-14 17:01:19 +0200
commit54978eb6b515afd1da68642de07e482b09acf9f3 (patch)
treeec310c4a2135be709a7f647e8df9073b5898cd1e /hommaexceli_py/sheets_client.py
parentfbdf6c694b5a92a663eac78230a85a47964a84a1 (diff)
Update last done in Sheets
Diffstat (limited to 'hommaexceli_py/sheets_client.py')
-rw-r--r--hommaexceli_py/sheets_client.py63
1 files changed, 47 insertions, 16 deletions
diff --git a/hommaexceli_py/sheets_client.py b/hommaexceli_py/sheets_client.py
index b30eb3d..9a09f07 100644
--- a/hommaexceli_py/sheets_client.py
+++ b/hommaexceli_py/sheets_client.py
@@ -1,26 +1,20 @@
import pickle
import os.path
import logging
+import re
from os import getenv
from datetime import date
from dataclasses import dataclass
-from googleapiclient.discovery import build
+from googleapiclient.discovery import Resource, build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
-
-@dataclass
-class SheetsRow:
- interval: str
- name: str
- last_done: str
-
- def __str__(self):
- return f"{self.interval}, {self.name}, {self.last_done}"
+from data_parser import ProcessedRow
+from dataclass_defs import SheetsRow
# If modifying these scopes, delete the file token.pickle.
-SCOPES = ["https://www.googleapis.com/auth/spreadsheets.readonly"]
+SCOPES = ["https://www.googleapis.com/auth/spreadsheets"]
def _get_or_default(list, index, default=""):
@@ -36,10 +30,27 @@ def _row_to_dataclass(values):
today = date.today()
last_done = _get_or_default(values, 2, today.strftime("%Y-%m-%d"))
- return SheetsRow(interval, name, last_done)
+ return SheetsRow(interval=interval, name=name, last_done=last_done)
+
+
+def _get_rightmost_column_in_range(range: str) -> str:
+ # Match range of format Sheet!A1:D4
+ match = re.search(r"(.+\!)?([A-Z]+?)(\d+)\:([A-Z]+?)(\d+)", range)
+
+ sheet_name: str = match[1] or ""
+ # topleft_col = match[2]
+ topleft_row = int(match[3])
+ bottomright_col = match[4]
+ bottomright_row = int(match[5])
+
+ rm_col = bottomright_col
+ rm_row_start = topleft_row
+ rm_row_end = bottomright_row
+
+ return f"{sheet_name}{rm_col}{rm_row_start}:{rm_col}{rm_row_end}"
-def authenticate_and_fetch_sheets_data():
+def authenticate_sheets() -> Resource:
logging.info("Reading Google credentials and authenticating...")
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
@@ -59,9 +70,10 @@ def authenticate_and_fetch_sheets_data():
with open("token.pickle", "wb") as token:
pickle.dump(creds, token)
- service = build("sheets", "v4", credentials=creds, cache_discovery=False)
+ return build("sheets", "v4", credentials=creds, cache_discovery=False)
- # Call the Sheets API
+
+def fetch_sheet_data(service: Resource) -> list[SheetsRow]:
logging.info("Calling Sheets API to fetch data...")
sheet = service.spreadsheets()
result = (
@@ -75,4 +87,23 @@ def authenticate_and_fetch_sheets_data():
rows = result.get("values", [])
logging.info(f"Fetched {len(rows)} rows of data")
- return map(_row_to_dataclass, rows)
+ return list(map(_row_to_dataclass, rows))
+
+
+def update_sheet_last_done_column(
+ service: Resource, processed_rows: list[ProcessedRow]
+):
+ logging.info("Calling Sheets API to update last done column...")
+ range = getenv("SHEETS_RANGE")
+ sheet = service.spreadsheets()
+ last_done_column_range = _get_rightmost_column_in_range(range)
+
+ # Update last done date to match next date
+ body = {"values": list(map(lambda row: [row.next_datestamp], processed_rows))}
+
+ sheet.values().update(
+ spreadsheetId=getenv("SHEETS_SPREADSHEET_ID"),
+ range=last_done_column_range,
+ valueInputOption="RAW",
+ body=body,
+ ).execute()