-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcleanup-duplicates.js
More file actions
399 lines (333 loc) · 12.1 KB
/
Copy pathcleanup-duplicates.js
File metadata and controls
399 lines (333 loc) · 12.1 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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
const { google } = require('googleapis');
const path = require('path');
const CREDENTIALS_PATH = path.join(__dirname, 'credentials.json');
const MASTER_SPREADSHEET_ID = '1hSzGYowH0qFmODYJF08vrcvfdcCycs7ztSALjTSDpYs';
async function getAuthClient() {
const auth = new google.auth.GoogleAuth({
keyFile: CREDENTIALS_PATH,
scopes: ['https://www.googleapis.com/auth/spreadsheets'],
});
return auth.getClient();
}
async function getSheetsApi() {
const authClient = await getAuthClient();
return google.sheets({ version: 'v4', auth: authClient });
}
async function readRange(sheets, spreadsheetId, range) {
try {
const response = await sheets.spreadsheets.values.get({ spreadsheetId, range });
return response.data.values || [];
} catch (err) {
console.error(`Error reading ${range} from ${spreadsheetId}:`, err.message);
return [];
}
}
function extractSpreadsheetId(url) {
const match = url.match(/\/spreadsheets\/d\/([a-zA-Z0-9-_]+)/);
return match ? match[1] : null;
}
async function getCrewMappings(sheets) {
const data = await readRange(sheets, MASTER_SPREADSHEET_ID, 'Crew Mappings!A:G');
if (!data || data.length < 2) return [];
const headers = data[0];
const crewCol = headers.indexOf('Crew');
const sheetCol = headers.indexOf('Sheet');
if (crewCol === -1 || sheetCol === -1) return [];
const crews = [];
for (let i = 1; i < data.length; i++) {
const crewName = data[i][crewCol];
const url = data[i][sheetCol];
if (crewName && url) {
const spreadsheetId = extractSpreadsheetId(url);
if (spreadsheetId) {
crews.push({ crewName, spreadsheetId, url });
}
}
}
return crews;
}
async function getSheetId(sheets, spreadsheetId, sheetName) {
const response = await sheets.spreadsheets.get({ spreadsheetId });
const sheet = response.data.sheets.find(s => s.properties.title === sheetName);
return sheet ? sheet.properties.sheetId : null;
}
async function findTasksTable(sheets, spreadsheetId, sheetName) {
const data = await readRange(sheets, spreadsheetId, `'${sheetName}'!A1:Z100`);
if (!data) return null;
for (let row = 0; row < data.length; row++) {
for (let col = 0; col < (data[row]?.length || 0); col++) {
if (data[row][col] === 'Tasks') {
const headerRow = row + 1;
if (headerRow >= data.length) return null;
const header = data[headerRow];
const headerMap = {};
header.forEach((h, i) => {
if (h) headerMap[String(h).trim()] = i;
});
const taskIdx = headerMap['Task'];
const tasks = [];
for (let r = headerRow + 1; r < data.length; r++) {
const taskValue = data[r]?.[taskIdx];
if (!taskValue) break;
tasks.push({
rowIndex: r, // 0-based row in data array
sheetRow: r + 1, // 1-based row in sheet
values: data[r],
header,
headerMap
});
}
return {
anchorRow: row,
headerRow,
header,
headerMap,
tasks,
startCol: col
};
}
}
}
return null;
}
async function findDuplicatesInSheet(sheets, spreadsheetId, sheetName) {
const table = await findTasksTable(sheets, spreadsheetId, sheetName);
if (!table) return { sheetName, duplicates: [] };
const taskIdCol = table.headerMap['TaskID'];
const updatedAtCol = table.headerMap['UpdatedAt'];
const taskNameCol = table.headerMap['Task'];
if (taskIdCol == null) return { sheetName, duplicates: [] };
// Group tasks by TaskID
const byTaskId = {};
for (const task of table.tasks) {
const taskId = task.values[taskIdCol];
if (!taskId) continue;
if (!byTaskId[taskId]) {
byTaskId[taskId] = [];
}
byTaskId[taskId].push({
sheetRow: task.sheetRow,
taskName: task.values[taskNameCol],
taskId,
updatedAt: updatedAtCol != null ? task.values[updatedAtCol] : null
});
}
// Find duplicates (same TaskID appears multiple times)
const duplicates = [];
for (const [taskId, tasks] of Object.entries(byTaskId)) {
if (tasks.length > 1) {
// Sort by UpdatedAt (newer first), then by row (higher row first as tiebreaker)
tasks.sort((a, b) => {
if (a.updatedAt && b.updatedAt) {
return new Date(b.updatedAt) - new Date(a.updatedAt);
}
if (a.updatedAt) return -1;
if (b.updatedAt) return 1;
return b.sheetRow - a.sheetRow;
});
// Keep the first (newest), mark rest for deletion
const keep = tasks[0];
const remove = tasks.slice(1);
duplicates.push({
taskId,
taskName: keep.taskName,
keep: { row: keep.sheetRow, updatedAt: keep.updatedAt },
remove: remove.map(t => ({ row: t.sheetRow, updatedAt: t.updatedAt }))
});
}
}
return { sheetName, table, duplicates };
}
async function deleteRows(sheets, spreadsheetId, sheetName, rows) {
if (rows.length === 0) return;
const sheetId = await getSheetId(sheets, spreadsheetId, sheetName);
if (sheetId == null) {
console.log(` Could not find sheetId for ${sheetName}`);
return;
}
// Sort rows in descending order to delete from bottom up
const sortedRows = [...rows].sort((a, b) => b - a);
const requests = sortedRows.map(row => ({
deleteDimension: {
range: {
sheetId,
dimension: 'ROWS',
startIndex: row - 1, // 0-based
endIndex: row // exclusive
}
}
}));
await sheets.spreadsheets.batchUpdate({
spreadsheetId,
requestBody: { requests }
});
}
async function cleanupDuplicates() {
console.log('\n' + '='.repeat(60));
console.log('CLEANUP: Finding and removing duplicate TaskIDs');
console.log('='.repeat(60) + '\n');
const sheets = await getSheetsApi();
const crews = await getCrewMappings(sheets);
const allSheets = [
{ name: 'Master Tasks', spreadsheetId: MASTER_SPREADSHEET_ID, sheetName: 'Master Tasks' },
...crews.map(c => ({
name: `${c.crewName} Crew`,
spreadsheetId: c.spreadsheetId,
sheetName: `${c.crewName} Crew`
}))
];
let totalRemoved = 0;
for (const sheet of allSheets) {
console.log(`\nChecking ${sheet.name}...`);
try {
const result = await findDuplicatesInSheet(sheets, sheet.spreadsheetId, sheet.sheetName);
if (result.duplicates.length === 0) {
console.log(` No duplicates found`);
continue;
}
console.log(` Found ${result.duplicates.length} TaskID(s) with duplicates:`);
const rowsToDelete = [];
for (const dup of result.duplicates) {
console.log(` TaskID: ${dup.taskId}`);
console.log(` Task: "${dup.taskName}"`);
console.log(` Keeping row ${dup.keep.row} (UpdatedAt: ${dup.keep.updatedAt || 'N/A'})`);
for (const rem of dup.remove) {
console.log(` Deleting row ${rem.row} (UpdatedAt: ${rem.updatedAt || 'N/A'})`);
rowsToDelete.push(rem.row);
}
}
console.log(` Deleting ${rowsToDelete.length} row(s)...`);
await deleteRows(sheets, sheet.spreadsheetId, sheet.sheetName, rowsToDelete);
console.log(` Done!`);
totalRemoved += rowsToDelete.length;
} catch (err) {
console.log(` Error: ${err.message}`);
}
}
console.log('\n' + '='.repeat(60));
console.log(`CLEANUP COMPLETE: Removed ${totalRemoved} duplicate row(s)`);
console.log('='.repeat(60) + '\n');
return totalRemoved;
}
async function testSyncAfterCleanup(sheets) {
console.log('\n' + '='.repeat(60));
console.log('SYNC TEST: Edit a cell and verify propagation');
console.log('='.repeat(60) + '\n');
const crews = await getCrewMappings(sheets);
if (crews.length === 0) {
console.log('No crews found to test with');
return false;
}
// Find a task in Master that has a crew assignment
const masterTable = await findTasksTable(sheets, MASTER_SPREADSHEET_ID, 'Master Tasks');
if (!masterTable || masterTable.tasks.length === 0) {
console.log('No tasks found in Master Tasks');
return false;
}
const crewsCol = masterTable.headerMap['Crews'];
const taskIdCol = masterTable.headerMap['TaskID'];
const notesCol = masterTable.headerMap['Notes'];
if (notesCol == null) {
console.log('Notes column not found - cannot test');
return false;
}
// Find a task with a crew assignment
let testTask = null;
let testCrew = null;
for (const task of masterTable.tasks) {
const taskId = task.values[taskIdCol];
const crewsValue = task.values[crewsCol];
if (taskId && crewsValue) {
const crewNames = crewsValue.split(',').map(c => c.trim().toLowerCase());
for (const crew of crews) {
if (crewNames.includes(crew.crewName.toLowerCase())) {
testTask = task;
testCrew = crew;
break;
}
}
if (testTask) break;
}
}
if (!testTask || !testCrew) {
console.log('Could not find a task with crew assignment to test');
return false;
}
const taskId = testTask.values[taskIdCol];
const taskName = testTask.values[masterTable.headerMap['Task']];
const originalNotes = testTask.values[notesCol] || '';
const testMarker = `[SYNC TEST ${Date.now()}]`;
const newNotes = originalNotes ? `${originalNotes} ${testMarker}` : testMarker;
console.log(`Test task: "${taskName}"`);
console.log(`TaskID: ${taskId}`);
console.log(`Testing with crew: ${testCrew.crewName}`);
console.log(`Original Notes: "${originalNotes}"`);
console.log(`New Notes: "${newNotes}"\n`);
// Update Notes in Master Tasks
const notesCell = `'Master Tasks'!${String.fromCharCode(65 + masterTable.startCol + notesCol)}${testTask.sheetRow}`;
console.log(`Updating Master Tasks at ${notesCell}...`);
await sheets.spreadsheets.values.update({
spreadsheetId: MASTER_SPREADSHEET_ID,
range: notesCell,
valueInputOption: 'USER_ENTERED',
requestBody: { values: [[newNotes]] },
});
console.log('Master Tasks updated');
// Wait for Apps Script trigger
console.log('\nWaiting 15 seconds for sync trigger to run...');
await new Promise(resolve => setTimeout(resolve, 15000));
// Check crew sheet
const crewSheetName = `${testCrew.crewName} Crew`;
console.log(`\nChecking ${crewSheetName} for sync...`);
const crewTable = await findTasksTable(sheets, testCrew.spreadsheetId, crewSheetName);
if (!crewTable) {
console.log(`Could not find Tasks table in ${crewSheetName}`);
return false;
}
const crewTaskIdCol = crewTable.headerMap['TaskID'];
const crewNotesCol = crewTable.headerMap['Notes'];
let syncSuccess = false;
for (const crewTask of crewTable.tasks) {
if (crewTask.values[crewTaskIdCol] === taskId) {
const crewNotes = crewTask.values[crewNotesCol] || '';
if (crewNotes.includes(testMarker)) {
console.log(`SYNC SUCCESSFUL! Found test marker in ${crewSheetName}`);
console.log(` Notes in crew: "${crewNotes}"`);
syncSuccess = true;
} else {
console.log(`SYNC FAILED - Task found but Notes not updated`);
console.log(` Notes in crew: "${crewNotes}"`);
console.log(` Expected to contain: "${testMarker}"`);
}
break;
}
}
// Clean up
console.log('\nRestoring original Notes...');
await sheets.spreadsheets.values.update({
spreadsheetId: MASTER_SPREADSHEET_ID,
range: notesCell,
valueInputOption: 'USER_ENTERED',
requestBody: { values: [[originalNotes]] },
});
console.log('Restored');
return syncSuccess;
}
async function main() {
const sheets = await getSheetsApi();
// Step 1: Clean up duplicates
const removedCount = await cleanupDuplicates();
// Step 2: Test sync
if (removedCount >= 0) {
console.log('\nWaiting 5 seconds before testing sync...\n');
await new Promise(resolve => setTimeout(resolve, 5000));
const syncSuccess = await testSyncAfterCleanup(sheets);
console.log('\n' + '='.repeat(60));
console.log('FINAL RESULTS');
console.log('='.repeat(60));
console.log(`Duplicates removed: ${removedCount}`);
console.log(`Sync test: ${syncSuccess ? 'PASSED' : 'FAILED or not triggered'}`);
console.log('='.repeat(60) + '\n');
}
}
main().catch(console.error);