-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpopup.js
More file actions
275 lines (235 loc) · 10 KB
/
Copy pathpopup.js
File metadata and controls
275 lines (235 loc) · 10 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
// ============================================================
// PAYBACK Helper – Popup Logik
// domain-map.js geladen davor: PAYBACK_DOMAIN_LOOKUP + normalizeName verfügbar
// ============================================================
document.addEventListener('DOMContentLoaded', async () => {
const {
shops = [], coupons = [],
shopsLastFetch, couponsLastFetch, couponsLoggedIn,
pointsBalance,
} = await chrome.storage.local.get([
'shops', 'coupons', 'shopsLastFetch', 'couponsLastFetch', 'couponsLoggedIn',
'pointsBalance',
]);
// Show points balance in header if available
if (typeof pointsBalance === 'number') {
const pointsEl = document.getElementById('points-display');
if (pointsEl) {
const euros = (pointsBalance / 100).toFixed(2).replace('.', ',');
pointsEl.textContent = `${pointsBalance.toLocaleString('de-AT')} °P ≈ ${euros} €`;
pointsEl.style.display = 'block';
}
}
if (!shopsLastFetch || shops.length === 0) {
show('view-no-data');
setupRefreshButton();
return;
}
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
let parsedUrl;
try { parsedUrl = new URL(tab?.url); } catch {}
const shop = parsedUrl ? matchShop(parsedUrl.hostname, shops) : null;
if (!shop) {
show('view-no-match');
document.getElementById('footer-no-match').innerHTML =
buildFooter(shopsLastFetch, couponsLastFetch, couponsLoggedIn);
setupRefreshButton();
setupOverlayToggle();
return;
}
show('view-match');
document.getElementById('shop-name').textContent = shop.name;
document.getElementById('shop-points').textContent = shop.points;
document.getElementById('shop-link').href = shop.paybackUrl + '#pb-autoclick';
const matchingCoupons = coupons.filter(c => c.partnerShortName === shop.partnerShortName);
renderCoupons(matchingCoupons, shop, couponsLoggedIn);
document.getElementById('footer-match').innerHTML =
buildFooter(shopsLastFetch, couponsLastFetch, couponsLoggedIn);
setupRefreshButton();
setupOverlayToggle();
});
// ---- Domain matching (same logic as background.js) ----
function matchShop(hostname, shops) {
const cleanHost = hostname.replace(/^www\./, '');
const normedFromMap = PAYBACK_DOMAIN_LOOKUP[cleanHost];
if (normedFromMap) {
const shop = shops.find(s => normalizeName(s.name) === normedFromMap);
if (shop) return shop;
}
for (const [domain, normedName] of Object.entries(PAYBACK_DOMAIN_LOOKUP)) {
if (cleanHost === domain || cleanHost.endsWith('.' + domain)) {
const shop = shops.find(s => normalizeName(s.name) === normedName);
if (shop) return shop;
}
}
const hostParts = cleanHost.split('.');
for (const shop of shops) {
const slug = shop.slug.toLowerCase();
if (hostParts.some(part => part === slug)) return shop;
if (cleanHost.startsWith(slug + '.') || cleanHost === slug) return shop;
const normedName = normalizeName(shop.name);
if (normedName.length > 3 && hostParts.some(p => normalizeName(p) === normedName)) return shop;
}
return null;
}
// ---- Render coupons ----
function renderCoupons(coupons, _shop, couponsLoggedIn) {
const section = document.getElementById('coupons-section');
if (couponsLoggedIn === false) {
section.innerHTML = `
<div class="login-warning">
⚠ eCoupons nicht geladen –
<a href="https://www.payback.at/coupons" target="_blank">Bitte einloggen</a>
</div>`;
return;
}
if (coupons.length === 0) {
section.innerHTML = `<div class="no-coupons-note">Kein eCoupon für diesen Shop verfügbar</div>`;
return;
}
const comingSoon = coupons.filter(c => c.comingSoon);
const unactivated = coupons.filter(c => !c.activated && !c.comingSoon);
const activated = coupons.filter(c => c.activated);
let html = '';
if (unactivated.length > 0) {
html += `<div class="coupons-header">⚠ Nicht aktivierte eCoupons</div>`;
html += `<button class="btn-activate-all" id="btn-activate-all">
⚡ Alle ${unactivated.length > 1 ? unactivated.length + ' eCoupons' : 'eCoupons'} automatisch aktivieren
</button>`;
unactivated.forEach(c => { html += buildCouponCard(c, 'unactivated'); });
}
if (activated.length > 0) {
html += `<div class="coupons-header">✓ Aktivierte eCoupons</div>`;
activated.forEach(c => { html += buildCouponCard(c, 'activated'); });
}
if (comingSoon.length > 0) {
html += `<div class="coupons-header">🕐 In Kürze verfügbar</div>`;
comingSoon.forEach(c => { html += buildCouponCard(c, 'coming-soon'); });
}
section.innerHTML = html;
// Event-Listener für "Alle aktivieren" Button
const activateAllBtn = document.getElementById('btn-activate-all');
if (activateAllBtn) {
activateAllBtn.addEventListener('click', () => {
const toActivate = unactivated
.map(c => ({ couponId: c.couponID, partnerShortName: c.partnerShortName }));
if (toActivate.length === 0) return;
chrome.runtime.sendMessage({ type: 'ACTIVATE_ALL_COUPONS', coupons: toActivate });
activateAllBtn.textContent = '⚡ Wird aktiviert…';
activateAllBtn.disabled = true;
});
}
}
function buildCouponCard(coupon, type) {
const validTo = formatDate(coupon.validTo);
// URL to payback.at/coupons with partner pre-filtered and scrolled to "nicht aktiviert"
const filterUrl = `https://www.payback.at/coupons#pbf~${encodeURIComponent(coupon.partnerShortName)}`;
const isExpired = coupon.validTo ? new Date(coupon.validTo).getTime() < Date.now() : false;
let statusHtml = '';
if (type === 'coming-soon') {
const activeFrom = formatDate(coupon.validFrom);
statusHtml = `<div class="coupon-coming-soon-note">🕐 Aktivierbar ab ${activeFrom}</div>`;
} else if (type === 'unactivated') {
if (!isExpired) {
statusHtml = `<a href="${filterUrl}" target="_blank" class="btn-activate">Jetzt aktivieren →</a>`;
} else {
type = 'expired';
statusHtml = `<div class="coupon-expired-note">⏰ Aktivierungszeitraum abgelaufen</div>`;
}
} else {
statusHtml = `<div class="coupon-activated-badge">✓ Bereits aktiviert</div>`;
}
return `
<div class="coupon-card ${type}">
<div class="coupon-headline">${esc(coupon.headline)}</div>
${coupon.subline ? `<div class="coupon-subline">${esc(coupon.subline)}</div>` : ''}
${validTo ? `<div class="coupon-validity">Gültig bis ${validTo}</div>` : ''}
${statusHtml}
</div>`;
}
// ---- Footer with timestamps + refresh button ----
function buildFooter(shopsLastFetch, couponsLastFetch, couponsLoggedIn) {
const shopsAge = shopsLastFetch ? formatAge(shopsLastFetch) : 'nie';
const couponsAge = couponsLastFetch ? formatAge(couponsLastFetch) : 'nie';
const staleClass = (isStale(shopsLastFetch) || isStale(couponsLastFetch)) ? 'stale' : '';
const couponStatus = couponsLoggedIn === false
? `<span class="warn">nicht eingeloggt</span>`
: couponsAge;
const loginHint = couponsLoggedIn === false
? `<div class="login-warning">⚠ Bitte auf <a href="https://www.payback.at/coupons" target="_blank">payback.at</a> einloggen, damit eCoupons geladen werden können.</div>`
: '';
return `
${loginHint}
<label class="overlay-toggle">
<input type="checkbox" class="chk-overlay">
<span>°P Overlay auf Websites anzeigen</span>
</label>
<div class="footer-timestamps ${staleClass}">
Shops: ${shopsAge} · Coupons: ${couponStatus}
</div>
<div class="footer-actions">
<button class="btn-refresh" title="Shops + eCoupons im Hintergrund aktualisieren">↺ Aktualisieren</button>
</div>`;
}
function setupRefreshButton() {
// There can be multiple refresh buttons (no-data view + footer), attach to all
document.querySelectorAll('.btn-refresh').forEach(btn => {
btn.addEventListener('click', () => {
// Disable all refresh buttons
document.querySelectorAll('.btn-refresh').forEach(b => {
b.textContent = '↺ Wird aktualisiert…';
b.disabled = true;
});
// Open pages directly from popup – no message passing to background needed.
// Content scripts extract data → send to background → storage updates → popup reloads.
chrome.tabs.create({ url: 'https://www.payback.at/online-punkten/alle-shops', active: false });
chrome.tabs.create({ url: 'https://www.payback.at/online-punkten', active: false });
chrome.tabs.create({ url: 'https://www.payback.at/coupons', active: false });
});
});
}
function setupOverlayToggle() {
const chk = document.querySelector('.chk-overlay');
if (!chk) return;
// Read current setting (default: enabled)
chrome.storage.local.get(['overlayEnabled'], ({ overlayEnabled }) => {
chk.checked = overlayEnabled !== false; // default true
});
chk.addEventListener('change', () => {
chrome.storage.local.set({ overlayEnabled: chk.checked });
});
}
// Listen for storage changes to update the popup live after refresh
chrome.storage.onChanged.addListener((changes, area) => {
if (area !== 'local') return;
if (changes.shopsLastFetch || changes.couponsLastFetch || changes.couponsLoggedIn || changes.coupons) {
// Reload the entire popup to show fresh data
window.location.reload();
}
});
// ---- Helpers ----
function show(id) {
['view-loading','view-no-data','view-no-match','view-match'].forEach(v => {
document.getElementById(v)?.classList.toggle('hidden', v !== id);
});
}
function formatDate(iso) {
if (!iso) return '';
try { return new Date(iso).toLocaleDateString('de-AT', { day:'2-digit', month:'2-digit', year:'numeric' }); }
catch { return ''; }
}
function formatAge(ts) {
const m = Math.round((Date.now() - ts) / 60000);
if (m < 1) return 'gerade eben';
if (m < 60) return `vor ${m} Min.`;
const h = Math.round(m / 60);
if (h < 24) return `vor ${h} Std.`;
return `vor ${Math.round(h/24)} Tag(en)`;
}
function isStale(ts) {
return !ts || (Date.now() - ts) > 25 * 3600 * 1000;
}
function esc(str) {
if (!str) return '';
return str.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"');
}