-
Notifications
You must be signed in to change notification settings - Fork 2
/
popup.js
397 lines (352 loc) · 15.3 KB
/
popup.js
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
let allOrderNumbers = new Set();
let downloadInProgress = false;
let timeout = 1000;
document.addEventListener("DOMContentLoaded", function () {
const startButton = document.getElementById("startCollection");
const stopButton = document.getElementById("stopCollection");
const progressElement = document.getElementById("progress");
const orderNumbersContainer = document.getElementById("orderNumbersContainer");
const pageLimitInput = document.getElementById("pageLimit");
progressElement.style.display = "none";
document.getElementById('faqButton').addEventListener('click', function(e) {
e.preventDefault();
chrome.tabs.create({
url: chrome.runtime.getURL('faq/faq.html')
});
});
// Add loading spinner function
function setButtonLoading(button, isLoading) {
const btnText = button.querySelector(".btn-text");
if (isLoading) {
button.disabled = true;
if (!button.querySelector(".loading-spinner")) {
const spinner = document.createElement("span");
spinner.className = "loading-spinner";
button.insertBefore(spinner, btnText);
}
} else {
button.disabled = false;
const spinner = button.querySelector(".loading-spinner");
if (spinner) spinner.remove();
}
}
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
var tab = tabs[0];
var url = tab.url;
if (url.startsWith("https://www.walmart.com/orders")) {
const cleanUrl = url.replace(/\/$/, "");
const orderPath = cleanUrl.split("/orders/")[1];
// Check if there's an order number after /orders/
if (orderPath && /^\d{10,}$/.test(orderPath.split("?")[0])) {
// Individual order page
const orderNumber = orderPath.split("?")[0];
console.log("Valid order number:", orderNumber);
displayOrderNumbers([orderNumber]);
// Hide unnecessary UI elements
document.querySelector(".card").style.display = "none";
document.getElementById("progress").style.display = "none";
document.getElementsByClassName("checkbox-container")[0].style.display = "none";
} else {
// Main orders page setup
startButton.addEventListener("click", function () {
const pageLimit = parseInt(pageLimitInput.value, 10);
startButton.style.display = "none";
stopButton.style.display = "inline-flex";
setButtonLoading(startButton, true);
chrome.runtime.sendMessage(
{
action: "startCollection",
url: url,
pageLimit: pageLimit,
},
function (response) {
if (response.status === "started") {
updateProgress();
}
setButtonLoading(startButton, false);
}
);
});
stopButton.addEventListener("click", function () {
setButtonLoading(stopButton, true);
chrome.runtime.sendMessage({ action: "stopCollection" }, function (response) {
if (response.status === "stopped") {
stopButton.style.display = "none";
startButton.style.display = "inline-flex";
startButton.querySelector(".btn-text").textContent = "Restart Collection";
setButtonLoading(stopButton, false);
}
});
});
}
} else {
document.body.innerHTML = `
<div class="card" style="text-align: center; padding: 24px;">
<svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="#e41e31" stroke-width="2" style="margin-bottom: 16px;">
<circle cx="12" cy="12" r="10"></circle>
<line x1="12" y1="8" x2="12" y2="12"></line>
<line x1="12" y1="16" x2="12.01" y2="16"></line>
</svg>
<p style="color: var(--text); font-size: 16px; margin-bottom: 8px;">Please navigate to</p>
<p style="color: var(--primary); font-weight: 500; margin-bottom: 16px;"><a href="https://walmart.com/orders" target="_blank">walmart.com/orders</a></p>
<p style="color: var(--text-secondary); font-size: 14px;">to use this extension.</p>
</div>`;
}
});
});
function updateProgress() {
chrome.runtime.sendMessage({ action: "getProgress" }, function (response) {
if (response.isCollecting) {
updateProgressUI(response.currentPage, response.pageLimit, true);
displayOrderNumbers(response.orderNumbers);
setTimeout(updateProgress, 1000);
// set all checkboxes to disabled
const checkboxes = document.querySelectorAll('input[type="checkbox"]');
checkboxes.forEach((cb) => (cb.disabled = true));
} else {
updateProgressUI(response.currentPage, response.pageLimit, false);
displayOrderNumbers(response.orderNumbers);
document.getElementById("startCollection").style.display = "inline-flex";
document.getElementById("stopCollection").style.display = "none";
document.getElementById("startCollection").querySelector(".btn-text").textContent = "Start Collection";
// set all checkboxes to enabled
const checkboxes = document.querySelectorAll('input[type="checkbox"]');
checkboxes.forEach((cb) => (cb.disabled = false));
}
});
}
function updateProgressUI(currentPage, pageLimit, inProgress) {
const progressElement = document.getElementById("progress") || createProgressElement();
const pageLimitText = pageLimit > 0 ? ` of ${pageLimit}` : "";
document.getElementById("progress").style.display = "block";
if (inProgress) {
console.log("Progress:", currentPage, pageLimit);
progressElement.innerHTML = `
<span class="loading-spinner" style="border-color: var(--primary); border-top-color: transparent;"></span>
Fetching order numbers... Fetching Page ${currentPage}${pageLimitText}
`;
} else {
progressElement.textContent = `Collection ${pageLimit > 0 && currentPage >= pageLimit ? "reached limit" : "completed"}. Total pages: ${
pageLimit > 0 ? currentPage : currentPage - 1
}`;
}
}
function createProgressElement() {
const progressElement = document.createElement("div");
progressElement.id = "progress";
document.body.insertBefore(progressElement, document.getElementById("orderNumbersContainer"));
return progressElement;
}
function displayOrderNumbers(orderNumbers) {
const container = document.getElementById("orderNumbersContainer");
container.innerHTML = "<h3>Select orders to download</h3>";
// Create select all checkbox
const selectAllDiv = document.createElement("div");
selectAllDiv.className = "checkbox-container";
const selectAll = document.createElement("input");
selectAll.type = "checkbox";
selectAll.id = "selectAll";
const selectAllLabel = document.createElement("label");
selectAllLabel.htmlFor = "selectAll";
selectAllLabel.appendChild(document.createTextNode("Select All"));
selectAllDiv.appendChild(selectAll);
selectAllDiv.appendChild(selectAllLabel);
container.appendChild(selectAllDiv);
// Create order list container with scrollable area
const orderList = document.createElement("div");
orderList.style.maxHeight = "200px";
orderList.style.overflowY = "auto";
orderList.style.marginBottom = "16px";
// Add individual order checkboxes
orderNumbers.forEach((orderNumber) => {
const div = document.createElement("div");
div.className = "checkbox-container";
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.id = orderNumber;
checkbox.value = orderNumber;
const label = document.createElement("label");
label.htmlFor = orderNumber;
label.appendChild(document.createTextNode(`Order #${orderNumber}`));
div.appendChild(checkbox);
div.appendChild(label);
orderList.appendChild(div);
});
container.appendChild(orderList);
// Add select all functionality
selectAll.addEventListener("change", function () {
const checkboxes = orderList.querySelectorAll('input[type="checkbox"]');
checkboxes.forEach((cb) => (cb.checked = selectAll.checked));
});
// Add download button if there are order numbers
if (orderNumbers.length > 0 && !document.getElementById("downloadButton")) {
const downloadButton = document.createElement("button");
downloadButton.id = "downloadButton";
downloadButton.className = "btn btn-success";
downloadButton.innerHTML = `
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
<polyline points="7 10 12 15 17 10"></polyline>
<line x1="12" y1="15" x2="12" y2="3"></line>
</svg>
Download Selected Orders
`;
downloadButton.addEventListener("click", downloadSelectedOrders);
container.appendChild(downloadButton);
}
}
async function downloadSelectedOrders() {
if (downloadInProgress) {
alert("Downloads are already in progress. Please wait.");
return;
}
const selectedOrders = Array.from(document.querySelectorAll('input[type="checkbox"]:checked'))
.map((cb) => cb.value)
.filter((value) => value !== "on");
if (selectedOrders.length === 0) {
alert("Please select at least one order to download.");
return;
}
const downloadButton = document.getElementById("downloadButton");
downloadButton.disabled = true;
setButtonLoading(downloadButton, true);
downloadInProgress = true;
let downloadTab = null;
const failedOrders = [];
// Helper function to attempt download with specific URL
async function attemptDownload(orderNumber, url, attempt) {
try {
// Create or reuse tab
if (!downloadTab) {
downloadTab = await new Promise((resolve) => {
chrome.tabs.create({ url: url, active: false }, resolve);
});
} else {
await new Promise((resolve) => {
chrome.tabs.update(downloadTab.id, { url: url }, resolve);
});
}
// Wait for page load and trigger download with timeout
await Promise.race([
new Promise((resolve, reject) => {
async function handleDownload(tabId, info) {
if (tabId === downloadTab.id && info.status === "complete") {
chrome.tabs.onUpdated.removeListener(handleDownload);
try {
// First, block images
await new Promise((blockResolve) => {
chrome.tabs.sendMessage(downloadTab.id, { action: "blockImagesForDownload" }, (response) => {
if (chrome.runtime.lastError) {
console.error("Error blocking images:", chrome.runtime.lastError);
}
// Continue even if blocking fails
blockResolve();
});
});
// Wait a bit longer for the page to stabilize
await new Promise((r) => setTimeout(r, 1000));
// Then proceed with download
chrome.tabs.sendMessage(downloadTab.id, { method: "downloadXLSX" }, (response) => {
if (chrome.runtime.lastError) {
reject(new Error(`Failed to download order #${orderNumber}: ${chrome.runtime.lastError.message}`));
} else {
resolve();
}
});
} catch (error) {
reject(error);
}
}
}
chrome.tabs.onUpdated.addListener(handleDownload);
}),
new Promise((_, reject) => setTimeout(() => reject(new Error(`Timeout downloading order #${orderNumber}`)), 30000))
]);
return true; // Download successful
} catch (error) {
console.error(`Error downloading order #${orderNumber} (attempt ${attempt}):`, error);
return false; // Download failed
}
}
try {
// Create progress indicator
const progressDiv = document.createElement("div");
progressDiv.id = "downloadProgress";
document.getElementById("progress").style.display = "none";
document.getElementById("progress").insertAdjacentElement("afterend", progressDiv);
for (let i = 0; i < selectedOrders.length; i++) {
const orderNumber = selectedOrders[i];
progressDiv.innerHTML = `
<span class="loading-spinner" style="border-color: var(--success); border-top-color: transparent;"></span>
Downloading order ${i + 1} of ${selectedOrders.length} (#${orderNumber})...
`;
let downloadSuccess = false;
const isLongOrderNumber = orderNumber.length >= 20;
// First attempt with default parameter based on order number length
let firstAttemptUrl = `https://www.walmart.com/orders/${orderNumber}${isLongOrderNumber ? '?storePurchase=true' : ''}`;
downloadSuccess = await attemptDownload(orderNumber, firstAttemptUrl, 1);
// If first attempt fails, try with opposite parameter
if (!downloadSuccess) {
progressDiv.innerHTML = `
<span class="loading-spinner" style="border-color: var(--success); border-top-color: transparent;"></span>
Retrying order ${i + 1} of ${selectedOrders.length} (#${orderNumber}) with different parameters...
`;
let secondAttemptUrl = `https://www.walmart.com/orders/${orderNumber}${isLongOrderNumber ? '' : '?storePurchase=true'}`;
downloadSuccess = await attemptDownload(orderNumber, secondAttemptUrl, 2);
}
// If both attempts fail, add to failed orders
if (!downloadSuccess) {
failedOrders.push(orderNumber);
}
await new Promise(resolve => setTimeout(resolve, 500));
}
// Cleanup
if (downloadTab) {
chrome.tabs.remove(downloadTab.id);
}
// Show completion message with failed orders if any
if (failedOrders.length === 0) {
progressDiv.innerHTML = `
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="var(--success)" stroke-width="2" style="margin-right: 8px;">
<path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path>
<polyline points="22 4 12 14.01 9 11.01"></polyline>
</svg>
All downloads completed successfully!
`;
} else {
progressDiv.innerHTML = `
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="var(--danger)" stroke-width="2" style="margin-right: 8px;">
<circle cx="12" cy="12" r="10"></circle>
<line x1="12" y1="8" x2="12" y2="12"></line>
<line x1="12" y1="16" x2="12.01" y2="16"></line>
</svg>
Downloads completed with ${failedOrders.length} failed orders:<br>
Failed orders: ${failedOrders.map(order => `#${order}`).join(', ')}
`;
}
setTimeout(() => progressDiv.remove(), failedOrders.length > 0 ? 30000 : 10000);
} catch (error) {
console.error("Download error:", error);
alert("An error occurred during download process. Some orders may have failed.");
if (downloadTab) {
chrome.tabs.remove(downloadTab.id);
}
} finally {
downloadButton.disabled = false;
setButtonLoading(downloadButton, false);
downloadInProgress = false;
}
}
// Helper function to set loading state on any button
function setButtonLoading(button, isLoading) {
if (isLoading) {
button.disabled = true;
const spinner = document.createElement("span");
spinner.className = "loading-spinner";
button.insertBefore(spinner, button.firstChild);
} else {
button.disabled = false;
const spinner = button.querySelector(".loading-spinner");
if (spinner) spinner.remove();
}
}