-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCode.js
More file actions
340 lines (287 loc) · 11.7 KB
/
Copy pathCode.js
File metadata and controls
340 lines (287 loc) · 11.7 KB
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
/**********************
* MedOps Calendar Sync
**********************/
const CALENDAR_ID = 'c_39024d4a6fcdd79dd21f17a9b3d9368b00489d102b07c044dba49d643d7aee0e@group.calendar.google.com';
const TIMEZONE = 'America/Los_Angeles';
const EVENT_ID_CANON = 'event id';
const MAX_SHIFT_HOURS = 5; // used if no end time is specified
const HARD_STOP_TIME = '23:30';// or latest same-day end for single time
// Sheet name matcher checks if name contains: "January", "Feb 2025", "7-2025", etc.
const MONTH_SHEET_RE = /jan(uary)?|feb(ruary)?|mar(ch)?|apr(il)?|may|jun(e)?|jul(y)?|aug(ust)?|sep(t)?(ember)?|oct(ober)?|nov(ember)?|dec(ember)?|\d{1,2}[-/_]\d{2,4}/i;
function onOpen() {
SpreadsheetApp.getUi()
.createMenu('MedOps Calendar')
.addItem('Process ACTIVE sheet', 'processActiveSheet')
.addItem('Process ALL month sheets', 'processAllMonthSheets')
.addToUi();
}
function processActiveSheet() {
processSheet(SpreadsheetApp.getActive().getActiveSheet());
}
function processAllMonthSheets() {
const ss = SpreadsheetApp.getActive();
const sheets = ss.getSheets();
const monthLike = sheets.filter(sh => MONTH_SHEET_RE.test(sh.getName()));
(monthLike.length ? monthLike : sheets).forEach(processSheet);
}
function processSheet(sheet) {
const calendar = CalendarApp.getCalendarById(CALENDAR_ID);
if (!calendar) throw new Error('Calendar not found. Check CALENDAR_ID.');
const values = sheet.getDataRange().getValues();
if (values.length < 2) return;
// 1) Detect header row in first 10 rows
const { headerRowIdx, header } = detectHeader(values);
if (headerRowIdx === -1) {
console.log(`No header row detected on sheet "${sheet.getName()}". Skipping.`);
return;
}
// 2) Fuzzy-map columns
const colIndex = indexHeadersFuzzy(header);
// 3) Ensure/locate Event ID column on header row
ensureOrLocateEventIdColumn(sheet, headerRowIdx, header, colIndex);
console.log(`Sheet "${sheet.getName()}": header row = ${headerRowIdx + 1}`);
console.log(`Columns -> Date:${colIndex.date} Name:${colIndex.name} Location:${colIndex.location} Shift:${colIndex.shift} EventID:${colIndex.eventId}`);
let lastDate = null;
let lastName = '';
let lastLocation = '';
// 4) Process rows after header
for (let r = headerRowIdx + 1; r < values.length; r++) {
const row = values[r];
const rawDate = safeCell(row, colIndex.date);
const rawName = safeCell(row, colIndex.name);
const rawLocation = safeCell(row, colIndex.location);
const shiftVal = rowValue(row, colIndex.shift); // keep original (Date or String)
const existingId = safeCell(row, colIndex.eventId);
// Skip spacer rows
if (!rawDate && !rawName && !shiftVal) continue;
// Carry-forward for multi-row events
lastDate = rawDate || lastDate;
lastName = rawName || lastName;
lastLocation = rawLocation || lastLocation;
// Need date, name, shift
if (!lastDate || !lastName || !shiftVal) continue;
const eventDate = normalizeDate(lastDate);
if (!eventDate) {
console.log(`Row ${r + 1}: bad/empty date "${lastDate}"`);
continue;
}
// Compute times (robust to single time / ranges / Date values)
let start, end;
try {
({ start, end } = computeShiftTimes(eventDate, shiftVal));
} catch (e) {
console.log(`Row ${r + 1}: bad time "${shiftVal}" → ${e.message}`);
continue;
}
const title = String(lastName).replace(/\s+/g, ' ').replace(/^"|"$/g, '').trim();
const location = String(lastLocation || '').trim();
const description = buildDescription(row, header, colIndex);
try {
if (existingId) {
// Update existing event (if found), else recreate and store new ID
const evt = CalendarApp.getCalendarById(CALENDAR_ID).getEventById(existingId);
if (evt) {
const needTimeUpdate = (evt.getStartTime().getTime() !== start.getTime()) ||
(evt.getEndTime().getTime() !== end.getTime());
if (evt.getTitle() !== title) evt.setTitle(title);
if (evt.getLocation() !== location) evt.setLocation(location);
if (evt.getDescription() !== description) evt.setDescription(description);
if (needTimeUpdate) evt.setTime(start, end);
continue; // done with this row
} else {
// Event was deleted or ID invalid → create new
const newEvt = CalendarApp.getCalendarById(CALENDAR_ID).createEvent(title, start, end, {
location, description
});
sheet.getRange(r + 1, colIndex.eventId + 1).setValue(newEvt.getId());
console.log(`Recreated: ${title} @ ${start.toLocaleString()}`);
continue;
}
}
// No existing ID → create fresh
const event = CalendarApp.getCalendarById(CALENDAR_ID).createEvent(title, start, end, {
location, description
});
sheet.getRange(r + 1, colIndex.eventId + 1).setValue(event.getId());
console.log(`Created: ${title} @ ${start.toLocaleString()}`);
} catch (e) {
console.log(`Row ${r + 1}: failed to create/update event → ${e.message}`);
}
}
}
/* ---------- Helpers ---------- */
function detectHeader(values) {
// A header row contains at least two of: date, name, location, shift/time
const KEY_PATTERNS = [/date/i, /name/i, /location|venue|place/i, /shift|time/i];
const maxScan = Math.min(values.length, 10);
for (let i = 0; i < maxScan; i++) {
const row = values[i].map(v => String(v || '').trim());
let hits = 0;
for (const cell of row) {
if (KEY_PATTERNS.some(rx => rx.test(cell))) hits++;
}
if (hits >= 2) return { headerRowIdx: i, header: row };
}
return { headerRowIdx: -1, header: [] };
}
function indexHeadersFuzzy(header) {
const lower = header.map(h => h.toLowerCase());
const findOne = (alts) => {
for (const a of alts) {
const i = lower.findIndex(h => h.includes(a));
if (i !== -1) return i;
}
return null;
};
const date = findOne(['date']);
const name = findOne(['name of event', 'event name', 'name']);
const location = findOne(['location', 'venue', 'place']);
const shift = findOne(['shift time', 'shift', 'time']);
const notes = findOne(['notes', 'note']);
const medops = findOne(['medops', 'med ops', 'med-ops']);
// EMTs = cols between Shift and Notes/Medops
let emtStart = shift != null ? shift + 1 : null;
let emtEnd = header.length - 1;
if (notes != null) emtEnd = Math.min(emtEnd, notes - 1);
if (medops != null) emtEnd = Math.min(emtEnd, medops - 1);
const emtCols = (emtStart != null && emtStart <= emtEnd)
? Array.from({ length: emtEnd - emtStart + 1 }, (_, i) => emtStart + i)
: [];
// Event ID
let eventId = lower.findIndex(h => h.includes(EVENT_ID_CANON));
if (eventId === -1) eventId = null;
return { date, name, location, shift, notes, medops, emtCols, eventId };
}
function ensureOrLocateEventIdColumn(sheet, headerRowIdx, header, colIndex) {
if (colIndex.eventId != null) return;
const row1 = headerRowIdx + 1;
const lastCol = header.length + 1; // 1-based to append
sheet.getRange(row1, lastCol).setValue('Event ID');
colIndex.eventId = lastCol - 1; // store 0-based index
}
function safeCell(row, i) {
if (i == null) return '';
const v = row[i];
if (v instanceof Date) return v; // pass Date through
return (v == null) ? '' : String(v).trim();
}
function rowValue(row, i) {
if (i == null) return '';
return row[i]; // raw: may be string, Date, or empty
}
function buildDescription(row, header, colIndex) {
const lines = [];
if (colIndex.location != null) {
const loc = safeCell(row, colIndex.location);
if (loc) lines.push(`Location: ${loc}`);
}
if (colIndex.emtCols && colIndex.emtCols.length) {
const emtLines = [];
colIndex.emtCols.forEach((c) => {
const label = (header[c] || '').replace(/^EMTs?\s*/i, '');
const val = safeCell(row, c);
if (val) emtLines.push(`• ${label} ${val}`);
});
if (emtLines.length) {
lines.push('---', 'EMTs / Staffing:', ...emtLines);
}
}
const notes = safeCell(row, colIndex.notes);
if (notes) lines.push('---', `Notes: ${notes}`);
const medops = safeCell(row, colIndex.medops);
if (medops) lines.push('---', `MedOps: ${medops}`);
return lines.join('\n');
}
function normalizeDate(value) {
if (value instanceof Date) {
return new Date(value.getFullYear(), value.getMonth(), value.getDate(), 0, 0, 0);
}
const s = String(value).trim();
if (!s) return null;
const m = s.match(/^(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{2,4})$/);
if (m) {
let [_, mm, dd, yy] = m;
mm = parseInt(mm, 10) - 1;
dd = parseInt(dd, 10);
yy = parseInt(yy, 10);
yy = yy < 100 ? 2000 + yy : yy;
return new Date(yy, mm, dd, 0, 0, 0);
}
const d = new Date(s);
return isNaN(d) ? null : new Date(d.getFullYear(), d.getMonth(), d.getDate(), 0, 0, 0);
}
/** Compute start/end from shift value:
* - If Date: treat as time-of-day on eventDate (single time)
* - If String range: "9:00-13:00", "9am-1pm", "09:00–13:00"
* - If String single time: apply 8h/23:30 rule
*/
function computeShiftTimes(eventDate, shiftVal) {
// Case 1: time cell is a Date (Google Sheets time)
if (shiftVal instanceof Date) {
const { hours, minutes } = { hours: shiftVal.getHours(), minutes: shiftVal.getMinutes() };
const start = new Date(eventDate.getFullYear(), eventDate.getMonth(), eventDate.getDate(), hours, minutes, 0);
const end = capSingleEnd(start, eventDate);
return { start, end };
}
// Case 2: parse string
const raw = String(shiftVal).trim();
if (!raw) throw new Error('Empty time');
// Normalize dashes
const norm = raw.replace(/[–—−]/g, '-').replace(/\s+/g, ' ');
const parts = norm.split('-').map(s => s.trim());
if (parts.length > 1 && parts[1]) {
// Range
const start = parseFlexibleTimeOnDate(eventDate, parts[0]);
let end = parseFlexibleTimeOnDate(eventDate, parts[1]);
if (end <= start) {
// Overnight → push to next day
end = new Date(end.getTime() + 24 * 60 * 60 * 1000);
}
return { start, end };
} else {
// Single time
const start = parseFlexibleTimeOnDate(eventDate, parts[0]);
const end = capSingleEnd(start, eventDate);
return { start, end };
}
}
function capSingleEnd(start, eventDate) {
const eightHours = new Date(start.getTime() + MAX_SHIFT_HOURS * 60 * 60 * 1000);
const hardStop = parseFlexibleTimeOnDate(eventDate, HARD_STOP_TIME);
let end = new Date(Math.min(eightHours.getTime(), hardStop.getTime()));
if (end <= start) end = new Date(start.getTime() + 30 * 60 * 1000);
return end;
}
/** Parse flexible time strings:
* Accepts:
* - "9", "09", "9:00", "09:00", "9am", "9:30am", "9 pm", "12:15AM", 24h, "18:30"
*/
function parseFlexibleTimeOnDate(dayDate, timeStr) {
const s = String(timeStr).trim().toLowerCase();
// "9", "09"
let m = s.match(/^(\d{1,2})$/);
if (m) {
const hh = parseInt(m[1], 10);
if (hh >= 0 && hh <= 23) {
return new Date(dayDate.getFullYear(), dayDate.getMonth(), dayDate.getDate(), hh, 0, 0);
}
}
// "9am", "9pm", "9 am", "9:30am", "09:30 pm"
m = s.match(/^(\d{1,2})(?::(\d{2}))?\s*(am|pm)$/i);
if (m) {
let hh = parseInt(m[1], 10);
const mm = m[2] ? parseInt(m[2], 10) : 0;
const ap = m[3].toLowerCase();
if (ap === 'pm' && hh < 12) hh += 12;
if (ap === 'am' && hh === 12) hh = 0;
return new Date(dayDate.getFullYear(), dayDate.getMonth(), dayDate.getDate(), hh, mm, 0);
}
// "09:00", "9:00", "18:30"
m = s.match(/^(\d{1,2}):(\d{2})$/);
if (m) {
const hh = parseInt(m[1], 10);
const mm = parseInt(m[2], 10);
return new Date(dayDate.getFullYear(), dayDate.getMonth(), dayDate.getDate(), hh, mm, 0);
}
throw new Error(`Unrecognized time: "${timeStr}"`);
}