feat(server): web server, interface shell, demo mode and Docker image (refs #11 #12 #13 #14 #15 #16 #17)
ci / test (postgres) (push) Successful in 2m22s
ci / test (sqlite) (push) Failing after 2m27s
ci / image (push) Skipped

Phase 1 completed on top of the library foundations:
- Server: startup state machine (config, first run, database down, schema,
  identity, ready) with an error page that retries by itself; the configured
  database is the only one ever opened, and a vanished SQLite file is never
  recreated. REST API and status WebSocket; session cookie auth, CSRF on
  every form and write call; desktop and demo answer only the computer itself.
- Interface: static Blazor rendering with plain forms (no interactive
  runtime), menu, top bar and phone bottom bar as in the mockups, light and
  dark themes with appendix C tokens and a contrast test, Panoramica, Diario,
  Rischio, Impostazioni; service pages for sign-in, first access, desktop
  first run and the database error page with its choices.
- Demo mode (tasks seed-demo): appendix F in a database of its own under the
  temp folder, frozen clock, never touches the configured installation.
- Docker: entrypoint gives /data to PUID:PGID and drops root with setpriv,
  HEALTHCHECK through bash /dev/tcp; proven with SQLite, PostgreSQL, a wrong
  configuration and a database that goes away and comes back.
- tasks screenshots drives the installed Edge/Chrome through DevTools for
  exact 1440 and 390 pixel shots; anubis db export|import on the command line.

Fixes from the independent review: return paths without control characters,
Host check against DNS rebinding, attempt limit counted before the check and
also on the error-page password, one-use TOTP codes and a code to switch the
second factor off, error-page choices serialized with the startup loop,
identity checked before migrating, restore restarts with "Ferma tutto" on,
damaged archives reported instead of crashing. Running the server tests on
PostgreSQL exposed pages rendered before their data arrived; data-loading
components now load first (LoadedComponent).

Decisions in ADR 0007. Tests: 100 on SQLite and on PostgreSQL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-10 12:40:15 +01:00
1 parent 53ca01b7c3
commit f9d71559e8
71 files changed
+5853 -80

No files matched your search

@@ -0,0 +1,12 @@
@if (Docker)
{
<label for="@_id">Password della configurazione d'avvio (<code>ANUBIS_ADMIN_PASSWORD</code>)</label>
<input id="@_id" name="password" type="password" autocomplete="off" required />
}
@code {
private readonly string _id = "admin-" + Guid.NewGuid().ToString("N")[..6];
[Parameter]
public bool Docker { get; set; }
}
+28
View File
@@ -0,0 +1,28 @@
@inherits LoadedComponent
@inject ShellData Shell
<!DOCTYPE html>
<html lang="it" data-theme="@_theme">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="color-scheme" content="light dark" />
<link rel="icon" href="/favicon.ico" />
<link rel="stylesheet" href="/assets/app.css?v=@AnubisInfo.Version" />
<script src="/assets/early.js?v=@AnubisInfo.Version"></script>
<HeadOutlet />
</head>
<body>
<Routes />
<script src="/assets/app.js?v=@AnubisInfo.Version" defer></script>
</body>
</html>
@code {
private string? _theme;
protected override async Task LoadAsync()
{
var snapshot = await Shell.SnapshotAsync(CancellationToken.None);
_theme = snapshot.Theme == "auto" ? null : snapshot.Theme;
}
}
+16
View File
@@ -0,0 +1,16 @@
@* A small filled triangle: the direction is never told by colour alone (SPEC 13.2). *@
<svg class="arrow" width="10" height="10" viewBox="0 0 10 10" aria-hidden="true" focusable="false">
@if (Up)
{
<path d="M5 1.5 9.3 8.5H.7Z" fill="currentColor" />
}
else
{
<path d="M5 8.5.7 1.5h8.6Z" fill="currentColor" />
}
</svg>
@code {
[Parameter]
public bool Up { get; set; }
}
@@ -0,0 +1,102 @@
@inject ShellData Shell
@* Equity against the "senza bot" comparison (SPEC 13.4): one scale, 2 px lines, faint grid, direct label on the last
point, legend, and the same numbers in a table. Lines are SVG stretched to the box; texts and the end point are
HTML placed in percent, so nothing gets distorted at any width. *@
@if (Points.Count >= 2)
{
var values = Points.Select(p => Shell.Convert(p.Equity, Currency)).ToList();
var bench = Points.Select(p => p.Benchmark is { } b ? Shell.Convert(b, Currency) : (decimal?)null).ToList();
var all = values.Concat(bench.OfType<decimal>()).ToList();
var (lo, hi, step) = Scale(all.Min(), all.Max());
double X(int i) => i * 1000.0 / (Points.Count - 1);
double Y(decimal v) => (double)((hi - v) / (hi - lo)) * 1000.0;
string Line(IEnumerable<(int I, decimal V)> pts) => string.Join(" ", pts.Select(p => Fmt(X(p.I)) + "," + Fmt(Y(p.V))));
var equityLine = Line(values.Select((v, i) => (i, v)));
var benchLine = Line(bench.Select((v, i) => (i, v)).Where(p => p.v is not null).Select(p => (p.i, p.v!.Value)));
var last = values[^1];
<figure class="chart" aria-label="Patrimonio nel tempo, con il bot e senza">
<div class="chart-box">
<div class="chart-axis" aria-hidden="true">
@for (var t = lo; t <= hi; t += step)
{
<span style="top:@Pct(Y(t) / 10)">@Format.Number(t)</span>
}
</div>
<div class="chart-plot">
<svg viewBox="0 0 1000 1000" preserveAspectRatio="none" aria-hidden="true" focusable="false">
@for (var t = lo; t <= hi; t += step)
{
<line class="grid" x1="0" x2="1000" y1="@Fmt(Y(t))" y2="@Fmt(Y(t))" vector-effect="non-scaling-stroke" />
}
<polygon class="area" points="0,1000 @equityLine 1000,1000" />
@if (benchLine.Length > 0)
{
<polyline class="bench" points="@benchLine" vector-effect="non-scaling-stroke" />
}
<polyline class="equity" points="@equityLine" vector-effect="non-scaling-stroke" />
</svg>
@if (bench[^1] is { } lastBench)
{
// Two labels never overlap: the lower one moves down when they are closer than one line.
var gap = Math.Abs(Y(last) - Y(lastBench)) / 10;
var benchTop = gap < 7 ? Y(last) / 10 + (Y(lastBench) >= Y(last) ? 7 : -7) : Y(lastBench) / 10;
<span class="end-dot bench-dot" style="left:100%;top:@Pct(Y(lastBench) / 10)"></span>
<span class="end-label bench-label" style="top:@Pct(benchTop)">@Shell.Money(Points[^1].Benchmark!.Value, Currency, decimals: 0)</span>
}
<span class="end-dot" style="left:100%;top:@Pct(Y(last) / 10)"></span>
<span class="end-label" style="top:@Pct(Y(last) / 10)">@Shell.Money(Points[^1].Equity, Currency, decimals: 0)</span>
</div>
</div>
<figcaption class="legend">
<span class="key key-equity">Con Anubis</span>
@if (benchLine.Length > 0)
{
<span class="key key-bench">Senza bot: Bitcoin e S&amp;P 500 comprati e tenuti</span>
}
</figcaption>
<details class="chart-table">
<summary>Vedi i numeri in una tabella</summary>
<div class="table-wrap">
<table class="table">
<thead><tr><th scope="col">Giorno</th><th scope="col" class="num">Con il bot</th><th scope="col" class="num">Senza bot</th></tr></thead>
<tbody>
@foreach (var p in Points.AsEnumerable().Reverse())
{
<tr><td>@Format.LongDate(p.Day)</td><td class="num">@Shell.Money(p.Equity, Currency)</td><td class="num">@(p.Benchmark is { } b ? Shell.Money(b, Currency) : "—")</td></tr>
}
</tbody>
</table>
</div>
</details>
</figure>
}
@code {
[Parameter, EditorRequired]
public IReadOnlyList<EquityPoint> Points { get; set; } = [];
[Parameter]
public string Currency { get; set; } = "EUR";
private static string Fmt(double v) => v.ToString("0.##", CultureInfo.InvariantCulture);
private static string Pct(double v) => v.ToString("0.###", CultureInfo.InvariantCulture) + "%";
// Round steps (1, 2, 2.5, 3, 5 times a power of ten) giving three to five grid lines.
internal static (decimal Lo, decimal Hi, decimal Step) Scale(decimal min, decimal max)
{
if (max <= min)
{
max = min + 1;
}
var raw = (double)(max - min) / 4;
var power = Math.Pow(10, Math.Floor(Math.Log10(raw)));
var step = new[] { 1, 2, 2.5, 3, 5, 10 }.Select(m => m * power).First(s => s >= raw);
var stepValue = (decimal)step;
var lo = Math.Floor(min / stepValue) * stepValue;
var hi = Math.Ceiling(max / stepValue) * stepValue;
return (lo, hi == lo ? lo + stepValue : hi, stepValue);
}
}
+95
View File
@@ -0,0 +1,95 @@
@* Line icons drawn for Anubis: 24 grid, stroke 2, round ends (appendix C). Decorative: the text next to them says it all. *@
<svg class="icon @Class" width="@Size" height="@Size" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false">
@switch (Name)
{
case "grid":
<rect x="3.5" y="3.5" width="7" height="7" rx="1.5" /><rect x="13.5" y="3.5" width="7" height="7" rx="1.5" /><rect x="3.5" y="13.5" width="7" height="7" rx="1.5" /><rect x="13.5" y="13.5" width="7" height="7" rx="1.5" />
break;
case "card":
<rect x="3" y="5.5" width="18" height="13" rx="2.5" /><path d="M3 10h18M16 14.5h2" />
break;
case "arrows":
<path d="M5 8h14M15 4l4 4-4 4M19 16H5M9 12l-4 4 4 4" />
break;
case "layers":
<path d="M12 3 3 8l9 5 9-5-9-5Z" /><path d="m3 12.5 9 5 9-5" /><path d="m3 16.5 9 5 9-5" />
break;
case "news":
<rect x="3.5" y="4" width="17" height="16" rx="2.5" /><path d="M7.5 9h9M7.5 12.5h9M7.5 16h5" />
break;
case "network":
<circle cx="5.5" cy="5.5" r="2.2" /><circle cx="18.5" cy="5.5" r="2.2" /><circle cx="12" cy="18.5" r="2.2" /><path d="M7.5 6.5 11 16.4M16.5 6.5 13 16.4M7.7 5.5h8.6" />
break;
case "shield":
<path d="M12 3 5 6v5.5c0 4.4 3 8 7 9.5 4-1.5 7-5.1 7-9.5V6l-7-3Z" /><path d="m9 12 2.2 2.2L15.5 10" />
break;
case "list":
<path d="M9 6h11M9 12h11M9 18h11" /><circle cx="4.5" cy="6" r="0.6" /><circle cx="4.5" cy="12" r="0.6" /><circle cx="4.5" cy="18" r="0.6" />
break;
case "flask":
<path d="M9.5 3h5M10 3v6.2L4.8 18.3A1.8 1.8 0 0 0 6.4 21h11.2a1.8 1.8 0 0 0 1.6-2.7L14 9.2V3" /><path d="M7.3 15h9.4" />
break;
case "sliders":
<path d="M4 7h9M17 7h3M4 17h3M11 17h9" /><circle cx="15" cy="7" r="2" /><circle cx="9" cy="17" r="2" />
break;
case "dots":
<circle cx="5.5" cy="12" r="1" /><circle cx="12" cy="12" r="1" /><circle cx="18.5" cy="12" r="1" />
break;
case "collapse":
<path d="m11 17-5-5 5-5M18 17l-5-5 5-5" />
break;
case "expand":
<path d="m13 17 5-5-5-5M6 17l5-5-5-5" />
break;
case "pause":
<path d="M9.5 6v12M14.5 6v12" />
break;
case "play":
<path d="M8 5.5v13l10-6.5-10-6.5Z" />
break;
case "stop":
<path d="M8.3 3h7.4L21 8.3v7.4L15.7 21H8.3L3 15.7V8.3L8.3 3Z" /><rect x="9.5" y="9.5" width="5" height="5" rx="0.6" />
break;
case "chevron":
<path d="m6 9 6 6 6-6" />
break;
case "clock":
<circle cx="12" cy="12" r="8.5" /><path d="M12 7.5V12l3 2" />
break;
case "half":
<path d="M12 3.5a8.5 8.5 0 0 0 0 17Z" fill="currentColor" />
break;
case "next":
<path d="M8 3.5h1a8.5 8.5 0 0 1 0 17H8Z" />
break;
case "alert":
<path d="M12 4 2.8 19.5h18.4L12 4Z" /><path d="M12 10v4M12 17h.01" />
break;
case "info":
<circle cx="12" cy="12" r="8.5" /><path d="M12 11v5M12 8h.01" />
break;
case "check":
<circle cx="12" cy="12" r="8.5" /><path d="m8.5 12 2.4 2.4 4.6-4.8" />
break;
case "database":
<ellipse cx="12" cy="6" rx="7.5" ry="2.8" /><path d="M4.5 6v12c0 1.5 3.4 2.8 7.5 2.8s7.5-1.3 7.5-2.8V6M4.5 12c0 1.5 3.4 2.8 7.5 2.8s7.5-1.3 7.5-2.8" />
break;
case "lock":
<rect x="5" y="10.5" width="14" height="10" rx="2.2" /><path d="M8.5 10.5V7.8a3.5 3.5 0 0 1 7 0v2.7" />
break;
case "logout":
<path d="M14 4h4.5A1.5 1.5 0 0 1 20 5.5v13a1.5 1.5 0 0 1-1.5 1.5H14M10 16l-4-4 4-4M6 12h10" />
break;
}
</svg>
@code {
[Parameter, EditorRequired]
public string Name { get; set; } = "";
[Parameter]
public int Size { get; set; } = 20;
[Parameter]
public string? Class { get; set; }
}
@@ -0,0 +1,125 @@
@inject AnubisHost Host
@inject IClock Clock
@* SPEC 15.1: database and data folder disagree. The user chooses; Docker asks the startup password because users
and sessions live in the database that is missing, desktop accepts choices only from the computer itself. *@
@{
var verdict = Status.Identity!.Verdict;
var data = Host.Config.Data;
var docker = Host.Config.Platform == PlatformKind.Docker;
var canChoose = docker || Local;
}
@switch (verdict)
{
case IdentityVerdict.EmptyDatabase:
<p>Il database è vuoto, ma la cartella dei dati appartiene a un'installazione che esiste già. Il motore resta spento: se partisse, comincerebbe da zero e i conti risulterebbero diversi dal registro.</p>
break;
case IdentityVerdict.DifferentInstallation:
<p>Il database appartiene a un'altra installazione di Anubis. Il motore resta spento: due registri sugli stessi conti produrrebbero ordini doppi.</p>
break;
case IdentityVerdict.StaleDatabase:
<p>È il database di questa installazione, ma una copia più vecchia: dopo l'ultimo ripristino o spostamento ne è nata una più recente. Il motore resta spento per non lavorare su dati superati.</p>
break;
}
<dl class="facts">
<dt>Database</dt><dd>@Host.Config.Db?.Describe()</dd>
<dt>Cartella dei dati</dt><dd>@data.Root</dd>
@if (Status.Identity.File is { } file)
{
<dt>Installazione della cartella</dt><dd>@file.InstallationId.ToString("D")[..8], nata il @Format.ShortDate(file.CreatedAt, Clock.UtcNow, Host.Config.TimeZone, withTime: false)</dd>
}
@if (Status.Identity.Row is { } row)
{
<dt>Installazione del database</dt><dd>@row.Id.ToString("D")[..8], nata il @Format.ShortDate(row.CreatedAt, Clock.UtcNow, Host.Config.TimeZone, withTime: false)</dd>
}
</dl>
<p class="hint">La soluzione più sicura spesso è correggere la configurazione perché punti al database giusto. Altrimenti scegli qui sotto. Dopo un ripristino o un'importazione il bot riparte protetto: "Ferma tutto" acceso finché non confermi.</p>
@if (!canChoose)
{
<p class="notice notice-attention" role="status"><Icon Name="lock" Size="16" />Queste scelte si fanno solo dal computer su cui gira Anubis.</p>
}
else
{
@if (verdict == IdentityVerdict.EmptyDatabase)
{
var backups = new Backups(data, Clock).List();
var imports = ServiceChoices.ImportFolders(data);
<section class="service-section">
<h2>Ripristina un salvataggio</h2>
@if (backups.Count == 0)
{
<p class="hint">Nessun salvataggio nella cartella <code>@data.Backups</code>.</p>
}
else
{
<form method="post" action="/azioni/servizio/ripristina" class="form">
<AntiforgeryToken />
<label for="salvataggio">Salvataggio</label>
<select id="salvataggio" name="salvataggio">
@foreach (var backup in backups)
{
<option value="@backup.Name">@Format.ShortDate(backup.TakenAt, Clock.UtcNow, Host.Config.TimeZone) · @backup.Reason</option>
}
</select>
<AdminPassword Docker="docker" />
<button class="btn btn-primary" type="submit">Ripristina</button>
</form>
}
</section>
<section class="service-section">
<h2>Importa un archivio</h2>
@if (imports.Count == 0)
{
<p class="hint">Metti la cartella di un archivio esportato (con il suo <code>index.json</code>) dentro <code>@data.Import</code> e ricarica la pagina.</p>
}
else
{
<form method="post" action="/azioni/servizio/importa" class="form">
<AntiforgeryToken />
<label for="archivio">Archivio</label>
<select id="archivio" name="archivio">
@foreach (var folder in imports)
{
<option value="@Path.GetFileName(folder)">@Path.GetFileName(folder)</option>
}
</select>
<AdminPassword Docker="docker" />
<button class="btn btn-primary" type="submit">Importa</button>
</form>
}
</section>
<section class="service-section">
<h2>Comincia da capo</h2>
<p class="hint">Una nuova installazione in questo database vuoto. Il file d'identità della cartella viene messo da parte, non cancellato.</p>
<form method="post" action="/azioni/servizio/da-capo" class="form">
<AntiforgeryToken />
<AdminPassword Docker="docker" />
<button class="btn btn-danger" type="submit" data-confirm="Cominciare da capo con un database vuoto? Lo storico precedente resta nei salvataggi.">Comincia da capo</button>
</form>
</section>
}
else
{
<section class="service-section">
<h2>Usa comunque questo database</h2>
<p class="hint">Diventa il database di questa installazione con una nuova impronta. Ogni altra copia non verrà più accettata. Il bot riparte protetto.</p>
<form method="post" action="/azioni/servizio/usa-questo" class="form">
<AntiforgeryToken />
<AdminPassword Docker="docker" />
<button class="btn btn-danger" type="submit" data-confirm="Usare questo database da ora in poi? Le altre copie non saranno più accettate.">Usa questo database</button>
</form>
</section>
}
}
@code {
[Parameter, EditorRequired]
public HostStatus Status { get; set; } = null!;
[Parameter]
public bool Local { get; set; }
}
@@ -0,0 +1,118 @@
@inherits LoadedLayout
@inject ShellData Shell
@inject NavigationManager Navigation
@* The shell of SPEC 13.4: menu on the left (collapsible, remembered), top bar with state and commands, on phones a
bottom bar with five entries. Rendered on the server; app.js keeps state and freshness live over the WebSocket. *@
<div class="shell" data-shell>
<nav class="sidebar" aria-label="Menu principale">
<div class="brand">
<a class="brand-link" href="/">
<img class="logo logo-light" src="/brand/anubis.svg" alt="" width="28" height="28" />
<img class="logo logo-dark" src="/brand/anubis-dark.svg" alt="" width="28" height="28" />
<span class="brand-name">Anubis</span>
</a>
<button type="button" class="icon-button collapse" data-collapse aria-label="Comprimi il menu" aria-expanded="true">
<Icon Name="collapse" Class="when-open" /><Icon Name="expand" Class="when-closed" />
</button>
</div>
@foreach (var group in Menu.Groups)
{
<ul class="nav-group">
@foreach (var item in group)
{
<li>
<a class="nav-item @(IsActive(item.Path) ? "active" : null)" href="@item.Path" aria-current="@(IsActive(item.Path) ? "page" : null)" title="@item.Label">
<Icon Name="@item.Icon" /><span class="nav-label">@item.Label</span>
</a>
</li>
}
</ul>
}
</nav>
<div class="main">
<header class="topbar">
<div class="topbar-title">
<a class="phone-brand" href="/">
<img class="logo logo-light" src="/brand/anubis.svg" alt="" width="24" height="24" />
<img class="logo logo-dark" src="/brand/anubis-dark.svg" alt="" width="24" height="24" />
<span>Anubis</span>
</a>
<span class="phone-bot" data-live="bot" data-state="@_shell.Bot"><span class="dot"></span><span data-live="bot-short">@_shell.BotShort</span></span>
<h1>@Menu.Title(_path)</h1>
<p class="status-line">
<span data-live="now">@_shell.Now</span>. <span data-live="age" data-age="@_shell.AgeSeconds">Dati aggiornati @Format.Ago(TimeSpan.FromSeconds(_shell.AgeSeconds))</span>.
</p>
</div>
<div class="topbar-actions">
<span class="pill pill-bot" data-live="bot" data-state="@_shell.Bot"><span class="dot"></span><span data-live="bot-label">@_shell.BotLabel</span></span>
<span class="pill pill-mode"><Icon Name="flask" Size="16" />Simulazione: nessun soldo reale</span>
<form class="currency" method="post" action="/azioni/impostazioni/appearance.currency">
<AntiforgeryToken />
<input type="hidden" name="ritorno" value="@_back" />
<label class="sr-only" for="valuta">Valuta di visualizzazione</label>
<select id="valuta" name="valore" data-autosubmit>
<option value="EUR" selected="@(_shell.Currency == "EUR")">EUR</option>
<option value="USD" selected="@(_shell.Currency == "USD")">USD</option>
</select>
<Icon Name="chevron" Size="16" Class="select-chevron" />
<noscript><button class="btn btn-small" type="submit">Cambia</button></noscript>
</form>
@if (_shell.Bot == "paused")
{
<form method="post" action="/azioni/bot/riprendi"><AntiforgeryToken /><input type="hidden" name="ritorno" value="@_back" /><button class="btn" type="submit"><Icon Name="play" Size="18" />Riprendi</button></form>
}
else if (_shell.Bot == "active")
{
<form method="post" action="/azioni/bot/pausa"><AntiforgeryToken /><input type="hidden" name="ritorno" value="@_back" /><button class="btn" type="submit"><Icon Name="pause" Size="18" />Metti in pausa</button></form>
}
<form class="stop-form" method="post" action="/azioni/bot/ferma"><AntiforgeryToken /><input type="hidden" name="ritorno" value="@_back" /><button class="btn btn-danger" type="submit" data-confirm="Ferma tutto: il bot non apre né gestisce nuove operazioni finché non lo riattivi dalla pagina Rischio. Confermi?" disabled="@(_shell.Bot == "stopped")"><Icon Name="stop" Size="18" />Ferma tutto</button></form>
</div>
</header>
<div class="mode-band"><Icon Name="flask" Size="16" />Simulazione: nessun soldo reale</div>
<div class="stale-notice" data-stale hidden role="status"><Icon Name="alert" Size="16" /><span data-stale-text>Collegamento interrotto.</span></div>
<main class="page" id="contenuto">
@Body
<footer class="page-footer">
@if (Shell.IsDemo)
{
<p>Modalità dimostrativa. Numeri, titoli e notizie sono dati di esempio.</p>
}
else
{
<p>Anubis @AnubisInfo.Version</p>
}
</footer>
</main>
</div>
<nav class="bottombar" aria-label="Menu del telefono">
@foreach (var item in Menu.Phone)
{
<a class="bottom-item @(IsActive(item.Path) ? "active" : null)" href="@item.Path" aria-current="@(IsActive(item.Path) ? "page" : null)">
<Icon Name="@item.Icon" Size="22" /><span>@item.Label</span>
</a>
}
</nav>
</div>
@code {
private ShellSnapshot _shell = null!;
private string _path = "/";
private string _back = "/";
[CascadingParameter]
public HttpContext? HttpContext { get; set; }
protected override async Task LoadAsync()
{
_shell = await Shell.SnapshotAsync(HttpContext?.RequestAborted ?? CancellationToken.None);
var uri = new Uri(Navigation.Uri);
_path = uri.AbsolutePath;
_back = uri.PathAndQuery;
}
private bool IsActive(string path) => path == "/" ? _path == "/" : _path.StartsWith(path, StringComparison.Ordinal);
}
@@ -0,0 +1,15 @@
@inherits LayoutComponentBase
@inject ShellData Shell
@* Pages outside the shell: sign-in, first run, first access, error page. *@
<div class="service">
<div class="service-box">
<div class="service-brand">
<img class="logo logo-light" src="/brand/anubis.svg" alt="" width="36" height="36" />
<img class="logo logo-dark" src="/brand/anubis-dark.svg" alt="" width="36" height="36" />
<span>Anubis</span>
</div>
@Body
<p class="service-foot">Anubis @AnubisInfo.Version@(Shell.IsDemo ? " · modalità dimostrativa" : "")</p>
</div>
</div>
+49
View File
@@ -0,0 +1,49 @@
using Microsoft.AspNetCore.Components;
namespace Anubis.Server.Components;
/// <summary>
/// A component that reads its data before drawing anything. With static rendering, a plain <c>OnInitializedAsync</c>
/// that really waits (PostgreSQL does; SQLite answers at once) lets Blazor draw the component once with its fields
/// still empty. Here the data are loaded first, then the component renders once.
/// </summary>
public abstract class LoadedComponent : ComponentBase
{
private bool _loaded;
public override async Task SetParametersAsync(ParameterView parameters)
{
parameters.SetParameterProperties(this);
if (!_loaded)
{
_loaded = true;
await LoadAsync().ConfigureAwait(true);
}
await base.SetParametersAsync(ParameterView.Empty).ConfigureAwait(true);
}
/// <summary>Reads what the component shows. Parameters, cascading values and query values are already set.</summary>
protected abstract Task LoadAsync();
}
/// <summary>The same for the layout.</summary>
public abstract class LoadedLayout : LayoutComponentBase
{
private bool _loaded;
public override async Task SetParametersAsync(ParameterView parameters)
{
parameters.SetParameterProperties(this);
if (!_loaded)
{
_loaded = true;
await LoadAsync().ConfigureAwait(true);
}
await base.SetParametersAsync(ParameterView.Empty).ConfigureAwait(true);
}
/// <inheritdoc cref="LoadedComponent.LoadAsync"/>
protected abstract Task LoadAsync();
}
+39
View File
@@ -0,0 +1,39 @@
namespace Anubis.Server.Components;
internal sealed record MenuItem(string Path, string Label, string Icon, string Title);
/// <summary>The screens of SPEC 13.6 in the order of the mockups.</summary>
internal static class Menu
{
public static readonly MenuItem Overview = new("/", "Panoramica", "grid", "Panoramica");
public static readonly MenuItem Accounts = new("/conti", "Conti e posizioni", "card", "Conti e posizioni");
public static readonly MenuItem Trades = new("/operazioni", "Operazioni", "arrows", "Operazioni");
public static readonly MenuItem Strategies = new("/strategie", "Strategie", "layers", "Strategie");
public static readonly MenuItem News = new("/notizie", "Notizie e mercato", "news", "Notizie e mercato");
public static readonly MenuItem Learning = new("/apprendimento", "Apprendimento", "network", "Apprendimento");
public static readonly MenuItem Risk = new("/rischio", "Rischio", "shield", "Rischio");
public static readonly MenuItem Journal = new("/diario", "Diario e sistema", "list", "Diario e sistema");
public static readonly MenuItem Lab = new("/laboratorio", "Laboratorio", "flask", "Laboratorio");
public static readonly MenuItem Settings = new("/impostazioni", "Impostazioni", "sliders", "Impostazioni");
public static readonly MenuItem More = new("/altro", "Altro", "dots", "Altro");
public static readonly IReadOnlyList<IReadOnlyList<MenuItem>> Groups =
[
[Overview, Accounts, Trades],
[Strategies, News, Learning],
[Risk, Journal, Lab, Settings],
];
/// <summary>The bottom bar of the phone (SPEC 13.4).</summary>
public static readonly IReadOnlyList<MenuItem> Phone =
[
Overview,
Accounts with { Label = "Conti" },
Journal with { Label = "Diario" },
Risk,
More,
];
public static string Title(string path) =>
Groups.SelectMany(g => g).Append(More).FirstOrDefault(i => i.Path == "/" ? path == "/" : path.StartsWith(i.Path, StringComparison.Ordinal))?.Title ?? "Anubis";
}
@@ -0,0 +1,46 @@
@page "/accesso"
@layout ServiceLayout
@attribute [AllowAnonymous]
<PageTitle>Accesso · Anubis</PageTitle>
<h1>Accedi</h1>
@if (Message is { } message)
{
<p class="notice notice-loss" role="alert"><Icon Name="alert" Size="16" />@message</p>
}
<form method="post" action="/azioni/accesso" class="form">
<AntiforgeryToken />
<input type="hidden" name="ritorno" value="@(Ritorno is { } r && Forms.IsLocalPath(r) ? r : "/")" />
<label for="password">Password</label>
<input id="password" name="password" type="password" autocomplete="current-password" required autofocus />
@if (Fattore == "1")
{
<label for="codice">Codice dell'app di autenticazione</label>
<input id="codice" name="codice" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]{6}" maxlength="6" required />
<p class="hint">Sei cifre, cambiano ogni 30 secondi. Scrivi di nuovo anche la password.</p>
}
<button class="btn btn-primary" type="submit">Accedi</button>
</form>
@code {
[SupplyParameterFromQuery(Name = "errore")]
public string? Errore { get; set; }
[SupplyParameterFromQuery(Name = "minuti")]
public string? Minuti { get; set; }
[SupplyParameterFromQuery(Name = "fattore")]
public string? Fattore { get; set; }
[SupplyParameterFromQuery(Name = "ritorno")]
public string? Ritorno { get; set; }
private string? Message => Errore switch
{
"password" => "Password sbagliata. Riprova: dopo 5 tentativi sbagliati l'accesso si blocca per 15 minuti.",
"codice" => "Il codice non è giusto o è scaduto. Usa quello che l'app mostra adesso.",
"attesa" => $"Troppi tentativi sbagliati. Riprova tra {Minuti ?? "15"} minuti.",
_ => null,
};
}
@@ -0,0 +1,44 @@
@inherits LoadedComponent
@page "/altro"
@inject ShellData Shell
<PageTitle>Altro · Anubis</PageTitle>
@* On the phone: the screens that do not fit the bottom bar, the pause and the currency (SPEC 13.4). *@
<section class="panel">
<ul class="more-list">
@foreach (var item in Menu.Groups.SelectMany(g => g).Where(i => !Menu.Phone.Any(p => p.Path == i.Path)))
{
<li><a href="@item.Path"><Icon Name="@item.Icon" />@item.Label</a></li>
}
</ul>
</section>
<section class="panel">
<h2>Comandi</h2>
<div class="form-inline">
@if (_shell.Bot == "active")
{
<form method="post" action="/azioni/bot/pausa"><AntiforgeryToken /><input type="hidden" name="ritorno" value="/altro" /><button class="btn" type="submit"><Icon Name="pause" Size="18" />Metti in pausa</button></form>
}
else if (_shell.Bot == "paused")
{
<form method="post" action="/azioni/bot/riprendi"><AntiforgeryToken /><input type="hidden" name="ritorno" value="/altro" /><button class="btn" type="submit"><Icon Name="play" Size="18" />Riprendi</button></form>
}
<form method="post" action="/azioni/impostazioni/appearance.currency">
<AntiforgeryToken />
<input type="hidden" name="ritorno" value="/altro" />
<input type="hidden" name="valore" value="@(_shell.Currency == "EUR" ? "USD" : "EUR")" />
<button class="btn" type="submit">Mostra in @(_shell.Currency == "EUR" ? "dollari" : "euro")</button>
</form>
@if (!Shell.IsDemo)
{
<form method="post" action="/azioni/esci"><AntiforgeryToken /><button class="btn" type="submit"><Icon Name="logout" Size="18" />Esci</button></form>
}
</div>
</section>
@code {
private ShellSnapshot _shell = null!;
protected override async Task LoadAsync() => _shell = await Shell.SnapshotAsync(CancellationToken.None);
}
@@ -0,0 +1,5 @@
@page "/apprendimento"
<PageTitle>Apprendimento · Anubis</PageTitle>
<Pending Title="Il modello non è ancora in osservazione.">Comincia a imparare quando ci sono abbastanza segnali: qui vedrai quanti ne mancano e quanto è preciso su casi mai visti.</Pending>
@@ -0,0 +1,5 @@
@page "/conti"
<PageTitle>Conti e posizioni · Anubis</PageTitle>
<Pending Title="Nessun conto collegato.">Conti, posizioni e ordini arrivano con la contabilità: lì aggiungerai le chiavi dei conti di prova e vedrai patrimonio, liquidità e commissioni di ciascuno.</Pending>
@@ -0,0 +1,90 @@
@inherits LoadedComponent
@page "/diario"
@inject AnubisHost Host
@inject ShellData Shell
<PageTitle>Diario e sistema · Anubis</PageTitle>
<div class="columns">
<section class="panel">
<h2>Diario</h2>
@if (_entries.Count == 0)
{
<p class="note">Ancora nessuna voce.</p>
}
else
{
<div class="table-wrap">
<table class="table">
<thead><tr><th scope="col">Quando</th><th scope="col">Tipo</th><th scope="col">Voce</th></tr></thead>
<tbody>
@foreach (var e in _entries)
{
<tr><td class="nowrap">@Format.ShortDate(e.At, Shell.Now, Shell.Zone)</td><td>@e.Kind</td><td>@e.Text</td></tr>
}
</tbody>
</table>
</div>
}
</section>
<section class="panel">
<h2>Sistema</h2>
<dl class="facts">
<dt>Versione</dt><dd>@AnubisInfo.Version</dd>
<dt>Piattaforma</dt><dd>@(Host.Config.Platform == PlatformKind.Docker ? "Docker" : "Desktop")</dd>
<dt>Database</dt><dd>@(Host.Config.Db?.Engine == DbEngine.Postgres ? "PostgreSQL" : "SQLite") · risponde</dd>
<dt>In funzione da</dt><dd>@Format.Ago(Shell.Now - _since).Replace(" fa", "", StringComparison.Ordinal)</dd>
</dl>
<h3 class="list-title">Lavori in programma</h3>
<ul class="moves">
@foreach (var job in _upcoming)
{
<li><span class="move-time">@Format.ShortDate(job.DueUtc, Shell.Now, Shell.Zone)</span><span>@job.Description</span></li>
}
</ul>
@if (_jobs.Count > 0)
{
<h3 class="list-title">Ultimi lavori</h3>
<ul class="moves moves-past">
@foreach (var job in _jobs)
{
<li><span class="move-time">@(job.Finished is { } f ? Format.ShortDate(f, Shell.Now, Shell.Zone) : "—")</span><span>@job.Description: @Outcome(job.Outcome)</span></li>
}
</ul>
}
</section>
</div>
@code {
private List<(DateTimeOffset At, string Kind, string Text)> _entries = [];
private List<(string Description, DateTimeOffset? Finished, string? Outcome)> _jobs = [];
private IReadOnlyList<UpcomingRun> _upcoming = [];
private DateTimeOffset _since;
[CascadingParameter]
public HttpContext? HttpContext { get; set; }
protected override async Task LoadAsync()
{
var ct = HttpContext?.RequestAborted ?? CancellationToken.None;
var services = Host.Services!;
(_entries, _jobs) = await services.Db.ReadAsync(async s =>
{
var entries = await s.QueryAsync("SELECT occurred_at, kind, message FROM journal ORDER BY occurred_at DESC LIMIT 200",
r => (r.Moment("occurred_at"), r.Text("kind"), r.Text("message")));
var jobs = await s.QueryAsync("SELECT description, last_finished_at, last_outcome FROM jobs ORDER BY last_finished_at DESC",
r => (r.Text("description"), r.MomentOrNull("last_finished_at"), r.TextOrNull("last_outcome")));
return (entries, jobs);
}, ct);
_upcoming = services.Scheduler.Upcoming(10);
_since = Host.Status.Since;
}
private static string Outcome(string? outcome) => outcome switch
{
"succeeded" => "fatto",
"failed" => "non riuscito",
"skipped" => "saltato, orario superato",
_ => "in attesa",
};
}
@@ -0,0 +1,230 @@
@inherits LoadedComponent
@page "/impostazioni"
@inject AnubisHost Host
@inject ShellData Shell
@inject SecondFactorDrafts Drafts
<PageTitle>Impostazioni · Anubis</PageTitle>
@* First part of SPEC 13.5: appearance, security, system. The other sections arrive with their phases. *@
@if (Ok is { } ok)
{
<p class="notice notice-gain" role="status"><Icon Name="check" Size="16" />@(ok switch
{
"password" => "Password cambiata. Le altre sessioni sono state chiuse.",
"due-fattori" => "Secondo fattore attivato.",
"due-fattori-tolti" => "Secondo fattore disattivato.",
"salvataggio" => "Salvataggio fatto.",
_ => "Fatto.",
})</p>
}
@if (ErrorText is { } error)
{
<p class="notice notice-loss" role="alert"><Icon Name="alert" Size="16" />@error</p>
}
<nav class="tabs" aria-label="Sezioni delle impostazioni">
<a href="#aspetto">Aspetto</a><a href="#sicurezza">Sicurezza</a><a href="#sistema">Sistema</a><a href="#modifiche">Modifiche</a>
</nav>
<section class="panel" id="aspetto">
<h2>Aspetto</h2>
@foreach (var setting in _appearance)
{
var definition = SettingsStore.Definition(setting.Key);
<form method="post" action="/azioni/impostazioni/@setting.Key" class="form-inline">
<AntiforgeryToken />
<input type="hidden" name="ritorno" value="/impostazioni#aspetto" />
<label for="@setting.Key">@definition.Label</label>
<select id="@setting.Key" name="valore" disabled="@setting.ReadOnly" data-autosubmit>
@foreach (var value in definition.Allowed!)
{
<option value="@value" selected="@(value == setting.Value)">@Label(value)</option>
}
</select>
@if (setting.ReadOnly)
{
<span class="hint">Fissato da @setting.Source: si cambia lì.</span>
}
else
{
<button class="btn btn-small" type="submit">Salva</button>
}
</form>
}
<p class="hint">Gli importi in dollari usano il cambio del giorno, che arriva con i dati di mercato. Fino ad allora restano in euro.</p>
</section>
<section class="panel" id="sicurezza">
<h2>Sicurezza</h2>
@if (Shell.IsDemo)
{
<p class="hint">Nella modalità dimostrativa password e secondo fattore non si cambiano.</p>
}
else
{
<h3>Password</h3>
<form method="post" action="/azioni/password" class="form">
<AntiforgeryToken />
<label for="attuale">Password attuale</label>
<input id="attuale" name="attuale" type="password" autocomplete="current-password" required />
<label for="nuova">Nuova password</label>
<input id="nuova" name="nuova" type="password" autocomplete="new-password" minlength="@Passwords.MinimumLength" required />
<label for="conferma">Scrivila di nuovo</label>
<input id="conferma" name="conferma" type="password" autocomplete="new-password" minlength="@Passwords.MinimumLength" required />
<button class="btn" type="submit">Cambia password</button>
</form>
<h3>Secondo fattore</h3>
@if (_hasSecondFactor)
{
<p>Attivo: all'accesso chiedo anche il codice dell'app. Servirà anche per attivare i soldi veri.</p>
<form method="post" action="/azioni/due-fattori/disattiva" class="form">
<AntiforgeryToken />
<label for="password-2fa">Per disattivarlo: password</label>
<input id="password-2fa" name="password" type="password" autocomplete="current-password" required />
<label for="codice-2fa">Codice dell'app</label>
<input id="codice-2fa" name="codice" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]{6}" maxlength="6" required />
<button class="btn" type="submit">Disattiva il secondo fattore</button>
</form>
}
else
{
<p>Facoltativo: un codice di sei cifre da un'app di autenticazione (per esempio quella del tuo gestore di password), oltre alla password.</p>
<ol class="steps">
<li>Nell'app scegli "aggiungi con chiave" e scrivi questa chiave: <code class="secret">@_draft</code></li>
<li>Oppure, se l'app accetta un indirizzo, usa: <code class="secret">@_draftUri</code></li>
<li>Scrivi qui il codice che l'app mostra.</li>
</ol>
<form method="post" action="/azioni/due-fattori/attiva" class="form">
<AntiforgeryToken />
<label for="codice">Codice</label>
<input id="codice" name="codice" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]{6}" maxlength="6" required />
<button class="btn" type="submit">Attiva il secondo fattore</button>
</form>
}
<form method="post" action="/azioni/esci" class="form-inline"><AntiforgeryToken /><button class="btn" type="submit"><Icon Name="logout" Size="18" />Esci</button></form>
}
</section>
<section class="panel" id="sistema">
<h2>Sistema</h2>
<dl class="facts">
<dt>Piattaforma</dt><dd>@(Host.Config.Platform == PlatformKind.Docker ? "Docker" : "Desktop (Windows)")</dd>
<dt>Database</dt><dd>@Host.Config.Db?.Describe()</dd>
<dt>Cartella dei dati</dt><dd>@Host.Config.Data.Root</dd>
<dt>Chiave dei segreti</dt><dd>@Host.Config.SecretKey.Description</dd>
<dt>Fuso orario</dt><dd>@Host.Config.TimeZone.Id</dd>
<dt>Versione</dt><dd>@AnubisInfo.Version</dd>
</dl>
<p class="hint">
@if (Host.Config.Platform == PlatformKind.Docker)
{
@:Motore e connessione del database si cambiano solo nella configurazione del container.
}
else
{
@:Motore e connessione del database stanno in config.toml, nella cartella dei dati. Lo spostamento su un altro database arriva con l'applicazione desktop.
}
</p>
<h3>Salvataggi</h3>
<p class="hint">Ogni notte alle 03:30 e prima di ogni aggiornamento dello schema. Tengo gli ultimi @Backups.Keep.</p>
<form method="post" action="/azioni/salvataggio" class="form-inline"><AntiforgeryToken /><button class="btn" type="submit"><Icon Name="database" Size="18" />Salva adesso</button></form>
@if (_backups.Count > 0)
{
<div class="table-wrap">
<table class="table">
<thead><tr><th scope="col">Quando</th><th scope="col">Perché</th><th scope="col">Cartella</th></tr></thead>
<tbody>
@foreach (var b in _backups)
{
<tr><td class="nowrap">@Format.ShortDate(b.TakenAt, Shell.Now, Shell.Zone)</td><td>@b.Reason</td><td><code>@b.Name</code></td></tr>
}
</tbody>
</table>
</div>
}
</section>
<section class="panel" id="modifiche">
<h2>Registro delle modifiche</h2>
@if (_history.Count == 0)
{
<p class="note">Nessuna modifica finora.</p>
}
else
{
<div class="table-wrap">
<table class="table">
<thead><tr><th scope="col">Quando</th><th scope="col">Voce</th><th scope="col">Prima</th><th scope="col">Dopo</th><th scope="col">Chi</th></tr></thead>
<tbody>
@foreach (var h in _history)
{
<tr><td class="nowrap">@Format.ShortDate(h.At, Shell.Now, Shell.Zone)</td><td>@h.Key</td><td>@Label(h.OldValue)</td><td>@Label(h.NewValue)</td><td>@h.ChangedBy</td></tr>
}
</tbody>
</table>
</div>
}
</section>
@code {
private readonly List<SettingValue> _appearance = [];
private List<SettingChange> _history = [];
private IReadOnlyList<BackupInfo> _backups = [];
private bool _hasSecondFactor;
private string? _draft;
private string? _draftUri;
[CascadingParameter]
public HttpContext? HttpContext { get; set; }
[SupplyParameterFromQuery(Name = "ok")]
public string? Ok { get; set; }
[SupplyParameterFromQuery(Name = "errore")]
public string? Errore { get; set; }
protected override async Task LoadAsync()
{
var ct = HttpContext?.RequestAborted ?? CancellationToken.None;
var services = Host.Services!;
_appearance.Add(await services.Settings.GetAsync(SettingsStore.Theme.Key, ct));
_appearance.Add(await services.Settings.GetAsync(SettingsStore.Currency.Key, ct));
_history = await services.Settings.HistoryAsync(null, 50, ct);
_backups = services.Backups.List();
var user = HttpContext!.User;
_hasSecondFactor = CurrentUser.HasSecondFactor(user);
if (!_hasSecondFactor && !Shell.IsDemo)
{
var secret = Drafts.For(CurrentUser.Session(user));
_draft = Base32.Encode(secret);
_draftUri = Totp.Uri("Anubis", AccessStore.AdminName, secret);
}
}
private string? ErrorText => Errore switch
{
"codice" => "Il codice non è giusto. Controlla l'ora del telefono e riprova con il codice che vedi adesso.",
"segreto" => "La chiave è scaduta: ricarica la pagina e aggiungi di nuovo Anubis nell'app.",
"salvataggio" => "Il salvataggio non è riuscito. Controlla lo spazio libero nella cartella dei dati.",
"impostazione" => "Questa impostazione non si può cambiare così.",
"bot" => "Comando non ammesso nello stato attuale del bot.",
_ => PasswordMessages.For(Errore),
};
private static string Label(string? value) => value switch
{
null => "—",
"auto" => "Come il sistema",
"light" => "Chiaro",
"dark" => "Scuro",
"EUR" => "Euro (EUR)",
"USD" => "Dollaro (USD)",
"active" => "Attivo",
"paused" => "In pausa",
"stopped" => "Fermo",
_ => value.Trim('"'),
};
}
@@ -0,0 +1,5 @@
@page "/laboratorio"
<PageTitle>Laboratorio · Anubis</PageTitle>
<Pending Title="Nessun test eseguito.">Il laboratorio dei test sul passato arriva con il motore dei backtest.</Pending>
@@ -0,0 +1,5 @@
@page "/notizie"
<PageTitle>Notizie e mercato · Anubis</PageTitle>
<Pending Title="Nessuna notizia letta finora.">La lettura delle notizie, l'umore del mercato e il calendario degli eventi arrivano in una fase successiva.</Pending>
@@ -0,0 +1,5 @@
@page "/operazioni"
<PageTitle>Operazioni · Anubis</PageTitle>
<Pending Title="Ancora nessuna operazione chiusa.">Quando il bot comincerà a lavorare, qui troverai ogni operazione con il suo risultato e il perché di ogni ingresso e uscita.</Pending>
@@ -0,0 +1,134 @@
@inherits LoadedComponent
@page "/"
@inject AnubisHost Host
@inject ShellData Shell
<PageTitle>Panoramica · Anubis</PageTitle>
@{
var o = _overview;
var c = _currency;
}
<section class="panel head-block" aria-label="Il punto della situazione">
<div class="half half-past">
<div class="half-head">
<h2><Icon Name="half" Size="18" />Finora</h2>
@if (o.HasData)
{
<nav class="segmented" aria-label="Periodo">
@foreach (var (key, label) in Overview.Periods)
{
<a href="@(key == "avvio" ? "/" : "/?periodo=" + key)" class="@(key == _period ? "on" : null)" aria-current="@(key == _period ? "true" : null)">@label</a>
}
</nav>
}
</div>
@if (!o.HasData)
{
<div class="empty">
<p class="empty-title">Ancora nessun risultato da mostrare.</p>
<p>Il patrimonio comincia a essere registrato quando colleghi un conto. Da quel giorno qui vedrai quanto stai guadagnando o perdendo, al netto dei costi, e il confronto con chi non usa il bot.</p>
</div>
}
else
{
var gain = o.Result.Amount >= 0;
<p class="lead">@(gain ? "Sei in profitto di" : "Sei in perdita di")</p>
<div class="big-result">
<span class="big-number">@Shell.Money(o.Result.Amount, c, withSign: true)</span>
<span class="badge @(gain ? "badge-gain" : "badge-loss")"><Arrow Up="gain" />@Format.Percent(o.Result.Percent, 2, withSign: true)</span>
</div>
<p class="note">Dal @Format.LongDate(o.From), partendo da @Shell.Money(o.FromEquity, c). Commissioni già tolte.</p>
<div class="cells">
@foreach (var (cell, i) in o.Cells.Select((x, i) => (x, i)))
{
var up = cell.Amount >= 0;
var label = cell.Label.StartsWith("Ultimi ", StringComparison.Ordinal) ? cell.Label["Ultimi ".Length..] : cell.Label;
<div class="cell @(i >= 3 ? "cell-extra" : null)">
<span class="cell-label">@if (label != cell.Label) {<span class="long">Ultimi </span>}@label</span>
<span class="cell-value">@Shell.Money(cell.Amount, c, withSign: true)</span>
<span class="cell-change @(up ? "gain" : "loss")"><Arrow Up="up" />@Format.Percent(cell.Percent, 2, withSign: true)</span>
</div>
}
</div>
<EquityChart Points="o.Series" Currency="c" />
}
</div>
<div class="half half-next">
<div class="half-head">
<h2><Icon Name="next" Size="18" />Adesso e dopo</h2>
@if (_runningDays is { } days)
{
<span class="note">Attivo da @days giorni senza interruzioni</span>
}
</div>
<p class="statement">@Statement(o)</p>
<h3 class="list-title">Prossime mosse</h3>
@if (o.Next.Count == 0)
{
<p class="note">Niente in programma.</p>
}
else
{
<ul class="moves">
@foreach (var move in o.Next)
{
<li><span class="move-time">@move.Time</span><span>@move.Text</span></li>
}
</ul>
}
<h3 class="list-title">Ultime azioni</h3>
@if (o.Last.Count == 0)
{
<p class="note">Ancora nessuna voce nel diario.</p>
}
else
{
<ul class="moves moves-past">
@foreach (var action in o.Last)
{
<li><span class="move-time">@action.When</span><span>@action.Text</span></li>
}
</ul>
<a class="more" href="/diario">Tutto il diario</a>
}
</div>
</section>
@code {
private Overview _overview = null!;
private string _currency = "EUR";
private string _period = "avvio";
private int? _runningDays;
[CascadingParameter]
public HttpContext? HttpContext { get; set; }
[SupplyParameterFromQuery(Name = "periodo")]
public string? Periodo { get; set; }
protected override async Task LoadAsync()
{
var ct = HttpContext?.RequestAborted ?? CancellationToken.None;
_period = Periodo is "30" or "7" or "oggi" ? Periodo : "avvio";
var services = Host.Services!;
_currency = Shell.Effective((await services.Settings.GetAsync(SettingsStore.Currency.Key, ct)).Value);
_overview = await Overview.LoadAsync(services, _period, Shell.Now, Shell.Zone, ct);
using var aggregates = Shell.Aggregates();
_runningDays = aggregates?.RootElement.GetProperty("giorno").GetInt32();
}
private static string Statement(Overview o)
{
var orders = o.OpenOrders == 0 ? "Nessun ordine in corso." : o.OpenOrders == 1 ? "Un ordine in corso." : $"{o.OpenOrders} ordini in corso.";
if (o.Positions == 0)
{
return "Nessuna posizione aperta. " + orders;
}
var stops = o.PositionsWithoutStop == 0
? (o.Positions == 1 ? "con il suo stop" : "ognuna con il suo stop")
: $"{o.PositionsWithoutStop} senza stop";
return o.Positions == 1 ? $"Sorveglio una posizione, {stops}. {orders}" : $"Sorveglio {o.Positions} posizioni, {stops}. {orders}";
}
}
@@ -0,0 +1,43 @@
@page "/primo-accesso"
@layout ServiceLayout
@inject AnubisHost Host
<PageTitle>Primo accesso · Anubis</PageTitle>
<h1>Benvenuto in Anubis</h1>
<p>Prima di cominciare, due cose.</p>
<section class="service-section">
<h2><Icon Name="database" Size="18" />Database</h2>
<p>Scelto nella configurazione del container: qui si vede soltanto. Per cambiarlo si modifica il container (manuale, capitolo Installazione).</p>
<dl class="facts">
<dt>Motore</dt><dd>@(Host.Config.Db?.Engine == DbEngine.Postgres ? "PostgreSQL" : "SQLite")</dd>
<dt>Dove</dt><dd>@Host.Config.Db?.Describe()</dd>
</dl>
</section>
<section class="service-section">
<h2><Icon Name="lock" Size="18" />Scegli la tua password</h2>
<p>La password iniziale del container vale solo per questo primo accesso. Scegline una nuova, di almeno @Passwords.MinimumLength caratteri.</p>
@if (Message is { } message)
{
<p class="notice notice-loss" role="alert"><Icon Name="alert" Size="16" />@message</p>
}
<form method="post" action="/azioni/primo-accesso" class="form">
<AntiforgeryToken />
<label for="attuale">Password iniziale</label>
<input id="attuale" name="attuale" type="password" autocomplete="current-password" required />
<label for="nuova">Nuova password</label>
<input id="nuova" name="nuova" type="password" autocomplete="new-password" minlength="@Passwords.MinimumLength" required />
<label for="conferma">Scrivila di nuovo</label>
<input id="conferma" name="conferma" type="password" autocomplete="new-password" minlength="@Passwords.MinimumLength" required />
<button class="btn btn-primary" type="submit">Salva e continua</button>
</form>
</section>
@code {
[SupplyParameterFromQuery(Name = "errore")]
public string? Errore { get; set; }
private string? Message => PasswordMessages.For(Errore);
}
@@ -0,0 +1,79 @@
@page "/primo-avvio"
@layout ServiceLayout
@attribute [AllowAnonymous]
@inject AnubisHost Host
<PageTitle>Primo avvio · Anubis</PageTitle>
<h1>Primo avvio</h1>
@if (!_local)
{
<p class="notice notice-attention" role="alert"><Icon Name="lock" Size="16" />La prima configurazione si fa solo dal computer su cui gira Anubis.</p>
}
else
{
<p>Due passi: dove tenere i dati e la password per entrare. Conti, capitale e Telegram si aggiungono dopo, dalle Impostazioni.</p>
@if (Message is { } message)
{
<p class="notice notice-loss" role="alert"><Icon Name="alert" Size="16" />@message</p>
}
<form method="post" action="/azioni/primo-avvio" class="form" data-wizard>
<AntiforgeryToken />
@if (!Host.Config.IsComplete)
{
<fieldset class="service-section">
<legend><span class="step">1</span>Database</legend>
<label class="choice">
<input type="radio" name="motore" value="sqlite" checked data-engine />
<span><strong>SQLite</strong> (consigliato): un file nella cartella dei dati, niente da installare.</span>
</label>
<label class="choice">
<input type="radio" name="motore" value="postgres" data-engine />
<span><strong>PostgreSQL</strong>: un server che hai già, con un database dedicato e vuoto.</span>
</label>
<div class="postgres-fields" data-postgres>
<label for="host">Indirizzo del server</label>
<input id="host" name="host" autocomplete="off" placeholder="192.168.1.10" />
<div class="row">
<div><label for="porta">Porta</label><input id="porta" name="porta" inputmode="numeric" value="5432" /></div>
<div><label for="nome">Nome del database</label><input id="nome" name="nome" value="anubis" /></div>
</div>
<div class="row">
<div><label for="utente">Utente</label><input id="utente" name="utente" value="anubis" autocomplete="off" /></div>
<div><label for="dbpassword">Password del database</label><input id="dbpassword" name="dbpassword" type="password" autocomplete="off" /></div>
</div>
<p class="hint">La password del database non va in <code>config.toml</code>: la custodisce Windows per il tuo utente.</p>
<button class="btn" type="submit" formaction="/azioni/primo-avvio/prova" data-test-connection>Prova la connessione</button>
<p class="test-result" data-test-result role="status"></p>
</div>
</fieldset>
}
<fieldset class="service-section">
<legend><span class="step">@(Host.Config.IsComplete ? "1" : "2")</span>Password</legend>
<p class="hint">Serve per entrare nell'interfaccia, anche da questo computer. Almeno @Passwords.MinimumLength caratteri.</p>
<label for="password">Password</label>
<input id="password" name="password" type="password" autocomplete="new-password" minlength="@Passwords.MinimumLength" required />
<label for="conferma">Scrivila di nuovo</label>
<input id="conferma" name="conferma" type="password" autocomplete="new-password" minlength="@Passwords.MinimumLength" required />
</fieldset>
<p class="hint">Anubis lavora solo quando il computer è acceso. Dopo un'assenza ricostruisce cosa è successo prima di riprendere.</p>
<button class="btn btn-primary" type="submit">Crea l'installazione</button>
</form>
}
@code {
private bool _local;
[CascadingParameter]
public HttpContext? HttpContext { get; set; }
[SupplyParameterFromQuery(Name = "errore")]
public string? Errore { get; set; }
protected override void OnInitialized() => _local = HttpContext is not null && CurrentUser.IsLocal(HttpContext);
private string? Message => Errore == "database"
? "Non riesco a collegarmi al database con questi dati. Controlla indirizzo, porta, nome, utente e password, poi riprova."
: PasswordMessages.For(Errore);
}
@@ -0,0 +1,30 @@
@inherits LoadedComponent
@page "/rischio"
@inject AnubisHost Host
<PageTitle>Rischio · Anubis</PageTitle>
<section class="panel">
<h2><Icon Name="shield" Size="18" />Interruttore</h2>
@if (_bot == "stopped")
{
<p class="notice notice-attention" role="status"><Icon Name="alert" Size="16" />"Ferma tutto" è acceso: il bot non apre e non gestisce operazioni finché non lo riattivi.</p>
<form method="post" action="/azioni/bot/riattiva" class="form-inline">
<AntiforgeryToken />
<input type="hidden" name="ritorno" value="/rischio" />
<button class="btn" type="submit" data-confirm="Riattivare il bot?">Riattiva il bot</button>
</form>
}
else
{
<p>"Ferma tutto", in alto, blocca il bot. Dopo averlo usato il bot si riattiva solo da qui, mai da solo e mai da Telegram.</p>
}
</section>
<Pending Title="Limiti e scenari non sono ancora attivi.">Limiti di perdita, calo dal massimo, esposizione e scenari arrivano con le strategie e il controllo del rischio.</Pending>
@code {
private string _bot = "active";
protected override async Task LoadAsync() =>
_bot = (await Host.Services!.Settings.GetAsync(SettingsStore.BotState.Key)).Value;
}
@@ -0,0 +1,117 @@
@page "/servizio"
@layout ServiceLayout
@attribute [AllowAnonymous]
@inject AnubisHost Host
@inject IClock Clock
@* The error page of SPEC 15.1: what is wrong, what to do, and the engine stays off. Never another database. *@
<PageTitle>@ServiceText.Title(_status.Mode) · Anubis</PageTitle>
@if (_refresh)
{
<HeadContent><meta http-equiv="refresh" content="5" /></HeadContent>
}
<h1>@ServiceText.Title(_status.Mode)</h1>
@switch (_status.Mode)
{
case HostMode.Starting:
<p>Controllo configurazione e database. Questa pagina si aggiorna da sola.</p>
break;
case HostMode.ConfigProblem:
<p>Il motore resta spento finché la configurazione non è completa. Non uso nessun altro database al posto di quello indicato.</p>
<table class="table problems">
<thead><tr><th scope="col">Voce</th><th scope="col">Cosa non va</th><th scope="col">Come rimediare</th></tr></thead>
<tbody>
@foreach (var problem in Host.Config.Problems)
{
<tr><td><code>@problem.Setting</code></td><td>@problem.What</td><td>@problem.Remedy</td></tr>
}
</tbody>
</table>
@if (Host.Config.Platform == PlatformKind.Docker)
{
<p class="hint">Le variabili si cambiano nella configurazione del container (su Unraid, nei campi del modello), poi si riavvia il container.</p>
}
else
{
<p class="hint">Il file è <code>@Host.Config.Data.ConfigFile</code>. Appena lo correggi riprovo da solo.</p>
}
break;
case HostMode.DatabaseUnavailable:
<p>Il motore è fermo e aspetta il database. Non apro un altro database al suo posto: riprovo da solo ogni pochi secondi e riparto appena risponde.</p>
<dl class="facts">
<dt>Database</dt><dd>@Host.Config.Db?.Describe()</dd>
<dt>Risposta</dt><dd>@(_status.Detail ?? "nessuna")</dd>
<dt>Tentativi</dt><dd>@_status.Attempts, dal @Format.ShortDate(_status.Since, Clock.UtcNow, Host.Config.TimeZone)</dd>
</dl>
<h2>Cosa controllare</h2>
<ul class="steps">
@if (Host.Config.Db?.Engine == DbEngine.Postgres)
{
<li>Che il server PostgreSQL sia acceso e raggiungibile da qui (indirizzo e porta).</li>
<li>Che nome del database, utente e password siano quelli giusti.</li>
<li>Che il database esista: lo crei tu una volta, Anubis non crea e non cancella database.</li>
}
else
{
<li>Che il file del database sia al suo posto e leggibile. Se l'hai spostato, rimettilo dov'era.</li>
<li>Che il disco della cartella dei dati sia collegato e abbia spazio libero.</li>
}
</ul>
break;
case HostMode.SchemaProblem:
<p>@_status.Detail</p>
<p>Per non rovinare i dati il motore resta spento. Aggiorna Anubis alla versione che ha creato questo database, oppure ripristina un salvataggio in un database vuoto.</p>
break;
case HostMode.IdentityProblem:
<IdentityChoices Status="_status" Local="_local" />
break;
case HostMode.FirstRun:
<p><a href="/primo-avvio">Apri la procedura di primo avvio</a>.</p>
break;
}
@if (Errore is { } errore)
{
<p class="notice notice-loss" role="alert"><Icon Name="alert" Size="16" />@(errore switch
{
"password" => "Password della configurazione d'avvio sbagliata, oppure scelta fatta da un altro computer.",
"importazione" => "Il ripristino non è riuscito e non ho cambiato nulla. Controlla l'archivio e riprova.",
"attesa" => "Troppi tentativi sbagliati. Riprova tra 15 minuti.",
_ => "Questa scelta non è disponibile adesso.",
})</p>
}
@code {
private HostStatus _status = null!;
private bool _refresh;
private bool _local;
[CascadingParameter]
public HttpContext? HttpContext { get; set; }
[SupplyParameterFromQuery(Name = "errore")]
public string? Errore { get; set; }
protected override void OnInitialized()
{
_status = Host.Status;
_refresh = _status.Mode is HostMode.Starting or HostMode.DatabaseUnavailable or HostMode.ConfigProblem;
if (HttpContext is not null)
{
_local = CurrentUser.IsLocal(HttpContext);
if (!HttpContext.Response.HasStarted)
{
HttpContext.Response.StatusCode = StatusCodes.Status503ServiceUnavailable;
HttpContext.Response.Headers.CacheControl = "no-store";
HttpContext.Response.Headers.RetryAfter = "5";
}
}
}
}
@@ -0,0 +1,5 @@
@page "/strategie"
<PageTitle>Strategie · Anubis</PageTitle>
<Pending Title="Le strategie non sono ancora attive.">Arrivano dopo il laboratorio: ognuna con la sua descrizione, i requisiti per passare allo stadio successivo e i risultati.</Pending>
@@ -0,0 +1,13 @@
@* A screen whose content arrives with a later phase: it says so plainly instead of showing invented numbers (SPEC 13.1). *@
<section class="panel empty">
<p class="empty-title">@Title</p>
<p>@ChildContent</p>
</section>
@code {
[Parameter, EditorRequired]
public string Title { get; set; } = "";
[Parameter]
public RenderFragment? ChildContent { get; set; }
}
@@ -0,0 +1,5 @@
<Router AppAssembly="typeof(App).Assembly">
<Found Context="routeData">
<RouteView RouteData="routeData" DefaultLayout="typeof(MainLayout)" />
</Found>
</Router>
@@ -0,0 +1,30 @@
namespace Anubis.Server;
/// <summary>Titles of the service page, also used in plain answers while the application is not ready.</summary>
internal static class ServiceText
{
public static string Title(HostMode mode) => mode switch
{
HostMode.Starting => "Anubis si sta avviando",
HostMode.ConfigProblem => "Manca qualcosa nella configurazione d'avvio",
HostMode.FirstRun => "Anubis va configurato",
HostMode.DatabaseUnavailable => "Il database non risponde",
HostMode.SchemaProblem => "Il database non è compatibile con questa versione",
HostMode.IdentityProblem => "Il database non è quello di questa installazione",
_ => "Anubis",
};
}
/// <summary>Messages of the password forms.</summary>
internal static class PasswordMessages
{
public static string? For(string? code) => code switch
{
"diverse" => "Le due password non coincidono. Scrivile di nuovo.",
"corta" => $"La password è troppo corta: servono almeno {Access.Passwords.MinimumLength} caratteri.",
"uguale" => "La nuova password deve essere diversa da quella iniziale.",
"attuale" => "La password attuale non è giusta.",
"demo" => "Nella modalità dimostrativa la password non si cambia.",
_ => null,
};
}
@@ -0,0 +1,14 @@
@using System.Globalization
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using Anubis
@using Anubis.Access
@using Anubis.Core
@using Anubis.Db
@using Anubis.Platform
@using Anubis.Server
@using Anubis.Server.Components
@using Anubis.Server.Components.Layout