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
|
import { google } from "googleapis";
import { add, set, Duration, parse, format, getDay, subDays, addDays } from "date-fns";
import config from "./config";
interface SheetsRawEntry {
intervalStr: string;
name: string;
lastDoneDateStr: string;
}
interface SheetsProcessedEntry {
name: string;
nextDateStamp: string;
nextDate: Date;
lastDateStamp: string;
lastDate?: Date;
interval: string;
}
const INTERVAL_ABBREVS = {
pv: 1,
vk: 7,
kk: 30,
v: 365,
} as const;
type IntervalAbbrevKey = keyof typeof INTERVAL_ABBREVS;
const strToDate = (s: string) => parse(s, "yyyy-MM-dd", new Date());
const dateToStr = (d: Date) => format(d, "yyyy-MM-dd");
const calculateDuration = (intervalStr: string) => {
const match = /(\d+)(\w+)/.exec(intervalStr);
if (!match) {
throw new Error("Given interval string does not match regular expression");
}
const number = Number.parseInt(match[1]);
const abbrev = match[2];
if (number <= 0) {
throw new Error(`"${number}" is an invalid interval number`);
}
if (!Object.keys(INTERVAL_ABBREVS).includes(abbrev)) {
throw new Error(`"${abbrev}" is an invalid interval string`);
}
const days = INTERVAL_ABBREVS[abbrev as IntervalAbbrevKey];
const totalDuration: Duration = {
days: number * days,
};
return totalDuration;
};
const processRow = (row: SheetsRawEntry) => {
const duration = calculateDuration(row.intervalStr);
const calcValues = () => {
if (row.lastDoneDateStr) {
const lastDate = strToDate(row.lastDoneDateStr);
const nextDate = add(lastDate, duration);
const nextDateStamp = dateToStr(nextDate);
return { lastDate, nextDate, nextDateStamp };
} else {
const lastDate = undefined;
const nextDate = new Date();
const nextDateStamp = dateToStr(nextDate);
return { lastDate, nextDate, nextDateStamp };
}
};
const processedEntry: SheetsProcessedEntry = {
...calcValues(),
name: row.name,
lastDateStamp: row.lastDoneDateStr,
interval: row.intervalStr,
};
return processedEntry;
};
const isThisWeek = (entry: SheetsProcessedEntry): boolean => {
const nextDate = entry.nextDate;
const currentDateTime = new Date();
const today = set(currentDateTime, { hours: 0, minutes: 0, seconds: 0, milliseconds: 0 });
const dayOfWeek = (getDay(today) + 7 - 1) % 7; // getDay returns sunday = 0
const currentWeekStart = subDays(today, dayOfWeek);
const currentWeekEnd = addDays(currentWeekStart, 7);
return nextDate >= currentWeekStart && nextDate < currentWeekEnd;
};
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export const buildSheetsClient = async () => {
const auth = new google.auth.GoogleAuth({
// Scopes can be specified either as an array or as a single, space-delimited string.
scopes: [
"https://www.googleapis.com/auth/spreadsheets",
"https://www.googleapis.com/auth/spreadsheets.readonly",
],
keyFile: config.googleSaJsonPath,
});
// Acquire an auth client, and bind it to all future calls
const authClient = await auth.getClient();
google.options({ auth: authClient });
const sheets = google.sheets({ version: "v4" });
const fetchSheetData = async (): Promise<SheetsRawEntry[]> => {
try {
const res = await sheets.spreadsheets.values.get({
spreadsheetId: config.sheetsSpreadsheetId,
range: config.sheetsRange,
});
const entriesAsLists = res.data.values || [];
const rawEntries: SheetsRawEntry[] = entriesAsLists.map(row => ({
intervalStr: row[0],
name: row[1],
lastDoneDateStr: row[2],
}));
console.log(`Fetched ${rawEntries.length} rows from Sheets.`);
return rawEntries;
} catch (err) {
console.error(err);
throw err;
}
};
const getRightmostColumnInRange = (range: string): string => {
const match = /(.+!)?([A-Z]+?)(\d+):([A-Z]+?)(\d+)/.exec(range);
if (!match) {
throw new Error("Given range does not match regular expression");
}
const sheetName = match[1];
const topLeftRow = Number.parseInt(match[3]);
const bottomRightCol = match[4];
const bottomRightRow = Number.parseInt(match[5]);
const rmCol = bottomRightCol;
const rmRowStart = topLeftRow;
const rmRowEnd = bottomRightRow;
return `${sheetName}${rmCol}${rmRowStart}:${rmCol}${rmRowEnd}`;
};
const updateSheetLastDoneColumn = async (newDateStamps: string[]) => {
const lastDoneColumnRange = getRightmostColumnInRange(config.sheetsRange);
const body = {
values: newDateStamps.map(nds => [nds]),
};
await sheets.spreadsheets.values.update({
spreadsheetId: config.sheetsSpreadsheetId,
range: lastDoneColumnRange,
valueInputOption: "RAW",
requestBody: body,
});
};
const processRows = (rows: SheetsRawEntry[]) => rows.map(processRow);
const filterOnlyThisWeek = (entries: SheetsProcessedEntry[]): SheetsProcessedEntry[] => entries.filter(isThisWeek);
const updatedLastDoneDateStamps = (entries: SheetsProcessedEntry[]): string[] =>
entries.map(e => isThisWeek(e) ? e.nextDateStamp : e.lastDateStamp);
return {
fetchSheetData,
getRightmostColumnInRange,
updateSheetLastDoneColumn,
processRows,
filterOnlyThisWeek,
updatedLastDoneDateStamps,
};
};
|