-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscripts.js
More file actions
338 lines (284 loc) · 11.6 KB
/
Copy pathscripts.js
File metadata and controls
338 lines (284 loc) · 11.6 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
/* scripts.js — Urban Environmental Ltd website
Full version with multi-currency support, Google Sheets, theme toggle, tabs, etc.
Order: constants → currency helpers → utility functions → init functions → data loaders → DOMContentLoaded
*/
// ────────────────────────────────────────────────
// CONFIG & CONSTANTS
// ────────────────────────────────────────────────
const apiKey = "AIzaSyDig1pzwMpM923E4tDyKN_KMcBqfz9lfH8";
const sheetId = "1xIoXT6tGCO55drQC8BCBVfd4xCiG301CtLK62y8vA58";
const sheetRange = "Metrics!A2:B150";
const sheetFetchTimeoutMs = 8000;
// ────────────────────────────────────────────────
// CURRENCY SUPPORT
// ────────────────────────────────────────────────
let currentCurrency = 'USD';
let exchangeRates = { USD: 1 };
let originalValues = {};
const currencyDependentIds = [
'bitcoin-price',
'share-price',
'outstanding-marketcap',
'btc-value',
'non-btc-value',
'nav',
'enterprise-value',
'btc-value-pershare',
'cash',
'debt',
'mstrcomp-share-price',
// Add any other IDs that display dollar amounts here
];
// ────────────────────────────────────────────────
// AUTO-DETECT PREFERRED CURRENCY FROM TIMEZONE
// ────────────────────────────────────────────────
function detectLikelyCurrency() {
// Default fallback
let currency = 'USD';
if (typeof Intl !== 'undefined' && Intl.DateTimeFormat) {
try {
const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
console.log("Detected timezone:", tz);
// Very common mappings (expand as needed)
const tzToCurrency = {
'Europe/London': 'GBP',
'Europe/Paris': 'EUR',
'Europe/Berlin': 'EUR',
'Europe/Rome': 'EUR',
'Asia/Tokyo': 'JPY',
'Asia/Shanghai': 'CNY',
'Asia/Hong_Kong': 'HKD',
'Australia/Sydney': 'AUD',
'Australia/Melbourne': 'AUD',
'Pacific/Auckland': 'NZD',
'America/New_York': 'USD',
'America/Los_Angeles': 'USD',
'America/Toronto': 'CAD',
'Europe/Zurich': 'CHF',
'Asia/Singapore': 'SGD',
'Asia/Seoul': 'KRW',
'Europe/Stockholm': 'SEK',
'Europe/Oslo': 'NOK',
'Asia/Jakarta': 'IDR', // example – add more if relevant
};
if (tzToCurrency[tz]) {
currency = tzToCurrency[tz];
} else if (tz.startsWith('Europe/')) {
currency = 'EUR'; // most of Western/Central Europe
} else if (tz.startsWith('America/')) {
currency = 'USD'; // most common in Americas
}
} catch (e) {
console.warn("Timezone detection failed", e);
}
}
// Optional fallback: browser language
if (currency === 'USD' && navigator.language) {
const lang = navigator.language.toUpperCase();
if (lang.includes('EN-AU') || lang.includes('EN-NZ')) currency = 'AUD'; // rough
if (lang.includes('FR')) currency = 'EUR';
if (lang.includes('DE')) currency = 'EUR';
if (lang.includes('JA')) currency = 'JPY';
}
console.log("Auto-detected preferred currency:", currency);
return currency;
}
async function fetchExchangeRates() {
try {
console.log("Fetching exchange rates...");
const res = await fetch('https://open.er-api.com/v6/latest/USD');
if (!res.ok) throw new Error('Rates fetch failed');
const data = await res.json();
if (data.result === 'success' && data.rates) {
exchangeRates = { USD: 1, ...data.rates };
console.log(`Loaded ${Object.keys(exchangeRates).length} currencies`);
}
} catch (err) {
console.warn("Exchange rates failed → staying in USD only", err);
}
}
function formatMoney(amount, code) {
if (typeof amount !== 'number' || !isFinite(amount)) return '—';
try {
return new Intl.NumberFormat(undefined, {
style: 'currency',
currency: code,
minimumFractionDigits: code === 'JPY' ? 0 : 2,
maximumFractionDigits: code === 'JPY' ? 0 : 2
}).format(amount);
} catch (e) {
const symbol = getCurrencySymbol(code);
return `${symbol}${amount.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
}
}
function getCurrencySymbol(code) {
const symbols = {
USD: '$', NZD: 'NZ$', EUR: '€', GBP: '£', JPY: '¥', CNY: '¥', AUD: 'A$', CAD: 'C$',
CHF: 'CHF ', INR: '₹', SGD: 'S$', HKD: 'HK$', SEK: 'SEK ', KRW: '₩', NOK: 'NOK ',
MXN: 'MXN ', TWD: 'NT$', ZAR: 'R ', RUB: '₽', BRL: 'R$', DKK: 'DKK ', PLN: 'zł', TRY: '₺'
};
return symbols[code] || code + ' ';
}
function convertAndUpdate(currency = 'USD') {
currentCurrency = currency;
const rate = exchangeRates[currency] || 1;
console.log(`Converting to ${currency} (rate ${rate.toFixed(4)})`);
let count = 0;
currencyDependentIds.forEach(id => {
const usdVal = originalValues[id];
if (usdVal !== undefined && usdVal !== null) {
const converted = usdVal * rate;
updateElementsById(id, formatMoney(converted, currency));
count++;
}
});
console.log(`Applied conversion to ${count} fields`);
}
// ────────────────────────────────────────────────
// UTILITY FUNCTIONS
// ────────────────────────────────────────────────
function updateElementsById(id, value) {
if (!id) return;
document.querySelectorAll(`[id="${id}"]`).forEach(el => {
if (el.tagName === "PRE") {
el.textContent = value;
} else {
el.textContent = value;
}
});
}
// ────────────────────────────────────────────────
// DATA FETCHERS
// ────────────────────────────────────────────────
async function fetchSheetMetrics() {
if (!apiKey || !sheetId) {
console.warn("Missing Google Sheets config");
return;
}
const url = `https://sheets.googleapis.com/v4/spreadsheets/${sheetId}/values/${encodeURIComponent(sheetRange)}?key=${apiKey}`;
try {
const res = await fetch(url, { cache: "no-store" });
if (!res.ok) {
console.warn("Sheets fetch failed", res.status);
return;
}
const { values } = await res.json();
if (!values) return;
originalValues = {}; // reset
values.forEach(([keyRaw, valRaw]) => {
if (!keyRaw) return;
const key = keyRaw.trim();
// Display raw value from sheet first
updateElementsById(key, valRaw || "—");
// Parse number (tolerant to $, commas, spaces, etc.)
let numStr = (valRaw || "").toString()
.replace(/[^\d.-]/g, '')
.replace(/^[-.]+/, '')
.replace(/[.]+/g, '.')
.replace(/,$/, '');
const num = parseFloat(numStr);
if (!isNaN(num) && isFinite(num) && currencyDependentIds.includes(key)) {
originalValues[key] = num;
console.log(`Stored convertible value → ${key}: ${num} (raw: ${valRaw})`);
}
});
console.log("Convertible values stored:", Object.keys(originalValues));
} catch (err) {
console.error("fetchSheetMetrics error:", err);
}
}
async function fetchDataJson() {
try {
const res = await fetch("Data.json", { cache: "no-store" });
if (!res.ok) return;
const data = await res.json();
// Add handling if you use Data.json for anything
} catch (err) {
console.error("fetchDataJson error:", err);
}
}
// ────────────────────────────────────────────────
// INIT FUNCTIONS
// ────────────────────────────────────────────────
function initThemeToggle() {
const toggle = document.getElementById("theme-toggle");
if (!toggle) return;
const saved = localStorage.getItem("theme");
if (saved === "dark") {
document.body.classList.add("dark");
toggle.textContent = "☀️";
}
toggle.addEventListener("click", () => {
document.body.classList.toggle("dark");
toggle.textContent = document.body.classList.contains("dark") ? "☀️" : "🌙";
localStorage.setItem("theme", document.body.classList.contains("dark") ? "dark" : "light");
});
}
function initTabs() {
document.querySelectorAll(".tab-btn").forEach(btn => {
btn.addEventListener("click", () => {
document.querySelectorAll(".tab-btn").forEach(b => b.classList.remove("active"));
btn.classList.add("active");
document.querySelectorAll(".tab-content").forEach(tab => tab.classList.remove("active"));
const target = document.getElementById(btn.dataset.tab);
if (target) target.classList.add("active");
});
});
}
function initScreenshot() {
const btn = document.getElementById("screenshot-btn");
if (!btn || typeof html2canvas !== "function") return;
btn.addEventListener("click", async () => {
const canvas = await html2canvas(document.querySelector("main"));
const link = document.createElement("a");
link.download = "metrics.png";
link.href = canvas.toDataURL();
link.click();
});
}
// ────────────────────────────────────────────────
// MAIN DATA LOADER
// ────────────────────────────────────────────────
async function loadAllData() {
console.log("Starting data load...");
await Promise.allSettled([
fetchDataJson(),
fetchSheetMetrics(),
fetchExchangeRates()
]);
console.log("Data load complete");
// Apply saved / default currency
const saved = localStorage.getItem('selectedCurrency') || 'USD';
const select = document.getElementById('currencySelect');
if (select) {
select.value = saved;
}
convertAndUpdate(saved);
}
// ────────────────────────────────────────────────
// START WHEN PAGE IS READY
// ────────────────────────────────────────────────
document.addEventListener("DOMContentLoaded", () => {
initThemeToggle();
initTabs();
initScreenshot();
const currencySelect = document.getElementById('currencySelect');
if (currencySelect) {
// First try saved preference (user manually changed it before)
let initialCurrency = localStorage.getItem('selectedCurrency');
// If no saved choice → use auto-detection
if (!initialCurrency) {
initialCurrency = detectLikelyCurrency();
localStorage.setItem('selectedCurrency', initialCurrency); // remember it
}
currencySelect.value = initialCurrency;
convertAndUpdate(initialCurrency);
// Still allow manual change
currencySelect.addEventListener('change', e => {
const newCurrency = e.target.value;
localStorage.setItem('selectedCurrency', newCurrency);
convertAndUpdate(newCurrency);
});
}
loadAllData();
});