ysdsd
All checks were successful
Deploy / deploy-staging (push) Successful in 6s
Deploy / deploy-production (push) Has been skipped

This commit is contained in:
2026-04-29 02:21:22 +02:00
parent a0f19ff6b4
commit 4ead35047a
7 changed files with 180 additions and 4 deletions

View File

@@ -87,6 +87,7 @@
} }
.fx-form-grid input, .fx-form-grid input,
.fx-form-grid select,
.fx-block input { .fx-block input {
width: 100%; width: 100%;
border: 1px solid #d0d7e2; border: 1px solid #d0d7e2;
@@ -127,3 +128,20 @@
margin-top: 0.75rem; margin-top: 0.75rem;
font-size: 0.95rem; font-size: 0.95rem;
} }
.fx-convert-result {
margin-top: 1rem;
min-height: 1.5rem;
font-size: 1rem;
font-weight: 700;
color: #1c2734;
}
.fx-history-block {
margin-top: 1.25rem;
}
.fx-history-block h3 {
margin: 0 0 0.75rem;
font-size: 1rem;
}

View File

@@ -12,9 +12,14 @@
defaultBase: root.querySelector('[data-bind="default-base"]'), defaultBase: root.querySelector('[data-bind="default-base"]'),
displayBase: root.querySelector('[data-bind="display-base"]'), displayBase: root.querySelector('[data-bind="display-base"]'),
ratesBody: root.querySelector('[data-bind="rates-body"]'), ratesBody: root.querySelector('[data-bind="rates-body"]'),
fetchesBody: root.querySelector('[data-bind="fetches-body"]'),
convertResult: root.querySelector('[data-bind="convert-result"]'),
defaultBaseInput: root.querySelector('input[name="default_base_currency"]'), defaultBaseInput: root.querySelector('input[name="default_base_currency"]'),
displayBaseInput: root.querySelector('input[name="display_base_currency"]'), displayBaseInput: root.querySelector('input[name="display_base_currency"]'),
preferredCurrenciesInput: root.querySelector('input[name="preferred_currencies"]'), preferredCurrenciesInput: root.querySelector('input[name="preferred_currencies"]'),
convertFrom: root.querySelector('select[name="convert_from"]'),
convertTo: root.querySelector('select[name="convert_to"]'),
convertAmount: root.querySelector('input[name="convert_amount"]'),
}; };
const apiBase = '/api/fx-rates/v1'; const apiBase = '/api/fx-rates/v1';
@@ -57,6 +62,24 @@
}).join(''); }).join('');
}; };
const renderFetches = (fetches) => {
if (!nodes.fetchesBody) {
return;
}
const entries = Array.isArray(fetches) ? fetches : [];
if (!entries.length) {
nodes.fetchesBody.innerHTML = '<tr><td colspan="3">Noch keine Abrufe vorhanden.</td></tr>';
return;
}
nodes.fetchesBody.innerHTML = entries.map((entry) => `
<tr>
<td>${entry?.fetched_at || ''}</td>
<td>${entry?.base_currency || ''}</td>
<td>${entry?.provider || ''}</td>
</tr>
`).join('');
};
const request = async (path, options = {}) => { const request = async (path, options = {}) => {
const response = await fetch(`${apiBase}${path}`, { const response = await fetch(`${apiBase}${path}`, {
credentials: 'same-origin', credentials: 'same-origin',
@@ -96,6 +119,39 @@
return data; return data;
}; };
const calculateConversion = async () => {
if (!nodes.convertFrom || !nodes.convertTo || !nodes.convertAmount || !nodes.convertResult) {
return;
}
const from = String(nodes.convertFrom.value || '').trim().toUpperCase();
const to = String(nodes.convertTo.value || '').trim().toUpperCase();
const amount = Number(nodes.convertAmount.value || '0');
if (!from || !to || !Number.isFinite(amount)) {
nodes.convertResult.textContent = 'Bitte Quellwaehrung, Zielwaehrung und Betrag angeben.';
return;
}
if (from === to) {
nodes.convertResult.textContent = `${amount.toLocaleString('de-DE', { maximumFractionDigits: 8 })} ${from} = ${amount.toLocaleString('de-DE', { maximumFractionDigits: 8 })} ${to}`;
return;
}
try {
const query = new URLSearchParams({ from, to });
const data = await request(`/rate?${query.toString()}`);
const rate = Number(data?.rate || 0);
if (!Number.isFinite(rate) || rate <= 0) {
throw new Error('Kein Kurs verfuegbar.');
}
const converted = amount * rate;
nodes.convertResult.textContent = `${amount.toLocaleString('de-DE', { maximumFractionDigits: 8 })} ${from} = ${converted.toLocaleString('de-DE', { maximumFractionDigits: 8 })} ${to} | Kurs ${rate.toLocaleString('de-DE', { maximumFractionDigits: 8 })}`;
} catch (error) {
nodes.convertResult.textContent = error.message || 'Umrechnung konnte nicht berechnet werden.';
}
};
root.querySelector('[data-action="refresh-rates"]')?.addEventListener('click', async () => { root.querySelector('[data-action="refresh-rates"]')?.addEventListener('click', async () => {
try { try {
setLoading(true); setLoading(true);
@@ -108,6 +164,9 @@
const data = await request('/refresh', { method: 'POST', body: JSON.stringify(payload) }); const data = await request('/refresh', { method: 'POST', body: JSON.stringify(payload) });
setMessage(`Aktuelle Kurse gespeichert. ${data?.updated_count || 0} Werte aktualisiert.`, 'success'); setMessage(`Aktuelle Kurse gespeichert. ${data?.updated_count || 0} Werte aktualisiert.`, 'success');
await loadLatest(); await loadLatest();
const recentFetches = await request('/recent-fetches?limit=12');
renderFetches(recentFetches);
await calculateConversion();
} catch (error) { } catch (error) {
setMessage(error.message || 'Kurse konnten nicht aktualisiert werden.', 'error'); setMessage(error.message || 'Kurse konnten nicht aktualisiert werden.', 'error');
} finally { } finally {
@@ -133,6 +192,7 @@
} }
setMessage('Waehrungs-Auswahl gespeichert.', 'success'); setMessage('Waehrungs-Auswahl gespeichert.', 'success');
await loadLatest(); await loadLatest();
await calculateConversion();
} catch (error) { } catch (error) {
setMessage(error.message || 'Waehrungs-Auswahl konnte nicht gespeichert werden.', 'error'); setMessage(error.message || 'Waehrungs-Auswahl konnte nicht gespeichert werden.', 'error');
} finally { } finally {
@@ -140,7 +200,19 @@
} }
}); });
[nodes.convertFrom, nodes.convertTo, nodes.convertAmount].forEach((node) => {
node?.addEventListener('change', () => {
calculateConversion().catch(() => {});
});
node?.addEventListener('input', () => {
calculateConversion().catch(() => {});
});
});
renderFetches(page.recent_fetches || []);
loadLatest().catch((error) => { loadLatest().catch((error) => {
setMessage(error.message || 'Letzter Snapshot konnte nicht geladen werden.', 'error'); setMessage(error.message || 'Letzter Snapshot konnte nicht geladen werden.', 'error');
}); });
calculateConversion().catch(() => {});
})(); })();

View File

@@ -251,6 +251,10 @@ $mm->registerFunction($moduleName, 'snapshot', static function (?string $baseCur
return module_fn('fx-rates', 'service')->snapshot($baseCurrency, $at, $symbols, $windowMinutes); return module_fn('fx-rates', 'service')->snapshot($baseCurrency, $at, $symbols, $windowMinutes);
}); });
$mm->registerFunction($moduleName, 'recent_fetches', static function (int $limit = 20): array {
return module_fn('fx-rates', 'service')->recentFetches($limit);
});
$mm->registerFunction($moduleName, 'scheduled_refresh', static function (array $context = []): array { $mm->registerFunction($moduleName, 'scheduled_refresh', static function (array $context = []): array {
$result = module_fn('fx-rates', 'service')->runScheduledRefresh($context); $result = module_fn('fx-rates', 'service')->runScheduledRefresh($context);
if (function_exists('module_debug_push')) { if (function_exists('module_debug_push')) {

View File

@@ -12,11 +12,13 @@ if ($assets) {
$settings = module_fn('fx-rates', 'settings'); $settings = module_fn('fx-rates', 'settings');
$service = module_fn('fx-rates', 'service'); $service = module_fn('fx-rates', 'service');
$latest = $service->latestStatus(); $latest = $service->latestStatus();
$recentFetches = $service->recentFetches(12);
$preferredCurrencies = is_array($settings['preferred_currencies'] ?? null) ? $settings['preferred_currencies'] : []; $preferredCurrencies = is_array($settings['preferred_currencies'] ?? null) ? $settings['preferred_currencies'] : [];
$pageData = json_encode([ $pageData = json_encode([
'settings' => $settings, 'settings' => $settings,
'latest' => $latest, 'latest' => $latest,
'preferred_currencies' => $preferredCurrencies, 'preferred_currencies' => $preferredCurrencies,
'recent_fetches' => $recentFetches,
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
?> ?>
<?= module_shell_header('fx-rates', ['title' => 'Waehrungskurse']) ?> <?= module_shell_header('fx-rates', ['title' => 'Waehrungskurse']) ?>
@@ -28,9 +30,6 @@ $pageData = json_encode([
<h1>Waehrungskurse</h1> <h1>Waehrungskurse</h1>
<p>Zentrale Quelle fuer FX-Snapshots, Zeitabfragen und manuelle Aktualisierung.</p> <p>Zentrale Quelle fuer FX-Snapshots, Zeitabfragen und manuelle Aktualisierung.</p>
</div> </div>
<div class="fx-actions">
<button type="button" class="fx-button fx-button--primary" data-action="refresh-rates">Aktuelle Kurse abrufen</button>
</div>
</div> </div>
<div class="fx-meta-grid"> <div class="fx-meta-grid">
<div><strong>Standard-Basis:</strong> <span data-bind="default-base"><?= e((string) ($settings['default_base_currency'] ?? 'EUR')) ?></span></div> <div><strong>Standard-Basis:</strong> <span data-bind="default-base"><?= e((string) ($settings['default_base_currency'] ?? 'EUR')) ?></span></div>
@@ -42,7 +41,7 @@ $pageData = json_encode([
</div> </div>
<div class="fx-card"> <div class="fx-card">
<h2>Anzeige und Waehrungen</h2> <h2>Setup</h2>
<p>Die Auswahl wird in den Modul-Settings gespeichert und steuert den Standardaufruf der letzten Kurse.</p> <p>Die Auswahl wird in den Modul-Settings gespeichert und steuert den Standardaufruf der letzten Kurse.</p>
<div class="fx-form-grid"> <div class="fx-form-grid">
<label> <label>
@@ -60,9 +59,38 @@ $pageData = json_encode([
</label> </label>
<div class="fx-actions"> <div class="fx-actions">
<button type="button" class="fx-button" data-action="save-settings">Auswahl speichern</button> <button type="button" class="fx-button" data-action="save-settings">Auswahl speichern</button>
<button type="button" class="fx-button fx-button--primary" data-action="refresh-rates">Aktuelle Kurse abrufen</button>
</div> </div>
</div> </div>
<div class="fx-card">
<h2>Umrechnung</h2>
<p>Umrechnung auf Basis des letzten verfuegbaren Kurses zwischen den bevorzugten Waehrungen.</p>
<div class="fx-form-grid">
<label>
<span>Quellwaehrung</span>
<select name="convert_from">
<?php foreach ($preferredCurrencies as $currency): ?>
<option value="<?= e((string) $currency) ?>"><?= e((string) $currency) ?></option>
<?php endforeach; ?>
</select>
</label>
<label>
<span>Zielwaehrung</span>
<select name="convert_to">
<?php foreach ($preferredCurrencies as $currency): ?>
<option value="<?= e((string) $currency) ?>" <?= (string) $currency === (string) ($preferredCurrencies[1] ?? $preferredCurrencies[0] ?? '') ? 'selected' : '' ?>><?= e((string) $currency) ?></option>
<?php endforeach; ?>
</select>
</label>
<label>
<span>Betrag</span>
<input type="number" name="convert_amount" min="0" step="0.00000001" value="1">
</label>
</div>
<div class="fx-convert-result" data-bind="convert-result">Noch keine Umrechnung berechnet.</div>
</div>
<div class="fx-card"> <div class="fx-card">
<h2>Letzter Snapshot</h2> <h2>Letzter Snapshot</h2>
<div class="fx-table-wrap"> <div class="fx-table-wrap">
@@ -78,6 +106,33 @@ $pageData = json_encode([
</tbody> </tbody>
</table> </table>
</div> </div>
<div class="fx-history-block">
<h3>Letzte Abrufe</h3>
<div class="fx-table-wrap">
<table class="fx-table">
<thead>
<tr>
<th>Datum</th>
<th>Basis</th>
<th>Provider</th>
</tr>
</thead>
<tbody data-bind="fetches-body">
<?php if ($recentFetches === []): ?>
<tr><td colspan="3">Noch keine Abrufe vorhanden.</td></tr>
<?php else: ?>
<?php foreach ($recentFetches as $fetch): ?>
<tr>
<td><?= e((string) ($fetch['fetched_at'] ?? '')) ?></td>
<td><?= e((string) ($fetch['base_currency'] ?? '')) ?></td>
<td><?= e((string) ($fetch['provider'] ?? '')) ?></td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>
</div>
</div>
</div> </div>
</div> </div>
</div> </div>

View File

@@ -26,6 +26,11 @@ final class Router
$this->respond(['data' => $this->service->latestStatuses()]); $this->respond(['data' => $this->service->latestStatuses()]);
} }
if ($path === 'v1/recent-fetches' && $method === 'GET') {
$limit = max(1, min(50, (int) ($_GET['limit'] ?? 12)));
$this->respond(['data' => $this->service->recentFetches($limit)]);
}
if ($path === 'v1/latest' && $method === 'GET') { if ($path === 'v1/latest' && $method === 'GET') {
$symbols = $this->parseCsv($_GET['symbols'] ?? null); $symbols = $this->parseCsv($_GET['symbols'] ?? null);
$base = $this->stringOrNull($_GET['base'] ?? null); $base = $this->stringOrNull($_GET['base'] ?? null);

View File

@@ -27,6 +27,11 @@ final class FxRatesService
return $this->repository->listLatestFetches(); return $this->repository->listLatestFetches();
} }
public function recentFetches(int $limit = 20): array
{
return $this->repository->listRecentFetches($limit);
}
public function snapshot(?string $baseCurrency = null, ?string $at = null, ?array $symbols = null, ?int $windowMinutes = null): ?array public function snapshot(?string $baseCurrency = null, ?string $at = null, ?array $symbols = null, ?int $windowMinutes = null): ?array
{ {
$base = $this->normalizeCurrency($baseCurrency ?: $this->defaultBaseCurrency()); $base = $this->normalizeCurrency($baseCurrency ?: $this->defaultBaseCurrency());

View File

@@ -117,6 +117,23 @@ final class FxRatesRepository
return array_values($latestByBase); return array_values($latestByBase);
} }
public function listRecentFetches(int $limit = 20): array
{
$stmt = $this->pdo->prepare(
'SELECT id, provider, base_currency, rate_date, fetched_at, created_at
FROM ' . $this->table('fetches') . '
ORDER BY fetched_at DESC, id DESC
LIMIT :limit'
);
$stmt->bindValue(':limit', max(1, $limit), PDO::PARAM_INT);
$stmt->execute();
return array_map(
fn (array $row): array => $this->normalizeFetch($row),
$stmt->fetchAll(PDO::FETCH_ASSOC) ?: []
);
}
public function getSnapshotByFetchId(int $fetchId, ?array $symbols = null): ?array public function getSnapshotByFetchId(int $fetchId, ?array $symbols = null): ?array
{ {
$fetch = $this->getFetchById($fetchId); $fetch = $this->getFetchById($fetchId);