\s*
\s*\+?\s*(\d+)\s*.*?
\s*([^<]+?)\s*", Opt);
+ private static readonly Regex ItalianDate = new(@"(\d{1,2})\s+(" + string.Join('|', Months) + @")\s+(\d{4})(?:\s+alle)?\s+(\d{1,2}):(\d{2})", Opt);
+ private static readonly Regex ChestSource = new(@"tramite\s+(.+?)\s+il\s+\d", Opt);
+
+ private static readonly Regex CreditTable = new(@"
]*class=""[^""]*my-bidoo-table[^""]*""[^>]*>(.*?)
", Opt);
+ private static readonly Regex Row = new(@"
]*>(.*?)
", Opt);
+ private static readonly Regex MovementId = new(@"id=""data_mov(\d+)""", Opt);
+ private static readonly Regex FirstRow = new(@"
(.*?)", Opt);
+ private static readonly Regex SecondRow = new(@"
(.*?)
", Opt);
+ private static readonly Regex Total = new(@"
(.*?) | ", Opt);
+ private static readonly Regex MovementTime = new(@"'data_mov'\s*\+\s*(\d+)\s*\)\s*\)\s*\{[^}]*?formattaDataStorico\(\s*(\d+)", Opt);
+ private static readonly Regex LeadingNumber = new(@"^\s*(\d[\d.]*)", Opt);
+
+ private static readonly Regex Tags = new("<[^>]+>", Opt);
+ private static readonly Regex Spaces = new(@"\s+", Opt);
+ private static readonly Regex Href = new(@"href\s*=\s*[""']([^""']+)[""']", Opt);
+ private static readonly Regex BareUrl = new(@"https?://[^\s""'<>]+", Opt);
+
+ // ── /my_chests.php ────────────────────────────────────────────────
+
+ ///
+ /// I forzieri aperti: ogni wrap-item con il testo («Ottenuto tramite link il 9 Novembre 2026 alle 14:05»)
+ /// e il premio (pt-chest, «+3 Puntate»). Un forziere senza premio (ancora da aprire o scaduto) si salta.
+ /// Due forzieri uguali nello stesso minuto restano due: la chiave porta il numero d'ordine.
+ ///
+ public static RewardsRead ParseChests(string? html, TimeZoneInfo tz)
+ {
+ if (string.IsNullOrEmpty(html) || !html.Contains("items-sections", StringComparison.OrdinalIgnoreCase))
+ return new([], "la pagina delle ricompense non ha l'elenco dei forzieri: sessione scaduta o formato cambiato?");
+ var starts = ChestItem.Matches(html).Select(m => m.Index).ToList();
+ var items = new List
();
+ var seen = new Dictionary(StringComparer.Ordinal);
+ var skipped = 0;
+ for (var i = 0; i < starts.Count; i++)
+ {
+ var block = html[starts[i]..(i + 1 < starts.Count ? starts[i + 1] : html.Length)];
+ var points = ChestPoints.Match(block);
+ if (!points.Success) continue;
+ var text = Clean(ChestText.Match(block).Groups[1].Value);
+ var date = ItalianDate.Match(text);
+ if (!date.Success) { skipped++; continue; }
+ var local = new DateTime(int.Parse(date.Groups[3].Value, CultureInfo.InvariantCulture),
+ Array.IndexOf(Months, date.Groups[2].Value.ToLowerInvariant()) + 1, int.Parse(date.Groups[1].Value, CultureInfo.InvariantCulture),
+ int.Parse(date.Groups[4].Value, CultureInfo.InvariantCulture), int.Parse(date.Groups[5].Value, CultureInfo.InvariantCulture), 0,
+ DateTimeKind.Unspecified);
+ var amount = int.Parse(points.Groups[1].Value, CultureInfo.InvariantCulture);
+ var unit = Clean(points.Groups[2].Value);
+ var isBids = unit.StartsWith("puntat", StringComparison.OrdinalIgnoreCase);
+ var source = ChestSource.Match(text) is { Success: true } s ? Clean(s.Groups[1].Value).ToLowerInvariant() : "";
+ var baseKey = $"{KindChest}|{local:yyyy-MM-ddTHH:mm}|{source}|{amount} {unit.ToLowerInvariant()}";
+ var n = seen.GetValueOrDefault(baseKey);
+ seen[baseKey] = n + 1;
+ items.Add(new AccountReward($"{baseKey}|{n}", KindChest, ToUtc(local, tz), isBids ? amount : 0, true, source,
+ $"{text} (+{amount} {unit})"));
+ }
+ return new(items, null, skipped);
+ }
+
+ // ── /bids_history.php ─────────────────────────────────────────────
+
+ ///
+ /// La cronologia crediti: una riga per movimento (data_mov<id>), descrizione («3 Gratis»), totale
+ /// («Gratis» o un prezzo). L'ora la scrive lo script della pagina: 'data_mov' + id … formattaDataStorico(unix.
+ ///
+ public static RewardsRead ParseCreditHistory(string? html)
+ {
+ if (string.IsNullOrEmpty(html) || CreditTable.Match(html) is not { Success: true } table)
+ return new([], "la cronologia crediti non ha la tabella dei movimenti: sessione scaduta o formato cambiato?");
+ var times = new Dictionary(StringComparer.Ordinal);
+ foreach (Match m in MovementTime.Matches(html))
+ times[m.Groups[1].Value] = long.Parse(m.Groups[2].Value, CultureInfo.InvariantCulture);
+
+ var items = new List();
+ var skipped = 0;
+ foreach (Match row in Row.Matches(table.Groups[1].Value))
+ {
+ var cells = row.Groups[1].Value;
+ if (MovementId.Match(cells) is not { Success: true } id) continue; // l'intestazione
+ if (!times.TryGetValue(id.Groups[1].Value, out var unix)) { skipped++; continue; }
+ var first = Clean(FirstRow.Match(cells).Groups[1].Value);
+ var second = Clean(SecondRow.Match(cells).Groups[1].Value);
+ var total = Clean(Total.Match(cells).Groups[1].Value);
+ var bids = LeadingNumber.Match(first) is { Success: true } b
+ && int.TryParse(b.Groups[1].Value.Replace(".", ""), NumberStyles.None, CultureInfo.InvariantCulture, out var v) ? v : 0;
+ var free = total.Contains("gratis", StringComparison.OrdinalIgnoreCase);
+ var description = string.Join(" · ", new[] { first, second, total }.Where(x => x.Length > 0));
+ items.Add(new AccountReward($"{KindCredit}|{id.Groups[1].Value}", KindCredit,
+ DateTimeOffset.FromUnixTimeSeconds(unix).UtcDateTime, bids, free, "", description));
+ }
+ return new(items, null, skipped);
+ }
+
+ // ── /checkN.php ───────────────────────────────────────────────────
+
+ ///
+ /// La campanella: {"count":…, "elements": {…} | […]}, ogni notifica con id e content in HTML.
+ /// Si tengono solo gli indirizzi con promocode: poi passano dallo stesso controllo dei collegamenti della fonte.
+ ///
+ public static NotificationLinks ParseNotifications(string? json)
+ {
+ try
+ {
+ using var doc = JsonDocument.Parse(string.IsNullOrWhiteSpace(json) ? "null" : json);
+ if (doc.RootElement.ValueKind != JsonValueKind.Object || !doc.RootElement.TryGetProperty("elements", out var els))
+ return new(0, [], "risposta della campanella senza elements: sessione scaduta o formato cambiato?");
+ var list = els.ValueKind switch
+ {
+ JsonValueKind.Array => els.EnumerateArray().ToList(),
+ JsonValueKind.Object => els.EnumerateObject().Select(p => p.Value).ToList(),
+ _ => []
+ };
+ var links = new List<(string, string)>();
+ var count = 0;
+ foreach (var e in list.Where(x => x.ValueKind == JsonValueKind.Object))
+ {
+ count++;
+ var id = e.TryGetProperty("id", out var idv) ? idv.ToString() : "";
+ var content = e.TryGetProperty("content", out var c) && c.ValueKind == JsonValueKind.String ? c.GetString() ?? "" : "";
+ var found = Href.Matches(content).Select(m => m.Groups[1].Value)
+ .Concat(BareUrl.Matches(Tags.Replace(content, " ")).Select(m => m.Value))
+ .Select(h => WebUtility.HtmlDecode(h) ?? "")
+ .Where(h => h.Contains("promocode", StringComparison.OrdinalIgnoreCase))
+ .Distinct(StringComparer.Ordinal);
+ foreach (var h in found) links.Add((id, h));
+ }
+ return new(count, links, null);
+ }
+ catch (JsonException)
+ {
+ return new(0, [], "la campanella non ha risposto con JSON: sessione scaduta o formato cambiato?");
+ }
+ }
+
+ // ── confronto ─────────────────────────────────────────────────────
+
+ ///
+ /// Il confronto del giorno fra ciò che Bidoo segna come ottenuto tramite collegamento e i riscatti riusciti del bot.
+ /// Una differenza non è per forza un errore: un collegamento aperto a mano dal telefono conta per Bidoo, non per il bot.
+ ///
+ public static string CompareToday(IEnumerable rewards, DateOnly today, TimeZoneInfo tz, int redeemed, int gained)
+ {
+ var fromLinks = rewards.Where(r => r.Kind == KindChest && r.Source == "link"
+ && DateOnly.FromDateTime(TimeZoneInfo.ConvertTimeFromUtc(r.AtUtc, tz)) == today).ToList();
+ var bids = fromLinks.Sum(r => r.Bids);
+ var head = $"oggi Bidoo segna {fromLinks.Count} ricompense da collegamento (+{bids} puntate), il bot ha {redeemed} riscatti riusciti (+{gained} dal saldo)";
+ return fromLinks.Count == redeemed && bids == gained ? head + ": tornano"
+ : fromLinks.Count > redeemed ? head + ": gli altri sono collegamenti aperti fuori dal bot o accrediti non visti dal saldo"
+ : head + ": qualche riscatto del bot non compare fra le ricompense";
+ }
+
+ private static DateTime ToUtc(DateTime local, TimeZoneInfo tz)
+ {
+ try { return TimeZoneInfo.ConvertTimeToUtc(local, tz); }
+ catch (ArgumentException) { return TimeZoneInfo.ConvertTimeToUtc(local.AddHours(1), tz); } // ora che non esiste (cambio d'ora)
+ }
+
+ private static string Clean(string html) => Spaces.Replace(WebUtility.HtmlDecode(Tags.Replace(html, " ")), " ").Trim();
+}
diff --git a/src/Mimante/Bidoo/bidoo.default.json b/src/Mimante/Bidoo/bidoo.default.json
index 44f0da7..c4483d5 100644
--- a/src/Mimante/Bidoo/bidoo.default.json
+++ b/src/Mimante/Bidoo/bidoo.default.json
@@ -149,6 +149,10 @@
// Forzieri: per ogni categoria {"url": null} o {"url": "…"}. Tag 0 più le categorie della home.
"chestTag": "/ajax/chest/get_chest_tag_url.php?tag={tag}",
"chestTags": [ 0, 6, 5, 7, 13, 18, 8, 11, 40, 44, 9, 14, 41, 21, 19, 20, 22, 10, 37, 12 ],
- "rewardsPage": "/my_chests.php"
+ // Le ricompense ottenute (forzieri) e la cronologia crediti: si leggono a intervalli per il confronto con i riscatti.
+ "rewardsPage": "/my_chests.php",
+ "creditsHistoryPage": "/bids_history.php",
+ // La campanella, seconda fonte di collegamenti. Solo lettura: _d=1 e _r=1 segnerebbero le notifiche, il bot non li usa.
+ "notifications": "/checkN.php"
}
}
diff --git a/src/Mimante/Data/Archive/ArchiveTables.cs b/src/Mimante/Data/Archive/ArchiveTables.cs
index b8668e1..c92971f 100644
--- a/src/Mimante/Data/Archive/ArchiveTables.cs
+++ b/src/Mimante/Data/Archive/ArchiveTables.cs
@@ -70,6 +70,8 @@ public sealed record ArchiveTable(
new("promo_redemptions", ArchiveSplit.Whole, null, "id",
"I riscatti delle puntate gratuite: codice, fonte, esito di Bidoo, saldo prima e dopo, puntate guadagnate."),
new("chests", ArchiveSplit.Whole, null, "id", "I forzieri visti nelle categorie (solo avviso), per giorno."),
+ new("account_rewards", ArchiveSplit.Whole, null, "id",
+ "Le ricompense che Bidoo ha accreditato, lette dalle sue pagine: forzieri aperti e movimenti della cronologia crediti."),
new("schema_migrations", ArchiveSplit.Whole, null, "version", "Le migrazioni applicate all'archivio."),
new("settings", ArchiveSplit.Whole, null, "id", "Le impostazioni del bot, senza token e chat di Telegram.",
Expressions: _ => new Dictionary { ["value"] = "value - 'TelegramBotToken' - 'TelegramChatId'" }),
diff --git a/src/Mimante/Data/Migrations/0006_ricompense.sql b/src/Mimante/Data/Migrations/0006_ricompense.sql
new file mode 100644
index 0000000..15293db
--- /dev/null
+++ b/src/Mimante/Data/Migrations/0006_ricompense.sql
@@ -0,0 +1,18 @@
+-- Ricompense accreditate da Bidoo (issue #38, ADR 0015). Solo una tabella nuova.
+
+-- Serve allo storico per: ciò che Bidoo ha davvero accreditato, letto dalle sue pagine (forzieri da
+-- /my_chests.php, movimenti gratuiti da /bids_history.php), da confrontare con i riscatti tentati in
+-- promo_redemptions: dice quanto rende il riscatto e se un accredito sfugge al saldo. Una riga per
+-- ricompensa, mai riscritta (key unica: forziere con data, fonte, premio e ordine; movimento con il suo id).
+CREATE TABLE IF NOT EXISTS account_rewards (
+ id bigserial PRIMARY KEY,
+ key text NOT NULL UNIQUE,
+ kind text NOT NULL,
+ ts timestamptz NOT NULL,
+ bids int NOT NULL,
+ free boolean NOT NULL,
+ source text NOT NULL,
+ description text NOT NULL,
+ seen_at timestamptz NOT NULL DEFAULT now()
+);
+CREATE INDEX IF NOT EXISTS account_rewards_ts ON account_rewards(ts);
diff --git a/src/Mimante/Host/BotWorld.cs b/src/Mimante/Host/BotWorld.cs
index 3e443c7..fbb9a03 100644
--- a/src/Mimante/Host/BotWorld.cs
+++ b/src/Mimante/Host/BotWorld.cs
@@ -202,6 +202,7 @@ public sealed class BotWorld : IAsyncDisposable
{
_jobs.Add(FreeBids.RunAsync(ct));
_jobs.Add(FreeBids.RunChestsAsync(ct));
+ _jobs.Add(FreeBids.RunRewardsAsync(ct));
}
bot.Log.Info("AVVIO", IsSimulator
? "Modalità debug: stai vedendo il simulatore (nessuna sessione Bidoo salvata)"
diff --git a/src/Mimante/Settings/AppSettings.cs b/src/Mimante/Settings/AppSettings.cs
index 8d13f72..be22752 100644
--- a/src/Mimante/Settings/AppSettings.cs
+++ b/src/Mimante/Settings/AppSettings.cs
@@ -208,6 +208,12 @@ public sealed class AppSettings
public int FreeBidsHoursStart { get; set; } = 8;
public int FreeBidsHoursEnd { get; set; } = 24;
+ /// La campanella di Bidoo come seconda fonte di collegamenti (letta senza segnare le notifiche).
+ public bool FreeBidsUseNotifications { get; set; } = true;
+
+ /// Ore fra una lettura delle ricompense (forzieri e cronologia crediti) e l'altra; 0 = mai.
+ public int FreeBidsRewardsHours { get; set; } = 6;
+
/// Giro delle categorie per i forzieri: solo avviso, il bot non li apre.
public bool ChestWatchEnabled { get; set; }
diff --git a/src/Mimante/Settings/SettingsStore.cs b/src/Mimante/Settings/SettingsStore.cs
index 69e12f6..8968593 100644
--- a/src/Mimante/Settings/SettingsStore.cs
+++ b/src/Mimante/Settings/SettingsStore.cs
@@ -216,6 +216,7 @@ public sealed class SettingsStore
s.FreeBidsHoursStart = Math.Clamp(s.FreeBidsHoursStart, 0, 24);
s.FreeBidsHoursEnd = Math.Clamp(s.FreeBidsHoursEnd, 0, 24);
s.ChestWatchMinutes = Math.Clamp(s.ChestWatchMinutes, 5, 24 * 60);
+ s.FreeBidsRewardsHours = Math.Clamp(s.FreeBidsRewardsHours, 0, 7 * 24);
s.SuggestedCoveragePercent = Math.Clamp(s.SuggestedCoveragePercent, 50, 99);
s.SuggestedValueTolerancePercent = Math.Clamp(s.SuggestedValueTolerancePercent, 0, 100);
diff --git a/src/Mimante/Web/Api.cs b/src/Mimante/Web/Api.cs
index 34ec84b..fb79f07 100644
--- a/src/Mimante/Web/Api.cs
+++ b/src/Mimante/Web/Api.cs
@@ -358,12 +358,21 @@ public static class Api
["first"] = r.Date("first_seen"), ["last"] = r.Date("last_seen"), ["tag"] = r.Int("tag"), ["url"] = r.Str("url")
}).ConfigureAwait(false);
+ var rewards = await bot.Db.QueryAsync(
+ "SELECT ts, kind, bids, free, source, description FROM account_rewards ORDER BY ts DESC, id DESC LIMIT 300",
+ r => new Dictionary
+ {
+ ["at"] = r.Date("ts"), ["kind"] = r.Str("kind"), ["bids"] = r.Int("bids"), ["free"] = r.BoolOrNull("free") ?? false,
+ ["source"] = r.Str("source"), ["description"] = r.Str("description")
+ }).ConfigureAwait(false);
+
return new Dictionary
{
["present"] = service != null,
["counts"] = counts,
["redemptions"] = redemptions,
["chests"] = chests,
+ ["rewards"] = rewards,
["log"] = service?.Lines(500).Select(l => new Dictionary { ["at"] = l.AtUtc, ["text"] = l.Text }).ToList()
};
}
diff --git a/src/Mimante/Web/Views.cs b/src/Mimante/Web/Views.cs
index e59afd7..848fd1b 100644
--- a/src/Mimante/Web/Views.cs
+++ b/src/Mimante/Web/Views.cs
@@ -196,6 +196,8 @@ public static class Views
["chestWatch"] = s.ChestWatch,
["lastChestAt"] = s.LastChestUtc,
["chestsToday"] = s.ChestsToday,
+ ["lastRewardsAt"] = s.LastRewardsUtc,
+ ["rewardsSummary"] = s.RewardsSummary,
["log"] = service.Lines(60).Select(l => new Dictionary { ["at"] = l.AtUtc, ["text"] = l.Text }).ToList()
};
}
diff --git a/src/Mimante/wwwroot/js/pages/impostazioni.js b/src/Mimante/wwwroot/js/pages/impostazioni.js
index da49fd1..7e549c3 100644
--- a/src/Mimante/wwwroot/js/pages/impostazioni.js
+++ b/src/Mimante/wwwroot/js/pages/impostazioni.js
@@ -91,6 +91,8 @@ const sections = [
['FreeBidsPauseMaxSeconds', 'Pausa fra riscatti: a s', I, 'Non meno della pausa minima'],
['FreeBidsHoursStart', 'Riscatta dalle ore', I, 'Ora di Roma, compresa; uguale alla fine = sempre'],
['FreeBidsHoursEnd', 'Riscatta fino alle ore', I, 'Ora di Roma, esclusa (24 = fino a mezzanotte)'],
+ ['FreeBidsUseNotifications', 'Anche dalla campanella', B, 'Cerca collegamenti anche nelle notifiche di Bidoo; le legge senza segnarle come lette'],
+ ['FreeBidsRewardsHours', 'Ricompense: lettura ogni ore', I, 'Legge forzieri e cronologia crediti di Bidoo e li confronta con i riscatti; 0 = mai'],
['ChestWatchEnabled', 'Avviso forzieri', B, 'Il bot guarda le categorie e avvisa di un forziere: non lo apre'],
['ChestWatchMinutes', 'Forzieri: un giro ogni min', I, 'Minimo 5'],
['TelegramNotifyFreeBids', 'Messaggio su Telegram', B, 'Per ogni riscatto riuscito, per una pausa del riscatto e per un forziere trovato']
diff --git a/src/Mimante/wwwroot/js/pages/puntate-gratis.js b/src/Mimante/wwwroot/js/pages/puntate-gratis.js
index 105c1cc..23cdecc 100644
--- a/src/Mimante/wwwroot/js/pages/puntate-gratis.js
+++ b/src/Mimante/wwwroot/js/pages/puntate-gratis.js
@@ -41,6 +41,7 @@ export async function mount(host) {
ui.tabs = el('div', { class: 'tabs', role: 'tablist' },
tabButton('riscatti', 'Puntate riscattate', 'Ogni riscatto tentato, con l\'esito di Bidoo e il saldo prima e dopo'),
+ tabButton('ricompense', 'Ricompense di Bidoo', 'Quello che Bidoo ha accreditato davvero: forzieri aperti e movimenti gratuiti della cronologia crediti, letti a intervalli'),
tabButton('forzieri', 'Forzieri', 'I forzieri visti nelle categorie (solo avviso)'),
tabButton('registro', 'Registro', 'Le operazioni del riscatto e dei forzieri, una riga per evento (anche nel file riscatti-AAAA-MM-GG.log)'));
ui.body = el('div', { class: 'in', style: { maxHeight: 'none' } });
@@ -106,8 +107,9 @@ function paint(f) {
if (f.nextRunAt && f.enabled) parts.push('prossimo ' + when(f.nextRunAt));
parts.push(f.confirmed ? 'accredito confermato dal saldo' : 'un collegamento per giro finché il saldo non conferma');
if (f.chestWatch) parts.push(`forzieri: ${num(f.chestsToday)} oggi` + (f.lastChestAt ? `, ultimo giro ${when(f.lastChestAt)}` : ''));
+ if (f.lastRewardsAt) parts.push('ricompense lette ' + when(f.lastRewardsAt));
ui.status.textContent = parts.join(' · ');
- if (f.lastSummary) ui.status.title = 'Ultimo giro: ' + f.lastSummary;
+ ui.status.title = [f.lastSummary ? 'Ultimo giro: ' + f.lastSummary : '', f.rewardsSummary ? 'Ricompense: ' + f.rewardsSummary : ''].filter(Boolean).join('\n');
ui.pause.hidden = !f.paused;
ui.resume.hidden = !f.paused;
if (f.paused) ui.pause.textContent = 'In pausa: ' + (f.pauseReason || 'motivo non registrato') + '. Controlla su Bidoo, poi togli la pausa.';
@@ -150,6 +152,7 @@ function paintBody() {
if (!ui.body || !data) return;
if (tab === 'riscatti') ui.body.replaceChildren(redemptions(data.redemptions || []));
else if (tab === 'forzieri') ui.body.replaceChildren(chests(data.chests || []));
+ else if (tab === 'ricompense') ui.body.replaceChildren(rewards(data.rewards || []));
else ui.body.replaceChildren(logLines(data.log || []));
}
@@ -189,6 +192,22 @@ function chests(rows) {
el('td', null, el('a', { href: r.url, target: '_blank', rel: 'noopener noreferrer', title: 'Apri il forziere su Bidoo (nel tuo browser)' }, r.url))))));
}
+function rewards(rows) {
+ const f = state.freebids || {};
+ const head = f.rewardsSummary ? el('p', { class: 'help note', title: 'L\'ultima lettura delle pagine di Bidoo e il confronto con i riscatti del bot' }, f.rewardsSummary) : '';
+ if (!rows.length) return el('div', null, head, el('span', { class: 'help' }, 'Nessuna ricompensa letta finora: il bot legge forzieri e cronologia crediti di Bidoo a intervalli (Impostazioni ▸ Puntate gratis), con l\'utente collegato.'));
+ return el('div', null, head, el('table', { class: 'grid' },
+ el('thead', null, el('tr', null, th('Quando', 'Quando Bidoo ha accreditato la ricompensa'), th('Tipo', 'Forziere aperto o movimento della cronologia crediti'),
+ th('Ottenuto con', 'Per i forzieri: come è stato ottenuto (link, aste di puntate confermate…)'),
+ th('Puntate', 'Puntate accreditate', 'num'), th('Descrizione', 'Il testo di Bidoo'))),
+ el('tbody', null, rows.map(r => el('tr', null,
+ el('td', { title: when(r.at) }, time(r.at)),
+ el('td', null, r.kind),
+ el('td', null, r.source || ''),
+ el('td', { class: 'num ' + (r.free && r.bids > 0 ? 'ok' : '') , title: r.free ? 'Gratuite' : 'A pagamento' }, r.bids ? (r.free ? '+' : '') + num(r.bids) : ''),
+ el('td', { class: 'sub' }, r.description))))));
+}
+
function logLines(rows) {
if (!rows.length) return el('span', { class: 'help' }, 'Nessuna operazione dall\'avvio del bot. Il file riscatti-AAAA-MM-GG.log è nella pagina Registro.');
return el('div', { class: 'log', style: { fontFamily: 'var(--mono)', lineHeight: '1.55' } },
diff --git a/tests/Mimante.Tests/Fixtures/campanella.json b/tests/Mimante.Tests/Fixtures/campanella.json
new file mode 100644
index 0000000..ae450bf
--- /dev/null
+++ b/tests/Mimante.Tests/Fixtures/campanella.json
@@ -0,0 +1 @@
+{"count":3,"elements":{"0":{"id":"9000003","users":"0","type":"9","arguments":"","created_at":"1795511000","visibleFor":"0","readFlag":"0","content":"Solo per oggi: 5 puntate gratis per te!<\/p><\/a>"},"1":{"id":"9000002","users":"0","type":"6","arguments":"","created_at":"1795470000","visibleFor":"0","readFlag":"1","content":"
\n Sul tuo conto Bidoo Shop è stato accreditato l'importo di 10.00 €<\/p><\/a>"},"2":{"id":"9000001","users":"0","type":"9","arguments":"","created_at":"1795400000","visibleFor":"0","readFlag":"2","content":"
Copia questo indirizzo: https:\/\/it.bidoo.com\/index.php?promocode=altro241126&sign=89abcdef0123456789abcdef0123456789abcdef<\/p>"}},"audio":"","exceed":22,"shexc":22,"t":1795541810}
diff --git a/tests/Mimante.Tests/Fixtures/cronologia-crediti.html b/tests/Mimante.Tests/Fixtures/cronologia-crediti.html
new file mode 100644
index 0000000..edce1f2
--- /dev/null
+++ b/tests/Mimante.Tests/Fixtures/cronologia-crediti.html
@@ -0,0 +1,42 @@
+
+
+
+
My Bidoo - Cronologia Crediti - Bidoo
+
+
+ | Data | Descrizione | Prezzo | Metodo di Pagamento |
+
+
+ | |
+ |
+ Gratis |
+ Gratis |
+
+
+ | |
+ |
+ Gratis |
+ Gratis |
+
+
+ | |
+ |
+ 100,00 € |
+ Carta |
+
+
+ | |
+ 3 Gratis |
+ Gratis |
+ Gratis |
+
+
+
+
+
+
+
diff --git a/tests/Mimante.Tests/Fixtures/ricompense-forzieri.html b/tests/Mimante.Tests/Fixtures/ricompense-forzieri.html
new file mode 100644
index 0000000..9227988
--- /dev/null
+++ b/tests/Mimante.Tests/Fixtures/ricompense-forzieri.html
@@ -0,0 +1,49 @@
+
+
+
+My Bidoo - Le mie ricompense - Bidoo
+
+
+
Cronologia
+
+
+
+
+
+
Ottenuto tramite link il 24 Novembre 2026 alle 09:05
+
+5
Puntate
+
+
+
+
+
+
+
Ottenuto tramite link il 24 Novembre 2026 alle 09:05
+
+5
Puntate
+
+
+
+
+
+
Ottenuto tramite link il 23 Novembre 2026 alle 21:40
+
+2
Puntate
+
+
+
+
+
+
Ottenuto tramite aste di puntate confermate il 3 Novembre 2026 alle 18:12
+
+15
Puntate
+
+
+
+
+
+
Dal forziere del 2 Novembre 2026 10:30
+
+
+
+
+
+
+
diff --git a/tests/Mimante.Tests/RewardsPagesTests.cs b/tests/Mimante.Tests/RewardsPagesTests.cs
new file mode 100644
index 0000000..d25816b
--- /dev/null
+++ b/tests/Mimante.Tests/RewardsPagesTests.cs
@@ -0,0 +1,99 @@
+using Mimante.Bidoo;
+using Mimante.Bidoo.FreeBids;
+using Xunit;
+
+namespace Mimante.Tests;
+
+/// Ricompense, cronologia crediti e campanella di Bidoo (#38): copie della struttura vera, valori inventati.
+public class RewardsPagesTests
+{
+ private static readonly TimeZoneInfo Rome = TimeZoneInfo.FindSystemTimeZoneById("Europe/Rome");
+
+ private static string Fixture(string name) => File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "Fixtures", name));
+
+ [Fact]
+ public void I_forzieri_aperti_con_data_fonte_e_premio()
+ {
+ var read = RewardsPages.ParseChests(Fixture("ricompense-forzieri.html"), Rome);
+ Assert.Null(read.Error);
+ Assert.Equal(4, read.Items.Count); // quello senza premio non conta
+
+ var first = read.Items[0];
+ Assert.Equal(RewardsPages.KindChest, first.Kind);
+ Assert.Equal(new DateTime(2026, 11, 24, 8, 5, 0, DateTimeKind.Utc), first.AtUtc); // 09:05 a Roma
+ Assert.Equal(5, first.Bids);
+ Assert.True(first.Free);
+ Assert.Equal("link", first.Source);
+ Assert.Contains("+5 Puntate", first.Description);
+
+ // Due forzieri uguali nello stesso minuto restano due.
+ Assert.NotEqual(read.Items[0].Key, read.Items[1].Key);
+ Assert.Equal(read.Items.Count, read.Items.Select(i => i.Key).Distinct().Count());
+
+ Assert.Equal("aste di puntate confermate", read.Items[3].Source);
+ Assert.Equal(15, read.Items[3].Bids);
+ }
+
+ [Fact]
+ public void La_cronologia_crediti_prende_l_ora_dallo_script_della_pagina()
+ {
+ var read = RewardsPages.ParseCreditHistory(Fixture("cronologia-crediti.html"));
+ Assert.Null(read.Error);
+ Assert.Equal(3, read.Items.Count);
+ Assert.Equal(1, read.Skipped); // il movimento senza ora nello script
+
+ var free = read.Items[0];
+ Assert.Equal("accredito|1000000003", free.Key);
+ Assert.Equal(DateTimeOffset.FromUnixTimeSeconds(1795511512).UtcDateTime, free.AtUtc);
+ Assert.Equal(5, free.Bids);
+ Assert.True(free.Free);
+
+ var paid = read.Items[2];
+ Assert.Equal(1000, paid.Bids);
+ Assert.False(paid.Free);
+ Assert.Contains("Pacchetto", paid.Description);
+ Assert.Contains("100,00 €", paid.Description);
+ }
+
+ [Fact]
+ public void La_campanella_da_solo_i_collegamenti_promozionali_e_passano_il_controllo()
+ {
+ var bell = RewardsPages.ParseNotifications(Fixture("campanella.json"));
+ Assert.Null(bell.Error);
+ Assert.Equal(3, bell.Notifications);
+ Assert.Equal(2, bell.Links.Count);
+ Assert.Equal("9000003", bell.Links[0].Id);
+ Assert.Equal("https://it.bidoo.com/?promocode=prova241126&sign=0123456789abcdef0123456789abcdef01234567", bell.Links[0].Href);
+ Assert.Equal("9000001", bell.Links[1].Id); // indirizzo scritto nel testo, senza href
+
+ var fb = BidooReferences.Default.FreeBids;
+ foreach (var (_, href) in bell.Links)
+ Assert.True(PromoLinkCheck.Check(href, BidooReferences.Default.Host, fb.PromoPaths, fb.PromoExtraParameters).Ok, href);
+
+ Assert.Empty(RewardsPages.ParseNotifications("""{"count":0,"elements":[],"t":1}""").Links);
+ }
+
+ [Fact]
+ public void Una_pagina_di_accesso_o_una_risposta_rotta_si_dicono_e_non_danno_ricompense()
+ {
+ const string login = "";
+ Assert.NotNull(RewardsPages.ParseChests(login, Rome).Error);
+ Assert.NotNull(RewardsPages.ParseCreditHistory(login).Error);
+ Assert.NotNull(RewardsPages.ParseChests(null, Rome).Error);
+ Assert.NotNull(RewardsPages.ParseNotifications(login).Error);
+ Assert.NotNull(RewardsPages.ParseNotifications("""{"count":0}""").Error);
+ Assert.Empty(RewardsPages.ParseNotifications("rotto").Links);
+ }
+
+ [Fact]
+ public void Il_confronto_del_giorno_con_i_riscatti_del_bot()
+ {
+ var items = RewardsPages.ParseChests(Fixture("ricompense-forzieri.html"), Rome).Items;
+ var today = new DateOnly(2026, 11, 24);
+ Assert.EndsWith("tornano", RewardsPages.CompareToday(items, today, Rome, 2, 10));
+ Assert.Contains("2 ricompense da collegamento (+10 puntate)", RewardsPages.CompareToday(items, today, Rome, 2, 10));
+ Assert.Contains("fuori dal bot", RewardsPages.CompareToday(items, today, Rome, 1, 5));
+ Assert.Contains("non compare", RewardsPages.CompareToday(items, today, Rome, 3, 15));
+ Assert.Contains("1 ricompense da collegamento (+2 puntate)", RewardsPages.CompareToday(items, today.AddDays(-1), Rome, 1, 2));
+ }
+}