using Mimante.Bidoo;
using Mimante.Data;
using Mimante.Engine;
using Mimante.Ml;
using Mimante.Products;
using Mimante.Settings;
using Mimante.Strategy;
using Xunit;
namespace Mimante.Tests;
/// Il registratore delle aste su PostgreSQL (AuctionRecorderTests del legacy, rifatti).
[Collection("Database")]
public class RecorderTests
{
private readonly DatabaseFixture _fx;
public RecorderTests(DatabaseFixture fx) => _fx = fx;
private static BidHistoryEntry Bid(int cents, string user, long unix, string type, bool mine = false) =>
new() { Price = cents / 100m, Username = user, Timestamp = unix, BidType = type, IsMyBid = mine };
[DbFact]
public async Task Una_storia_completa_da_risposte_esiti_e_previsione_realta()
{
await _fx.TruncateAsync();
var db = _fx.Db!;
await using var queue = new WriteQueue(db.Writer);
var recorder = new AuctionRecorder(queue, db, () => new AppSettings(), () => "io");
await recorder.InitAsync();
var a = new AuctionInfo("900") { Name = "Buono Amazon 50 €", ProductKey = "buono amazon 50", Url = "u", BuyNowPrice = 50, Shipping = 1 };
var rec = (await recorder.PrepareAsync(a))!;
// Storico: 4,10 anna, 4,11 io, 4,12 bruno (risponde a me dopo 6 s), 4,13 io (l'ultima).
rec.ForeignBid(Bid(410, "anna", 1000, "Manuale"));
rec.ForeignBid(Bid(411, "io", 1004, "Manuale", mine: true));
rec.ForeignBid(Bid(412, "bruno", 1010, "Auto"));
rec.ForeignBid(Bid(412, "bruno", 1010, "Auto")); // doppione: non si riscrive
rec.ForeignBid(Bid(413, "io", 1016, "", mine: true));
rec.ForeignBid(Bid(413, "io", 1016, "Manuale", mine: true)); // il tipo arriva dopo: si aggiorna
rec.Reset(1, 4.12, "bruno");
var state = new AuctionState { Price = 4.10, Timer = 1.2 };
var d1 = recorder.RecordDecision(a, state, new DecisionRecord("punta", "BID", 0.02, 0.03, 1, 0.02, 0.1, 0.13, 50, "punto", "g5|r0", "logit", "v", "BID", 500, false,
new DecisionState { Ctx = new BidContext(9, 0.5, 2, 0.08, 12, DayOfWeek.Monday, 11, false, 0, 410, false, "buono amazon 50"), Price = 4.10 }));
rec.MyBid(4.10, 500, 480, 0.3, 60, 70, true, null, 1, 1406, 926, 480, d1, 0.02, "punta", manual: false);
var d2 = recorder.RecordDecision(a, new AuctionState { Price = 4.12 }, new DecisionRecord("punta", "BID", 0.03, null, 1, 0.03, 0.2, 0.13, 50, "punto", "g5|r0", "logit", "v", "BID", 500, false, new DecisionState()));
rec.MyBid(4.12, 500, 490, 0.2, 60, 70, true, null, 2, 1405, 925, 480, d2, 0.03, "punta", manual: false);
recorder.RecordDecision(a, new AuctionState { Price = 4.12 }, new DecisionRecord("ev-negativo", "NO-OP", 0.001, null, 1, 0.001, -0.1, 0.13, 50, "no", "k", "logit", "v", "NO-OP", 500, true, new DecisionState()));
recorder.RecordForecast(a, new ForecastResult(4.50, 3.00, 6.00, 40, 5, 0.1, 1, 0.5, "prova", 20, DateTime.UtcNow, 4.10), initial: true);
recorder.Close(a, new CloseSummary(DateTime.UtcNow, "vinta", "EndedWon", true, "io", 4.13, 50, 1, null, 0.13, 1, 2, 0.26,
3, 1, 1, 3, 4, 0.5, true, true, 12, DateTime.UtcNow.AddMinutes(-12), DateTime.UtcNow.AddMinutes(-12), 60, 80, 120, 500, 0,
500, false, 0, 2, 0, 0.3, "[]", "{}", "attiva", null));
Assert.True(await queue.FlushAsync(TimeSpan.FromSeconds(20)));
Assert.Equal(0, queue.Failed);
Assert.Equal(4L, await db.ScalarAsync("SELECT COUNT(*) FROM bids WHERE auction_id = '900'"));
Assert.Equal("Manuale", await db.ScalarAsync("SELECT bid_type FROM bids WHERE auction_id = '900' AND price_after = 4.13"));
Assert.Equal(1L, await db.ScalarAsync("SELECT COUNT(*) FROM resets WHERE auction_id = '900'"));
// La mia a 4,10 (prezzo dopo 4,11) è stata coperta da bruno a 4,12 dopo 6 s; quella a 4,12 è rimasta l'ultima.
var first = await db.QueryOneAsync("SELECT answered_by, answered_type, answered_after_s, unanswered FROM my_bids WHERE auction_id = '900' AND price = 4.10",
r => new { By = r.StrOrNull("answered_by"), Type = r.StrOrNull("answered_type"), After = r.DblOrNull("answered_after_s"), U = r.BoolOrNull("unanswered") });
Assert.Equal("bruno", first!.By);
Assert.Equal("Auto", first.Type);
Assert.Equal(6, first.After);
Assert.False(first.U);
Assert.True(await db.ScalarAsync("SELECT unanswered FROM my_bids WHERE auction_id = '900' AND price = 4.12"));
Assert.Equal("answered", await db.ScalarAsync("SELECT outcome FROM bot_decisions WHERE decision_id = $1", d1));
Assert.Equal("won", await db.ScalarAsync("SELECT outcome FROM bot_decisions WHERE decision_id = $1", d2));
Assert.Equal(1L, await db.ScalarAsync("SELECT COUNT(*) FROM bot_decisions WHERE auction_id = '900' AND shadow AND outcome = 'right_skip'"));
Assert.True(await db.ScalarAsync("SELECT bool_and(has_my_bid) FROM bot_decisions WHERE auction_id = '900'"));
var f = await db.QueryOneAsync("SELECT actual_close, error_close, in_interval FROM auction_forecasts WHERE auction_id = '900'",
r => new { Actual = r.Dbl("actual_close"), Err = r.Dbl("error_close"), In = r.Bool("in_interval") });
Assert.Equal(4.13, f!.Actual, 6);
Assert.Equal(4.13 - 4.50, f.Err, 6);
Assert.True(f.In);
Assert.Equal("vinta", await db.ScalarAsync("SELECT outcome FROM auctions WHERE auction_id = '900'"));
Assert.Equal(1, await db.ScalarAsync("SELECT win_count FROM bidders WHERE username = 'io'"));
Assert.Equal(2, await db.ScalarAsync("SELECT n_bids FROM bidders WHERE username = 'io'"));
}
[DbFact]
public async Task Le_decisioni_ripetute_sono_una_riga_e_le_puntate_hanno_i_loro_tempi()
{
await _fx.TruncateAsync();
var db = _fx.Db!;
await using var queue = new WriteQueue(db.Writer);
var recorder = new AuctionRecorder(queue, db, () => new AppSettings(), () => "io");
await recorder.InitAsync();
var a = new AuctionInfo("901") { Name = "Buono Amazon 50 €", ProductKey = "buono amazon 50", Url = "u", BuyNowPrice = 50, Shipping = 1 };
var rec = (await recorder.PrepareAsync(a))!;
var t0 = new DateTime(2026, 11, 24, 10, 0, 0, DateTimeKind.Utc);
// Una puntata vera, con i suoi tempi rispetto alla scadenza.
var bid = recorder.RecordDecision(a, new AuctionState { Price = 0.50 }, new DecisionRecord("punta", "BID", 0.02, null, 1, 0.02, 0.1, 0.13, 50, "punto",
"g5|r0", "logit", "v", "BID", 500, false, new DecisionState(), AtUtc: t0));
rec.MyBid(0.50, 500, 480, 0.3, 60, 70, true, null, 1, 1406, 926, 480, bid, 0.02, "punta", manual: false,
timing: new BidTiming(520.4, 481.2, 412.9, 200, "ok|0.51", 12, 3.5));
// Una puntata decisa e non partita.
var notFired = recorder.RecordDecision(a, new AuctionState { Price = 0.60 }, new DecisionRecord("punta", "BID", 0.02, null, 1, 0.02, 0.1, 0.13, 50, "punto",
"g5|r0", "logit", "v", "BID", 500, false, new DecisionState(), AtUtc: t0.AddSeconds(5)));
recorder.NoteNotFired(notFired, "eravamo già in testa");
// 200 cicli fermati dallo stesso paletto, senza parere: una riga sola, fino all'ultimo prezzo.
var ids = new HashSet();
for (var i = 0; i < 200; i++)
ids.Add(recorder.RecordDecision(a, new AuctionState { Price = 1.00 + i / 100.0 }, new DecisionRecord("puntate-residue", "NO-OP", null, null, null, null,
null, 0.13, 50, "puntate residue sotto la soglia", null, null, null, null, 500, false, new DecisionState(), AtUtc: t0.AddSeconds(10 + i))));
Assert.Single(ids);
recorder.Close(a, new CloseSummary(DateTime.UtcNow, "persa", "EndedLost", false, "anna", 2.99, 50, 1, null, 0.13, 1, 1, 0.13,
3, 1, 0, 3, 4, 0.5, true, true, 12, DateTime.UtcNow.AddMinutes(-12), DateTime.UtcNow.AddMinutes(-12), 60, 80, 120, 500, 0,
500, false, 0, 1, 0, 0.3, "[]", "{}", "attiva", null));
Assert.True(await queue.FlushAsync(TimeSpan.FromSeconds(20)));
Assert.Equal(0, queue.Failed);
Assert.Equal(3L, await db.ScalarAsync("SELECT COUNT(*) FROM bot_decisions WHERE auction_id = '901'"));
var run = await db.QueryOneAsync("SELECT repeat_count, price, last_price, ts, last_ts, outcome FROM bot_decisions WHERE decision_id = $1",
r => new { N = r.Int("repeat_count"), Price = r.Dbl("price"), Last = r.Dbl("last_price"), Ts = r.Date("ts"), LastTs = r.Date("last_ts"), Outcome = r.Str("outcome") },
ids.Single());
Assert.Equal(200, run!.N);
Assert.Equal(1.00, run.Price, 6);
Assert.Equal(2.99, run.Last, 6);
Assert.Equal(t0.AddSeconds(10), run.Ts);
Assert.Equal(t0.AddSeconds(209), run.LastTs);
// L'esito guarda l'ultimo prezzo della serie: a 2,99 il paletto ha fermato una puntata che avrebbe chiuso l'asta.
Assert.Equal("missed", run.Outcome);
Assert.Equal("eravamo già in testa", await db.ScalarAsync("SELECT fire_note FROM bot_decisions WHERE decision_id = $1", notFired));
var counts = await db.QueryOneAsync("SELECT decisions, decisions_bid, decisions_model_bid FROM auctions WHERE auction_id = '901'",
r => new { N = r.Int("decisions"), B = r.Int("decisions_bid"), M = r.Int("decisions_model_bid") });
Assert.Equal(202, counts!.N);
Assert.Equal(2, counts.B);
Assert.Equal(2, counts.M);
var timing = await db.QueryOneAsync("SELECT verdict_remaining_ms, sent_remaining_ms, answer_remaining_ms, http_status, response, clock_samples, clock_spread_ms " +
"FROM my_bids WHERE auction_id = '901'",
r => new { V = r.DblOrNull("verdict_remaining_ms"), S = r.DblOrNull("sent_remaining_ms"), A = r.DblOrNull("answer_remaining_ms"),
H = r.IntOrNull("http_status"), R = r.StrOrNull("response"), C = r.IntOrNull("clock_samples"), D = r.DblOrNull("clock_spread_ms") });
Assert.Equal(520.4, timing!.V!.Value, 1);
Assert.Equal(481.2, timing.S!.Value, 1);
Assert.Equal(412.9, timing.A!.Value, 1);
Assert.Equal(200, timing.H);
Assert.Equal("ok|0.51", timing.R);
Assert.Equal(12, timing.C);
Assert.Equal(3.5, timing.D!.Value, 1);
}
[DbFact]
public async Task Riaprendo_un_asta_gia_seguita_non_si_duplicano_le_puntate()
{
await _fx.TruncateAsync();
var db = _fx.Db!;
await using var queue = new WriteQueue(db.Writer);
var a = new AuctionInfo("901") { Name = "X", ProductKey = "x" };
var first = new AuctionRecorder(queue, db, () => new AppSettings(), () => null);
(await first.PrepareAsync(a))!.ForeignBid(Bid(101, "anna", 1000, "Auto"));
await queue.FlushAsync(TimeSpan.FromSeconds(20));
var restarted = new AuctionRecorder(queue, db, () => new AppSettings(), () => null);
var rec = (await restarted.PrepareAsync(a))!;
rec.ForeignBid(Bid(101, "anna", 1000, "Auto"));
rec.ForeignBid(Bid(102, "bruno", 1005, "Auto"));
await queue.FlushAsync(TimeSpan.FromSeconds(20));
Assert.Equal(2L, await db.ScalarAsync("SELECT COUNT(*) FROM bids WHERE auction_id = '901'"));
}
[DbFact]
public async Task Senza_registrazione_non_si_scrive_nulla()
{
await _fx.TruncateAsync();
var off = new AuctionRecorder(null, null, () => new AppSettings(), () => null);
Assert.Null(await off.PrepareAsync(new AuctionInfo("902")));
Assert.False(off.Enabled);
}
[DbFact]
public async Task Il_rischio_rilegge_la_contabilita_del_giorno()
{
await _fx.TruncateAsync();
var db = _fx.Db!;
await using var queue = new WriteQueue(db.Writer);
var docs = new MemoryDocumentStore();
var risk = new RiskManager(docs, new DbRiskLedger(queue));
risk.NoteBidSpent("a", 0.20);
risk.NoteBidSpent("a", 0.20);
risk.NoteWin("a", 1.50, "vinta");
await queue.FlushAsync(TimeSpan.FromSeconds(20));
var reloaded = new RiskManager(docs, new DbRiskLedger(queue));
await reloaded.LoadAsync(db);
var n = reloaded.Snapshot();
Assert.Equal(0.40, n.TodaySpent, 2);
Assert.Equal(1.50, n.TodayGained, 2);
Assert.Equal(1.10, n.Cumulative, 2);
Assert.Equal(1.10, n.Peak, 2);
}
[DbFact]
public async Task Prodotti_e_statistiche_si_salvano_e_si_ricalcolano()
{
await _fx.TruncateAsync();
var db = _fx.Db!;
await using var queue = new WriteQueue(db.Writer);
var store = new ProductStore(queue);
store.Upsert(new ProductRecord { ProductKey = "buono", DisplayName = "Buono", MarketValue = 45, Followed = true, MaxPrice = 6.5 });
store.MarkProposed("buono", "777");
await queue.FlushAsync(TimeSpan.FromSeconds(20));
var again = new ProductStore(queue);
await again.LoadAsync(db);
Assert.Equal(45, again.Find("buono")!.MarketValue);
Assert.True(again.IsHandled("777"));
Assert.Equal(45.0, await db.ScalarAsync("SELECT market_price_est FROM items WHERE product_key = 'buono'"));
for (var i = 0; i < 6; i++)
await db.ExecuteAsync("INSERT INTO auctions(auction_id, product_key, name, outcome, final_price, end_time, winner_bids_paid, winner_bids_free, won_by_me, my_bids, my_bids_cost, buy_now_price) " +
"VALUES($1, 'buono', 'Buono', 'persa', $2, now(), 5, 20, $3, $4, $5, 50)", $"s{i}", 3.0 + i, i == 0, i == 0 ? 10 : 0, i == 0 ? 1.3 : 0);
var stats = (await ProductStatsRepository.RefreshAsync(db, queue, "buono", 1.0))!;
Assert.Equal(6, stats.Auctions);
Assert.Equal(1, stats.Won);
Assert.Equal(5.5, stats.AvgFinal, 6);
Assert.Equal(25, stats.AvgWinnerBids);
Assert.Equal(3.0 + 1.3 + 1.0, stats.AvgRealCostWon!.Value, 6);
await queue.FlushAsync(TimeSpan.FromSeconds(20));
Assert.True((await ProductStatsRepository.LoadAllAsync(db)).ContainsKey("buono"));
}
}