Write the manuals and fix what following them found

The manual, the runbook and the go-live list are written and checked claim by
claim against the code, and the installation is done from zero by following
them on both engines. That found real defects, now fixed:

- with SQLite a missing database file left no way to restore a backup: the
  choices appear, and the file is created only by the user's choice;
- an account whose difference vanished after the 15 minutes stayed prudent
  with no button, a missing stop could be left out for good, and a choice
  made while the broker was silent used old numbers;
- after "Ferma tutto" the positions could not be closed without restarting;
- a refused key looked like a silent broker: it has its own notice now;
- the split of the capital between the strategies of a broker (SPEC 13.5)
  could not be changed from the interface.

refs #72 #68

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-12-01 21:38:33 +01:00
1 parent 2257c3e16c
commit 24e20584d4
28 files changed
+1147 -57

No files matched your search

+19 -1
View File
@@ -128,6 +128,16 @@ internal sealed partial class AnubisHost(
/// <summary>The database even when not ready (error-page choices need it to restore or import).</summary>
internal Database? Database => _db;
/// <summary>SQLite, and the file of an installation that exists is not in its place.</summary>
internal bool SqliteFileMissing =>
Config.Db is { Engine: DbEngine.Sqlite, SqlitePath: { } path } && !File.Exists(path) && File.Exists(Config.Data.InstallationFile);
/// <summary>
/// For an error-page choice that writes into a missing SQLite file: the only place where a known installation gets a
/// new one. Called while the choice holds <see cref="ExclusiveAsync"/>.
/// </summary>
internal Database OpenForChoice() => _db ??= Database.Open(Config.Db!, allowCreate: SqliteFileMissing);
/// <summary>Holds the loop still while an error-page choice works on the database.</summary>
internal async Task<IDisposable> ExclusiveAsync(CancellationToken cancellationToken)
{
@@ -250,7 +260,6 @@ internal sealed partial class AnubisHost(
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
SetStatus(HostMode.DatabaseUnavailable, Redactor.Redact(ex.Message));
if (Config.Db!.Engine == DbEngine.Sqlite)
{
// Reopen next time: the file may come back, or the folder may be released.
@@ -258,6 +267,15 @@ internal sealed partial class AnubisHost(
_db = null;
}
if (SqliteFileMissing)
{
// SPEC 15.1: without the file the user may restore, import or start over, as with an empty database. The
// file is created only by that choice, and a file that comes back meanwhile is used without one.
SetStatus(HostMode.IdentityProblem, Redactor.Redact(ex.Message), new IdentityCheck(IdentityVerdict.EmptyDatabase, Installation.ReadFile(Config.Data), null));
return;
}
SetStatus(HostMode.DatabaseUnavailable, Redactor.Redact(ex.Message));
return;
}
@@ -12,6 +12,9 @@
@switch (verdict)
{
case IdentityVerdict.EmptyDatabase when Host.SqliteFileMissing:
<p>Il file del database non c'è, ma la cartella dei dati appartiene a un'installazione che esiste già. Il motore resta spento e non ne creo un altro da solo. Se l'hai spostato, o il disco era scollegato, rimettilo al suo posto: riparto da solo.</p>
break;
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;
+24 -3
View File
@@ -79,7 +79,7 @@ else
<section class="panel account" aria-label="@a.Name">
<div class="account-head">
<h2>@a.Name <span class="tag">@a.Kind</span></h2>
<span class="link-state @(state.LastOutcome == ReconcileOutcomes.Unreachable ? "down" : null)"><span class="dot"></span>@Connection(a)</span>
<span class="link-state @(ReconcileOutcomes.IsDown(state.LastOutcome) ? "down" : null)"><span class="dot"></span>@Connection(a)</span>
</div>
<div class="account-value">
<span class="account-equity">@Shell.Money(a.Eur(a.Equity), c)</span>
@@ -119,7 +119,16 @@ else
<li>@d.Message</li>
}
</ul>
@if (state.WaitsForUser(Clock.UtcNow, TimeSpan.FromMinutes(15)) && !Shell.IsDemo)
@if (state.WaitsForUser(Clock.UtcNow, TimeSpan.FromMinutes(15)) && !state.HasChoices && !Shell.IsDemo)
{
<p>@(state.Differences.Count == 0
? "La differenza non c'è più, ma si è spiegata dopo i 15 minuti: il conto torna normale quando lo dici tu."
: "Manca ancora uno stop: riprovo a ogni confronto. Se nel frattempo è tornato al suo posto, ricontrolla adesso.")</p>
<div class="choices">
<form method="post" action="/azioni/conti/@a.Id/allinea"><AntiforgeryToken /><button class="btn btn-small" type="submit">Ricontrolla adesso</button></form>
</div>
}
else if (state.WaitsForUser(Clock.UtcNow, TimeSpan.FromMinutes(15)) && !Shell.IsDemo)
{
<p>Sono passati 15 minuti e la differenza non si è spiegata da sola. Scegli tu:</p>
<div class="choices">
@@ -166,7 +175,11 @@ else
}
else if (state.LastOutcome is ReconcileOutcomes.Unreachable)
{
<li class="attention"><Icon Name="alert" Size="16" />Il broker non risponde: riprovo ogni 5 minuti (ultimo tentativo alle @Time(state.LastReconciledAt))</li>
<li class="attention"><Icon Name="alert" Size="16" />Il broker non risponde: riprovo ogni 5 minuti (ultimo controllo riuscito alle @Time(state.LastReconciledAt))</li>
}
else if (state.LastOutcome is ReconcileOutcomes.KeyRefused)
{
<li class="attention"><Icon Name="alert" Size="16" /><span>Il broker non accetta più la chiave: inseriscine una nuova in <a href="/impostazioni#conti">Impostazioni</a></span></li>
}
else
{
@@ -353,6 +366,9 @@ else
{
("allinea", _) => ("Fatto: il registro ha preso i numeri del conto e il conto è tornato normale.", true),
("escludi", _) => ("Fatto: la differenza resta fuori dal registro e il conto è tornato normale.", true),
("ricontrollo", _) => ("Fatto: ho ricontrollato e il conto è tornato normale.", true),
(_, "broker") => ("Il broker non risponde: non ho potuto confrontare il conto e non ho cambiato niente. Riprova tra poco.", false),
(_, "stop") => ("Il conto resta prudente: manca ancora uno stop. Riprovo a metterlo e torna normale da solo quando c'è.", false),
(_, "motore") => ("Il motore di trading non è attivo: riprova tra poco.", false),
(_, "chiave") => ("Una chiave che permette i prelievi non si allinea: va sostituita in Impostazioni.", false),
(_, "presto") => ("La scelta si fa dopo 15 minuti di modalità prudente: prima la differenza può ancora spiegarsi da sola.", false),
@@ -374,6 +390,11 @@ else
return "Il broker non risponde";
}
if (a.State.LastOutcome == ReconcileOutcomes.KeyRefused)
{
return "Chiave non accettata";
}
if (_latency?.GetValueOrDefault(a.Id) is > 0 and var ms)
{
return $"Connesso, risposta in {ms} ms";
@@ -21,6 +21,7 @@
"chiavi" => "Chiavi verificate e salvate: possono fare ordini e non possono prelevare. Il motore è ripartito e le usa.",
"chiavi-tolte" => "Chiavi tolte: quel conto torna al simulatore interno per le strategie che non hanno ancora storia sul conto di prova.",
"capitale" => "Capitale affidato aggiornato e diviso tra le strategie.",
"quote" => "Ripartizione del capitale salvata.",
"limiti" => "Limiti di rischio salvati.",
"rischio" => "Impostazione del rischio salvata.",
"telegram" => "Telegram funziona: ti ho mandato un messaggio di prova e ho salvato token e chat.",
@@ -76,7 +77,7 @@
<section class="panel" id="conti">
<h2>Conti e chiavi</h2>
<p class="hint">In questa fase uso solo denaro finto: il simulatore interno è sempre acceso e, con le chiavi dei conti di prova, le strategie passano ai conti di prova dei broker. Le chiavi di conti veri non servono e non vanno inserite.</p>
<p class="hint">Questa versione usa solo denaro finto: il simulatore interno è sempre acceso. Con le chiavi di prova di Alpaca le strategie azionarie che non hanno ancora movimenti passano al conto di prova; le crypto restano nel simulatore interno. Le chiavi di conti veri non servono e non vanno inserite.</p>
@foreach (var b in _brokers)
{
<h3>@b.Title</h3>
@@ -141,9 +142,30 @@
<AntiforgeryToken />
<label for="euro-@b.Broker">Nuovo importo in euro</label>
<input id="euro-@b.Broker" name="euro" inputmode="decimal" autocomplete="off" value="@(b.Entrusted is { } cur ? Format.Quantity(cur.AmountEur) : "")" required />
@if (b.Live)
{
<RaiseFields />
}
<button class="btn btn-small" type="submit">Salva</button>
</form>
<p class="hint">Si divide tra le strategie del conto secondo le quote@(b.Broker == Venues.Alpaca ? ", in dollari al cambio BCE del giorno" : ""). Ridurlo non vende nulla: se una strategia ha investito più di quanto le resterebbe, aspetto che venda.</p>
@if (b.Strategies.Count > 1)
{
<h4>Ripartizione tra le strategie di @b.Short</h4>
<form method="post" action="/azioni/quote/@b.Broker" class="form-grid">
<AntiforgeryToken />
@foreach (var s in b.Strategies)
{
<label>@StrategyNames.Label(s.Strategy, withMarket: true) (%)<input name="quota-@s.Strategy" inputmode="decimal" autocomplete="off" value="@Format.Quantity(s.Share * 100m)" required /></label>
}
@if (b.Live)
{
<RaiseFields />
}
<button class="btn btn-small" type="submit">Salva la ripartizione</button>
</form>
<p class="hint">Insieme devono fare 100. La quota cambia la dimensione delle prossime operazioni: non vende quello che è già comprato. I parametri delle strategie invece non si toccano da qui: sono quelli provati nel test, e un cambio passa da una nuova prova in Laboratorio.</p>
}
}
}
</section>
@@ -170,7 +192,7 @@
<h3>Protezione day trade</h3>
<form method="post" action="/azioni/rischio/@Anubis.Risk.RiskSettings.PdtGuard.Key" class="form-inline">
<AntiforgeryToken />
<label for="pdt">Per un conto Alpaca sotto i 25.000 $: al massimo 3 operazioni aperte e chiuse in giornata ogni 5 sedute.</label>
<label for="pdt">Se Alpaca applica ancora al tuo conto la regola sulle operazioni in giornata (PDT): al massimo 3 operazioni aperte e chiuse in giornata ogni 5 sedute.</label>
<select id="pdt" name="valore" data-autosubmit>
<option value="off" selected="@(_pdt == "off")">Spenta</option>
<option value="on" selected="@(_pdt == "on")">Accesa</option>
@@ -641,7 +663,7 @@
private sealed record BrokerKey(string Name, string Label, SecretStatus Status);
private sealed record BrokerSetup(string Broker, string Title, string Short, IReadOnlyList<BrokerKey> Keys, AccountState? State, EntrustedCapital? Entrusted,
IReadOnlyList<StrategyCapital> Strategies);
IReadOnlyList<StrategyCapital> Strategies, bool Live);
private sealed record LimitField(string Key, string Label, string Value, bool ReadOnly);
private readonly List<LimitField> _limits = [];
private SettingValue _taxMethod = new(Anubis.Trading.TaxExport.MethodSetting.Key, "lifo", false, null);
@@ -717,7 +739,8 @@
_pdt = (await services.Settings.GetAsync(Anubis.Risk.RiskSettings.PdtGuard.Key, ct)).Value;
_scenarios = (await services.Settings.GetAsync(Anubis.Risk.Scenarios.Setting.Key, ct)).Value;
_anyLive = await (services.Trading?.Stages ?? new StageBook(services.Db, Clock, TradingConsent.None, (_, _, _) => Task.FromResult(false))).AnyLiveAsync(null, ct);
var stages = services.Trading?.Stages ?? new StageBook(services.Db, Clock, TradingConsent.None, (_, _, _) => Task.FromResult(false));
_anyLive = await stages.AnyLiveAsync(null, ct);
_backups = services.Backups.List();
_telegramToken = await services.Secrets.StatusAsync(Anubis.Notifications.TelegramSettings.TokenSecret, ct);
@@ -738,7 +761,7 @@
var demoAccount = await services.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT id FROM accounts WHERE broker = @b AND environment = 'demo'", r => (Guid?)r.Id("id"), ("b", broker)), ct);
var state = demoAccount is { } id ? await reconciler.StateAsync(id, ct) : null;
_brokers.Add(new BrokerSetup(broker, title, name, keys, state, await capital.EntrustedAsync(broker, ct), await capital.StrategiesAsync(broker, ct)));
_brokers.Add(new BrokerSetup(broker, title, name, keys, state, await capital.EntrustedAsync(broker, ct), await capital.StrategiesAsync(broker, ct), await stages.AnyLiveAsync(broker, ct)));
}
var user = HttpContext!.User;
_hasSecondFactor = CurrentUser.HasSecondFactor(user);
@@ -770,6 +793,7 @@
"importo" => "Scrivi un importo in euro, per esempio 4000 o 1.500,50.",
"cambio" => "Manca ancora il cambio euro/dollaro della BCE: lo scarico ogni giorno, riprova più tardi.",
"capitale" => "Una strategia ha investito più di quanto le resterebbe: potrò ridurre il capitale quando avrà venduto.",
"quote" => "Le quote vanno da 0 a 100 e insieme fanno 100: per esempio 60 e 40. Non ho cambiato nulla.",
"limite" => "Un limite non è valido: controlla che ogni valore sia un numero dentro il suo intervallo.",
"ordine-limiti" => "Il dimezzamento sul calo dal massimo deve venire prima dell'interruttore, e la perdita di un giorno non può superare quella di una settimana.",
"frase-rischio" => $"Una strategia usa soldi veri: per aggiungere rischio scrivi la frase «{StageBook.RaisePhrase}». Non ho cambiato nulla.",
@@ -149,7 +149,7 @@
<section class="panel overview-account desk-only" aria-label="@a.Name">
<div class="account-head">
<h2>@a.Name <span class="tag">@a.Kind</span></h2>
<span class="link-state @(Down(a) ? "down" : null)"><span class="dot"></span>@(Down(a) ? "Non risponde" : "Connesso")</span>
<span class="link-state @(Down(a) ? "down" : null)"><span class="dot"></span>@(KeyRefused(a) ? "Chiave non accettata" : Down(a) ? "Non risponde" : "Connesso")</span>
</div>
<div class="account-value">
<span class="account-equity">@Shell.Money(a.Eur(a.Equity), c)</span>
@@ -225,7 +225,7 @@
{
var up = a.Result >= 0;
<li>
<span><strong>@a.Name</strong><span class="sub"><span class="dot @(Down(a) ? "down" : null)"></span>@a.Kind, @(Down(a) ? "non risponde" : "connesso")</span></span>
<span><strong>@a.Name</strong><span class="sub"><span class="dot @(Down(a) ? "down" : null)"></span>@a.Kind, @(KeyRefused(a) ? "chiave non accettata" : Down(a) ? "non risponde" : "connesso")</span></span>
<span class="num"><strong>@Shell.Money(a.Eur(a.Equity), c)</strong><span class="sub @(up ? "gain" : "loss")"><Arrow Up="up" /><strong>@Shell.Money(a.Eur(a.Result), c, withSign: true)</strong></span></span>
</li>
}
@@ -446,7 +446,9 @@
return o.Positions == 1 ? $"Sorveglio una posizione, {stops}. {orders}" : $"Sorveglio {o.Positions} posizioni, {stops}. {orders}";
}
private static bool Down(AccountCard a) => a.State.LastOutcome == ReconcileOutcomes.Unreachable;
private static bool KeyRefused(AccountCard a) => a.State.LastOutcome == ReconcileOutcomes.KeyRefused;
private static bool Down(AccountCard a) => ReconcileOutcomes.IsDown(a.State.LastOutcome);
private string AccountNote(AccountCard a, IReadOnlyList<PositionRow> held)
{
@@ -81,6 +81,11 @@
<input type="hidden" name="ritorno" value="/rischio" />
<button class="btn" type="submit" disabled="@(v.StopFile || v.ProtectedRestart is { CanRestart: false })" data-confirm="@RestartText(v)">Riparti</button>
</form>
@if (v.BotState == "stopped" && !v.CloseAllPending && v.ProtectedRestart is not { CanRestart: false })
{
<p class="note">Se preferisci uscire da tutto, puoi vendere le posizioni adesso, senza ripartire.</p>
<form method="post" action="/azioni/bot/chiudi"><AntiforgeryToken /><input type="hidden" name="ritorno" value="/rischio" /><button class="btn btn-danger" type="submit" data-confirm="Vendo a mercato ogni posizione del bot, che resta fermo. Ciò che è su un mercato chiuso parte all'apertura e intanto tiene il suo stop. Non si annulla. Confermi?">Chiudi tutte le posizioni</button></form>
}
}
}
@if (v.BotState != "stopped")
@@ -151,7 +156,7 @@
<dd><span>Nessuno negli ultimi 14 giorni.</span></dd>
}
<dt>Protezione day trade (azioni)</dt>
<dd><span>@(v.PdtGuard ? "Accesa: al massimo 3 operazioni in giornata ogni 5 sedute." : "Spenta. Si accende in Impostazioni se il conto Alpaca vale meno di 25.000 $.")</span></dd>
<dd><span>@(v.PdtGuard ? "Accesa: al massimo 3 operazioni in giornata ogni 5 sedute." : "Spenta. Si accende in Impostazioni se Alpaca applica ancora al tuo conto la regola sulle operazioni in giornata.")</span></dd>
</dl>
</section>
</div>
@@ -143,7 +143,7 @@
}
else if (!v.LiveAllowed || accounts.Count == 0 || Shell.IsDemo)
{
<p class="form-inline"><button class="btn" type="button" disabled>@target</button> <span class="note">@(v.LiveAllowed ? "Serve un conto reale di " + (broker == "okx" ? "OKX" : "Alpaca") + " nelle Impostazioni." : "La configurazione d'avvio non consente i soldi veri.")</span></p>
<p class="form-inline"><button class="btn" type="button" disabled>@target</button> <span class="note">@(v.LiveAllowed ? "Manca un conto reale di " + (broker == "okx" ? "OKX" : "Alpaca") + ": questa versione non permette ancora di collegarne uno." : "La configurazione d'avvio non consente i soldi veri.")</span></p>
}
else
{
@@ -0,0 +1,5 @@
@* The fields of the procedure of SPEC 12.4, for a change that adds risk while a strategy uses real money. *@
<p class="note">Una strategia di questo conto usa soldi veri: per aggiungere rischio servono la frase e la password.</p>
<label>Scrivi: <code>@Anubis.Trading.StageBook.RaisePhrase</code><input name="frase" autocomplete="off" /></label>
<label>Password<input name="password" type="password" autocomplete="current-password" /></label>
<label>Codice a sei cifre (se attivo)<input name="codice" inputmode="numeric" autocomplete="one-time-code" /></label>
+4 -3
View File
@@ -368,9 +368,10 @@ internal static partial class Endpoints
: "Comando non ammesso nello stato attuale del bot.");
}
var restart = command is "restart" or "riattiva"
&& await Platform.Installation.ReadRowAsync(host.Services.Db, ct).ConfigureAwait(false) is { ProtectedRestart: true };
if (restart && (host.Services.Trading is not { Risk: not null, Started: true } engineOn || engineOn.AccountsToRebuild.Count > 0))
var protectedRestart = await Platform.Installation.ReadRowAsync(host.Services.Db, ct).ConfigureAwait(false) is { ProtectedRestart: true };
var restart = protectedRestart && command is "restart" or "riattiva";
if (protectedRestart && command is "restart" or "riattiva" or "close" or "chiudi"
&& (host.Services.Trading is not { Risk: not null, Started: true } engineOn || engineOn.AccountsToRebuild.Count > 0))
{
// SPEC 15.1: first the executions after the archive, then the user's confirmation.
var waiting = host.Services.Trading?.AccountsToRebuild ?? [];
+65 -9
View File
@@ -34,6 +34,7 @@ internal static partial class Forms
signed.MapPost("/chiavi/{broker}", SaveKeysAsync);
signed.MapPost("/chiavi/{broker}/togli", RemoveKeysAsync);
signed.MapPost("/capitale/{broker}", SetCapitalAsync);
signed.MapPost("/quote/{broker}", SetSharesAsync);
signed.MapPost("/telegram", SaveTelegramAsync);
signed.MapPost("/telegram/prova", TestTelegramAsync);
signed.MapPost("/telegram/togli", RemoveTelegramAsync);
@@ -361,9 +362,15 @@ internal static partial class Forms
return Results.Redirect("/conti?errore=presto");
}
await trading.Reconciler.ResolveAsync(manager, choice == "allinea" ? Anubis.Trading.ReconcileChoice.Align : Anubis.Trading.ReconcileChoice.Exclude,
var resolution = await trading.Reconciler.ResolveAsync(manager, choice == "allinea" ? Anubis.Trading.ReconcileChoice.Align : Anubis.Trading.ReconcileChoice.Exclude,
context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
return Results.Redirect("/conti?ok=" + choice);
return Results.Redirect(resolution switch
{
Anubis.Trading.ReconcileResolution.NotCompared => "/conti?errore=broker",
Anubis.Trading.ReconcileResolution.StopsMissing => "/conti?errore=stop",
_ when !state.HasChoices => "/conti?ok=ricontrollo",
_ => "/conti?ok=" + choice,
});
}
/// <summary>
@@ -590,6 +597,54 @@ internal static partial class Forms
return Results.Redirect(back + "?ok=capitale#conti");
}
/// <summary>How the capital of a broker is split between its strategies, in percent (SPEC 13.5): only the user changes it.</summary>
private static async Task<IResult> SetSharesAsync(string broker, IFormCollection form, AnubisHost host, IClock clock, HttpContext context, CancellationToken ct)
{
const string back = "/impostazioni";
if (broker is not (Anubis.Data.Venues.Okx or Anubis.Data.Venues.Alpaca))
{
return Results.Redirect(back + "?errore=conto#conti");
}
if (host.IsDemo || host.Services?.Trading is not { } trading)
{
return Results.Redirect(back + "?errore=motore#conti");
}
var shares = new Dictionary<string, decimal>(StringComparer.Ordinal);
foreach (var strategy in await trading.Capital.StrategiesAsync(broker, ct).ConfigureAwait(false))
{
if (ParseEuro(form["quota-" + strategy.Strategy].ToString().Replace("%", "", StringComparison.Ordinal)) is not { } percent)
{
return Results.Redirect(back + "?errore=quote#conti");
}
shares[strategy.Strategy] = percent / 100m;
}
if (shares.Count == 0 || shares.Values.Any(s => s is < 0m or > 1m) || shares.Values.Sum() != 1m)
{
return Results.Redirect(back + "?errore=quote#conti");
}
// Moving capital between strategies gives some of them more: with real money on this broker it is more risk (SPEC 12.4).
if (await RaiseRefusalAsync(host.Services!, clock, broker, form, ct).ConfigureAwait(false) is { } refusal)
{
return Results.Redirect(back + "?errore=" + refusal + "#conti");
}
try
{
await trading.SetSharesAsync(broker, shares, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
}
catch (Anubis.Trading.CapitalException)
{
return Results.Redirect(back + "?errore=capitale#conti");
}
return Results.Redirect(back + "?ok=quote#conti");
}
/// <summary>
/// The user's choices on the Strategie screen (SPEC 12.3, 12.4): observation and simulation from a button, real
/// money only through the procedure, with the phrase, the password and the second factor checked by the stage book.
@@ -1097,7 +1152,6 @@ internal static partial class Forms
// The startup loop stays still until the choice is done and the installation renewed.
using var exclusive = await host.ExclusiveAsync(ct).ConfigureAwait(false);
var status = host.Status;
var db = host.Database;
if (choice == "riprova" && status.Mode == HostMode.SchemaProblem)
{
host.MigrationFailed = null;
@@ -1106,8 +1160,10 @@ internal static partial class Forms
return Results.Redirect("/");
}
if (status.Mode != HostMode.IdentityProblem || status.Identity is null || db is null)
// Without a database the choices stand only while the SQLite file is missing: one that came back is used as it is.
if (status.Mode != HostMode.IdentityProblem || status.Identity is null || (host.Database is null && !host.SqliteFileMissing))
{
host.Wake();
return Results.Redirect("/");
}
@@ -1123,8 +1179,8 @@ internal static partial class Forms
return Results.Redirect("/?errore=scelta");
}
await Archive.ImportAsync(db, Path.Combine(backup.Folder, Backups.ArchiveFolder), clock, ct).ConfigureAwait(false);
await Installation.RenewAsync(db, config.Data, clock, "Salvataggio ripristinato", ct).ConfigureAwait(false);
await Archive.ImportAsync(host.OpenForChoice(), Path.Combine(backup.Folder, Backups.ArchiveFolder), clock, ct).ConfigureAwait(false);
await Installation.RenewAsync(host.OpenForChoice(), config.Data, clock, "Salvataggio ripristinato", ct).ConfigureAwait(false);
break;
case "importa" when verdict == IdentityVerdict.EmptyDatabase:
var folder = ServiceChoices.ImportFolders(config.Data).FirstOrDefault(f => Path.GetFileName(f) == form["archivio"].ToString());
@@ -1133,8 +1189,8 @@ internal static partial class Forms
return Results.Redirect("/?errore=scelta");
}
await Archive.ImportAsync(db, folder, clock, ct).ConfigureAwait(false);
await Installation.RenewAsync(db, config.Data, clock, "Archivio importato", ct).ConfigureAwait(false);
await Archive.ImportAsync(host.OpenForChoice(), folder, clock, ct).ConfigureAwait(false);
await Installation.RenewAsync(host.OpenForChoice(), config.Data, clock, "Archivio importato", ct).ConfigureAwait(false);
break;
case "da-capo" when verdict == IdentityVerdict.EmptyDatabase:
Installation.StartOver(config.Data, clock);
@@ -1142,7 +1198,7 @@ internal static partial class Forms
case "usa-questo" when verdict is IdentityVerdict.DifferentInstallation or IdentityVerdict.StaleDatabase or IdentityVerdict.MissingFile:
// An old copy may have an old schema: it is brought up to date, after its own backup, before it is protected.
await host.MigrateAsync(new Backups(config.Data, clock), ct).ConfigureAwait(false);
await Installation.RenewAsync(db, config.Data, clock, "Database scelto dalla pagina d'errore", ct).ConfigureAwait(false);
await Installation.RenewAsync(host.OpenForChoice(), config.Data, clock, "Database scelto dalla pagina d'errore", ct).ConfigureAwait(false);
break;
default:
return Results.Redirect("/?errore=scelta");
+1 -1
View File
@@ -27,7 +27,7 @@ internal sealed record ProtectedRestartView(DateTimeOffset Since, bool Working,
var rebuilt = await services.Db.ReadAsync(s => s.QueryAsync("SELECT message FROM journal WHERE code = 'ledger_rebuilt' AND occurred_at >= @f ORDER BY occurred_at, id",
r => r.Text("message"), ("f", row.RenewedAt)), cancellationToken).ConfigureAwait(false);
var stages = services.Trading is { } trading ? await trading.Stages.AllAsync(cancellationToken).ConfigureAwait(false) : [];
return new ProtectedRestartView(row.RenewedAt, services.Trading is { Started: false }, services.Trading?.AccountsToRebuild ?? [], rebuilt,
return new ProtectedRestartView(row.RenewedAt, services.Trading is not { Started: true }, services.Trading?.AccountsToRebuild ?? [], rebuilt,
[.. stages.Where(s => s.WaitsForReconfirmation).Select(s => StrategyNames.Label(s.Strategy, withMarket: true))]);
}
}