diff --git a/brand/prediqo-app-icon.png b/brand/prediqo-app-icon.png index 36ff1c3c..28d34d54 100644 Binary files a/brand/prediqo-app-icon.png and b/brand/prediqo-app-icon.png differ diff --git a/brand/prediqo-lockup-source.png b/brand/prediqo-lockup-source.png index f4ffc9fe..c104326c 100644 Binary files a/brand/prediqo-lockup-source.png and b/brand/prediqo-lockup-source.png differ diff --git a/brand/prediqo-lockup.png b/brand/prediqo-lockup.png index f4ffc9fe..c104326c 100644 Binary files a/brand/prediqo-lockup.png and b/brand/prediqo-lockup.png differ diff --git a/brand/prediqo-lockup.svg b/brand/prediqo-lockup.svg index b85599f2..76710e7f 100644 --- a/brand/prediqo-lockup.svg +++ b/brand/prediqo-lockup.svg @@ -1,13 +1,4 @@ - - - - - - - - - - - + + TLOTO diff --git a/brand/prediqo-mark-source.png b/brand/prediqo-mark-source.png index 36ff1c3c..28d34d54 100644 Binary files a/brand/prediqo-mark-source.png and b/brand/prediqo-mark-source.png differ diff --git a/brand/prediqo-mark.png b/brand/prediqo-mark.png index 36ff1c3c..28d34d54 100644 Binary files a/brand/prediqo-mark.png and b/brand/prediqo-mark.png differ diff --git a/brand/prediqo-mark.svg b/brand/prediqo-mark.svg index 55bf9df0..757a89fc 100644 --- a/brand/prediqo-mark.svg +++ b/brand/prediqo-mark.svg @@ -1,20 +1,4 @@ - - - - - - - - - - - - + + + diff --git a/brand/render_tloto_assets.py b/brand/render_tloto_assets.py new file mode 100644 index 00000000..b166e468 --- /dev/null +++ b/brand/render_tloto_assets.py @@ -0,0 +1,248 @@ +"""Generate TLoto brand PNGs and distribute to web/mobile icon slots.""" +from __future__ import annotations + +import math +import shutil +from pathlib import Path + +from PIL import Image, ImageDraw, ImageFilter + +ROOT = Path(__file__).resolve().parents[1] +BRAND = ROOT / "brand" +AI_SRC = Path( + r"C:\Users\ADMIN\.cursor\projects\d-Projects-Workplace-Own-Projects-games-app\assets\tloto-mark-final.jpg" +) +if not AI_SRC.exists(): + AI_SRC = Path( + r"C:\Users\ADMIN\.cursor\projects\d-Projects-Workplace-Own-Projects-games-app\assets\tloto-mark-v1.jpg" + ) + +NAVY = (11, 15, 26, 255) +GOLD = (212, 175, 55, 255) +EMERALD_TOP = (52, 211, 153, 255) +EMERALD = (16, 185, 129, 255) +EMERALD_DEEP = (4, 120, 87, 255) + + +def _lerp(a, b, t: float): + return tuple(int(a[i] + (b[i] - a[i]) * t) for i in range(4)) + + +def _rounded_rect_mask(size: int, radius: int) -> Image.Image: + m = Image.new("L", (size, size), 0) + d = ImageDraw.Draw(m) + d.rounded_rectangle((0, 0, size - 1, size - 1), radius=radius, fill=255) + return m + + +def draw_mark(size: int = 1024) -> Image.Image: + """Vector-like raster of the fused T+L mark.""" + s = size + img = Image.new("RGBA", (s, s), (0, 0, 0, 0)) + draw = ImageDraw.Draw(img) + + # Background squircle + bg = Image.new("RGBA", (s, s), (0, 0, 0, 0)) + bg_draw = ImageDraw.Draw(bg) + rr = int(s * 0.22) + bg_draw.rounded_rectangle((0, 0, s - 1, s - 1), radius=rr, fill=NAVY) + # Gold border + inset = int(s * 0.05) + border_w = max(2, int(s * 0.022)) + bg_draw.rounded_rectangle( + (inset, inset, s - 1 - inset, s - 1 - inset), + radius=max(1, rr - inset // 2), + outline=GOLD, + width=border_w, + ) + img = Image.alpha_composite(img, bg) + draw = ImageDraw.Draw(img) + + # Glyph geometry in 128-space scaled + def xy(x: float, y: float) -> tuple[float, float]: + return x / 128 * s, y / 128 * s + + # Continuous TL path points (outer contour) + pts = [ + xy(34, 24), + xy(84, 24), + xy(102, 40), + xy(84, 56), + xy(54, 56), + xy(54, 74), + xy(76, 74), + xy(94, 90), + xy(76, 106), + xy(34, 106), + xy(17, 90), + xy(17, 40), + ] + + # Build filled glyph on its own layer for gradient + glyph = Image.new("RGBA", (s, s), (0, 0, 0, 0)) + gdraw = ImageDraw.Draw(glyph) + + # Approximate smooth TL with thick rounded polygon + rounded bars + # Top canopy (T) + top = [ + xy(28, 28), + xy(88, 28), + xy(100, 40), + xy(88, 52), + xy(50, 52), + xy(50, 40), + xy(28, 40), + ] + # Stem + stem = [ + xy(28, 40), + xy(50, 40), + xy(50, 88), + xy(28, 88), + ] + # Foot (L) + foot = [ + xy(28, 78), + xy(82, 78), + xy(94, 90), + xy(82, 102), + xy(28, 102), + ] + + def fill_soft(poly, color): + gdraw.polygon(poly, fill=color) + + # Gradient by layered fills + fill_soft(top, EMERALD_TOP) + fill_soft(stem, EMERALD) + fill_soft(foot, EMERALD_DEEP) + + # Soften joints with overlapping rounded rects + x0, y0 = xy(28, 28) + x1, y1 = xy(50, 102) + gdraw.rounded_rectangle((x0, y0, x1, y1), radius=int(s * 0.06), fill=EMERALD) + # Top arm + tx0, ty0 = xy(28, 28) + tx1, ty1 = xy(100, 52) + gdraw.rounded_rectangle((tx0, ty0, tx1, ty1), radius=int(s * 0.07), fill=EMERALD_TOP) + # Blend mid + mx0, my0 = xy(28, 40) + mx1, my1 = xy(92, 52) + gdraw.rounded_rectangle((mx0, my0, mx1, my1), radius=int(s * 0.05), fill=EMERALD) + # L foot + fx0, fy0 = xy(28, 78) + fx1, fy1 = xy(94, 102) + gdraw.rounded_rectangle((fx0, fy0, fx1, fy1), radius=int(s * 0.07), fill=EMERALD) + + # Slight blur then re-composite for premium softness at edges + glyph = glyph.filter(ImageFilter.GaussianBlur(radius=max(0.4, s / 900))) + # Re-sharpen core by overlaying unblurred core at lower opacity handled via mask + core = Image.new("RGBA", (s, s), (0, 0, 0, 0)) + cdraw = ImageDraw.Draw(core) + cdraw.rounded_rectangle((x0, y0, x1, y1), radius=int(s * 0.06), fill=EMERALD) + cdraw.rounded_rectangle((tx0, ty0, tx1, ty1), radius=int(s * 0.07), fill=EMERALD_TOP) + cdraw.rounded_rectangle((fx0, fy0, fx1, fy1), radius=int(s * 0.07), fill=EMERALD) + glyph = Image.alpha_composite(glyph, core) + + img = Image.alpha_composite(img, glyph) + draw = ImageDraw.Draw(img) + + # Gold spark at joint + cx, cy = xy(54, 52) + r = s * 0.028 + spark = [ + (cx, cy - r * 1.7), + (cx + r * 0.35, cy - r * 0.35), + (cx + r * 1.7, cy), + (cx + r * 0.35, cy + r * 0.35), + (cx, cy + r * 1.7), + (cx - r * 0.35, cy + r * 0.35), + (cx - r * 1.7, cy), + (cx - r * 0.35, cy - r * 0.35), + ] + draw.polygon(spark, fill=GOLD) + + return img + + +def prepare_from_ai(size: int = 1024) -> Image.Image | None: + if not AI_SRC.exists(): + return None + src = Image.open(AI_SRC).convert("RGBA") + # Center-crop to square + w, h = src.size + side = min(w, h) + left = (w - side) // 2 + top = (h - side) // 2 + src = src.crop((left, top, left + side, top + side)) + src = src.resize((size, size), Image.Resampling.LANCZOS) + # Apply squircle mask so PNG edges are clean for adaptive icons + mask = _rounded_rect_mask(size, int(size * 0.22)) + out = Image.new("RGBA", (size, size), (0, 0, 0, 0)) + out.paste(src, (0, 0)) + out.putalpha(mask) + return out + + +def save_png(img: Image.Image, path: Path, size: int | None = None) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + out = img if size is None else img.resize((size, size), Image.Resampling.LANCZOS) + if out.mode != "RGBA": + out = out.convert("RGBA") + out.save(path, format="PNG", optimize=True) + + +def make_lockup(mark: Image.Image, width: int = 1600, height: int = 512) -> Image.Image: + canvas = Image.new("RGBA", (width, height), (0, 0, 0, 0)) + mark_size = height + m = mark.resize((mark_size, mark_size), Image.Resampling.LANCZOS) + canvas.paste(m, (0, 0), m) + # Wordmark drawn by SVG/text elsewhere; keep mark-only lockup base transparent + # Consumers use SVG lockup for text; PNG lockup = mark + transparent padding + return canvas + + +def distribute(master: Image.Image) -> None: + # Brand master + save_png(master, BRAND / "prediqo-mark.png", 1024) + save_png(master, BRAND / "prediqo-app-icon.png", 1024) + save_png(master, BRAND / "prediqo-mark-source.png", 1024) + + lockup = make_lockup(master) + save_png(lockup, BRAND / "prediqo-lockup.png") + save_png(lockup, BRAND / "prediqo-lockup-source.png") + + # Web public + web_brand = ROOT / "prediqo_web" / "public" / "brand" + save_png(master, web_brand / "prediqo-mark.png", 512) + save_png(master, web_brand / "prediqo-app-icon.png", 512) + save_png(lockup, web_brand / "prediqo-lockup.png") + shutil.copy2(BRAND / "prediqo-mark.svg", web_brand / "prediqo-mark.svg") + shutil.copy2(BRAND / "prediqo-lockup.svg", web_brand / "prediqo-lockup.svg") + + # Favicon SVG (same mark) + shutil.copy2(BRAND / "prediqo-mark.svg", ROOT / "prediqo_web" / "public" / "favicon.svg") + + # Mobile assets + mobile_brand = ROOT / "prediqo_mobile" / "assets" / "brand" + save_png(master, mobile_brand / "prediqo-mark.png", 512) + save_png(master, mobile_brand / "prediqo-app-icon.png", 1024) + save_png(lockup, mobile_brand / "prediqo-lockup.png") + shutil.copy2(BRAND / "prediqo-mark.svg", mobile_brand / "prediqo-mark.svg") + + # Mobile web favicon + save_png(master, ROOT / "prediqo_mobile" / "web" / "favicon.png", 192) + + print("Distributed brand assets.") + + +def main() -> None: + ai = prepare_from_ai(1024) + # Prefer AI master; fall back to vector draw only if AI source is missing. + master = ai if ai is not None else draw_mark(1024) + print(f"Using AI master from {AI_SRC}" if ai is not None else "Using vector-drawn master") + distribute(master) + + +if __name__ == "__main__": + main() diff --git a/brand/sync_svg_from_png.py b/brand/sync_svg_from_png.py new file mode 100644 index 00000000..fd2a851b --- /dev/null +++ b/brand/sync_svg_from_png.py @@ -0,0 +1,57 @@ +"""Make SVG mark identical to the master PNG by embedding it.""" +from __future__ import annotations + +import base64 +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +BRAND = ROOT / "brand" +PNG = BRAND / "prediqo-mark.png" + + +def main() -> None: + b64 = base64.b64encode(PNG.read_bytes()).decode("ascii") + mark = ( + '\n' + " \n" + f' \n' + "\n" + ) + lockup = ( + '\n' + f' \n' + ' TLOTO\n' + "\n" + ) + + targets_mark = [ + BRAND / "prediqo-mark.svg", + ROOT / "prediqo_web" / "public" / "brand" / "prediqo-mark.svg", + ROOT / "prediqo_web" / "public" / "favicon.svg", + ROOT / "prediqo_mobile" / "assets" / "brand" / "prediqo-mark.svg", + ] + targets_lockup = [ + BRAND / "prediqo-lockup.svg", + ROOT / "prediqo_web" / "public" / "brand" / "prediqo-lockup.svg", + ] + for path in targets_mark: + path.write_text(mark, encoding="utf-8") + print(f"wrote {path}") + for path in targets_lockup: + path.write_text(lockup, encoding="utf-8") + print(f"wrote {path}") + + +if __name__ == "__main__": + main() diff --git a/prediqo_mobile/android/app/src/main/res/drawable-hdpi/android12splash.png b/prediqo_mobile/android/app/src/main/res/drawable-hdpi/android12splash.png index 22615045..63cb913c 100644 Binary files a/prediqo_mobile/android/app/src/main/res/drawable-hdpi/android12splash.png and b/prediqo_mobile/android/app/src/main/res/drawable-hdpi/android12splash.png differ diff --git a/prediqo_mobile/android/app/src/main/res/drawable-hdpi/ic_launcher_foreground.png b/prediqo_mobile/android/app/src/main/res/drawable-hdpi/ic_launcher_foreground.png index 182cd912..8cf7cc8d 100644 Binary files a/prediqo_mobile/android/app/src/main/res/drawable-hdpi/ic_launcher_foreground.png and b/prediqo_mobile/android/app/src/main/res/drawable-hdpi/ic_launcher_foreground.png differ diff --git a/prediqo_mobile/android/app/src/main/res/drawable-hdpi/splash.png b/prediqo_mobile/android/app/src/main/res/drawable-hdpi/splash.png index 22615045..63cb913c 100644 Binary files a/prediqo_mobile/android/app/src/main/res/drawable-hdpi/splash.png and b/prediqo_mobile/android/app/src/main/res/drawable-hdpi/splash.png differ diff --git a/prediqo_mobile/android/app/src/main/res/drawable-mdpi/android12splash.png b/prediqo_mobile/android/app/src/main/res/drawable-mdpi/android12splash.png index d6307fe9..d9cfe115 100644 Binary files a/prediqo_mobile/android/app/src/main/res/drawable-mdpi/android12splash.png and b/prediqo_mobile/android/app/src/main/res/drawable-mdpi/android12splash.png differ diff --git a/prediqo_mobile/android/app/src/main/res/drawable-mdpi/ic_launcher_foreground.png b/prediqo_mobile/android/app/src/main/res/drawable-mdpi/ic_launcher_foreground.png index 10497e1e..2fae4780 100644 Binary files a/prediqo_mobile/android/app/src/main/res/drawable-mdpi/ic_launcher_foreground.png and b/prediqo_mobile/android/app/src/main/res/drawable-mdpi/ic_launcher_foreground.png differ diff --git a/prediqo_mobile/android/app/src/main/res/drawable-mdpi/splash.png b/prediqo_mobile/android/app/src/main/res/drawable-mdpi/splash.png index d6307fe9..d9cfe115 100644 Binary files a/prediqo_mobile/android/app/src/main/res/drawable-mdpi/splash.png and b/prediqo_mobile/android/app/src/main/res/drawable-mdpi/splash.png differ diff --git a/prediqo_mobile/android/app/src/main/res/drawable-night-hdpi/android12splash.png b/prediqo_mobile/android/app/src/main/res/drawable-night-hdpi/android12splash.png index 22615045..63cb913c 100644 Binary files a/prediqo_mobile/android/app/src/main/res/drawable-night-hdpi/android12splash.png and b/prediqo_mobile/android/app/src/main/res/drawable-night-hdpi/android12splash.png differ diff --git a/prediqo_mobile/android/app/src/main/res/drawable-night-mdpi/android12splash.png b/prediqo_mobile/android/app/src/main/res/drawable-night-mdpi/android12splash.png index d6307fe9..d9cfe115 100644 Binary files a/prediqo_mobile/android/app/src/main/res/drawable-night-mdpi/android12splash.png and b/prediqo_mobile/android/app/src/main/res/drawable-night-mdpi/android12splash.png differ diff --git a/prediqo_mobile/android/app/src/main/res/drawable-night-xhdpi/android12splash.png b/prediqo_mobile/android/app/src/main/res/drawable-night-xhdpi/android12splash.png index 4c002a37..4aa86efd 100644 Binary files a/prediqo_mobile/android/app/src/main/res/drawable-night-xhdpi/android12splash.png and b/prediqo_mobile/android/app/src/main/res/drawable-night-xhdpi/android12splash.png differ diff --git a/prediqo_mobile/android/app/src/main/res/drawable-night-xxhdpi/android12splash.png b/prediqo_mobile/android/app/src/main/res/drawable-night-xxhdpi/android12splash.png index cbb595b4..681beab4 100644 Binary files a/prediqo_mobile/android/app/src/main/res/drawable-night-xxhdpi/android12splash.png and b/prediqo_mobile/android/app/src/main/res/drawable-night-xxhdpi/android12splash.png differ diff --git a/prediqo_mobile/android/app/src/main/res/drawable-night-xxxhdpi/android12splash.png b/prediqo_mobile/android/app/src/main/res/drawable-night-xxxhdpi/android12splash.png index fb0bef12..b8e9e9ea 100644 Binary files a/prediqo_mobile/android/app/src/main/res/drawable-night-xxxhdpi/android12splash.png and b/prediqo_mobile/android/app/src/main/res/drawable-night-xxxhdpi/android12splash.png differ diff --git a/prediqo_mobile/android/app/src/main/res/drawable-xhdpi/android12splash.png b/prediqo_mobile/android/app/src/main/res/drawable-xhdpi/android12splash.png index 4c002a37..4aa86efd 100644 Binary files a/prediqo_mobile/android/app/src/main/res/drawable-xhdpi/android12splash.png and b/prediqo_mobile/android/app/src/main/res/drawable-xhdpi/android12splash.png differ diff --git a/prediqo_mobile/android/app/src/main/res/drawable-xhdpi/ic_launcher_foreground.png b/prediqo_mobile/android/app/src/main/res/drawable-xhdpi/ic_launcher_foreground.png index b90fc00a..f4540d44 100644 Binary files a/prediqo_mobile/android/app/src/main/res/drawable-xhdpi/ic_launcher_foreground.png and b/prediqo_mobile/android/app/src/main/res/drawable-xhdpi/ic_launcher_foreground.png differ diff --git a/prediqo_mobile/android/app/src/main/res/drawable-xhdpi/splash.png b/prediqo_mobile/android/app/src/main/res/drawable-xhdpi/splash.png index 4c002a37..4aa86efd 100644 Binary files a/prediqo_mobile/android/app/src/main/res/drawable-xhdpi/splash.png and b/prediqo_mobile/android/app/src/main/res/drawable-xhdpi/splash.png differ diff --git a/prediqo_mobile/android/app/src/main/res/drawable-xxhdpi/android12splash.png b/prediqo_mobile/android/app/src/main/res/drawable-xxhdpi/android12splash.png index cbb595b4..681beab4 100644 Binary files a/prediqo_mobile/android/app/src/main/res/drawable-xxhdpi/android12splash.png and b/prediqo_mobile/android/app/src/main/res/drawable-xxhdpi/android12splash.png differ diff --git a/prediqo_mobile/android/app/src/main/res/drawable-xxhdpi/ic_launcher_foreground.png b/prediqo_mobile/android/app/src/main/res/drawable-xxhdpi/ic_launcher_foreground.png index fd776927..3dbd79af 100644 Binary files a/prediqo_mobile/android/app/src/main/res/drawable-xxhdpi/ic_launcher_foreground.png and b/prediqo_mobile/android/app/src/main/res/drawable-xxhdpi/ic_launcher_foreground.png differ diff --git a/prediqo_mobile/android/app/src/main/res/drawable-xxhdpi/splash.png b/prediqo_mobile/android/app/src/main/res/drawable-xxhdpi/splash.png index cbb595b4..681beab4 100644 Binary files a/prediqo_mobile/android/app/src/main/res/drawable-xxhdpi/splash.png and b/prediqo_mobile/android/app/src/main/res/drawable-xxhdpi/splash.png differ diff --git a/prediqo_mobile/android/app/src/main/res/drawable-xxxhdpi/android12splash.png b/prediqo_mobile/android/app/src/main/res/drawable-xxxhdpi/android12splash.png index fb0bef12..b8e9e9ea 100644 Binary files a/prediqo_mobile/android/app/src/main/res/drawable-xxxhdpi/android12splash.png and b/prediqo_mobile/android/app/src/main/res/drawable-xxxhdpi/android12splash.png differ diff --git a/prediqo_mobile/android/app/src/main/res/drawable-xxxhdpi/ic_launcher_foreground.png b/prediqo_mobile/android/app/src/main/res/drawable-xxxhdpi/ic_launcher_foreground.png index 0a70dc1e..46e52bc5 100644 Binary files a/prediqo_mobile/android/app/src/main/res/drawable-xxxhdpi/ic_launcher_foreground.png and b/prediqo_mobile/android/app/src/main/res/drawable-xxxhdpi/ic_launcher_foreground.png differ diff --git a/prediqo_mobile/android/app/src/main/res/drawable-xxxhdpi/splash.png b/prediqo_mobile/android/app/src/main/res/drawable-xxxhdpi/splash.png index fb0bef12..b8e9e9ea 100644 Binary files a/prediqo_mobile/android/app/src/main/res/drawable-xxxhdpi/splash.png and b/prediqo_mobile/android/app/src/main/res/drawable-xxxhdpi/splash.png differ diff --git a/prediqo_mobile/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/prediqo_mobile/android/app/src/main/res/mipmap-hdpi/ic_launcher.png index cedc2feb..f0232eba 100644 Binary files a/prediqo_mobile/android/app/src/main/res/mipmap-hdpi/ic_launcher.png and b/prediqo_mobile/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/prediqo_mobile/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/prediqo_mobile/android/app/src/main/res/mipmap-mdpi/ic_launcher.png index 677c9b3b..edc70097 100644 Binary files a/prediqo_mobile/android/app/src/main/res/mipmap-mdpi/ic_launcher.png and b/prediqo_mobile/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/prediqo_mobile/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/prediqo_mobile/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png index 8dcefa6f..4ffc1cb9 100644 Binary files a/prediqo_mobile/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png and b/prediqo_mobile/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/prediqo_mobile/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/prediqo_mobile/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png index a2fe3d9d..42a02d66 100644 Binary files a/prediqo_mobile/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png and b/prediqo_mobile/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/prediqo_mobile/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/prediqo_mobile/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png index 0e7a72ba..12f1b7f4 100644 Binary files a/prediqo_mobile/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png and b/prediqo_mobile/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/prediqo_mobile/assets/brand/prediqo-app-icon.png b/prediqo_mobile/assets/brand/prediqo-app-icon.png index 36ff1c3c..28d34d54 100644 Binary files a/prediqo_mobile/assets/brand/prediqo-app-icon.png and b/prediqo_mobile/assets/brand/prediqo-app-icon.png differ diff --git a/prediqo_mobile/assets/brand/prediqo-lockup.png b/prediqo_mobile/assets/brand/prediqo-lockup.png index f4ffc9fe..c104326c 100644 Binary files a/prediqo_mobile/assets/brand/prediqo-lockup.png and b/prediqo_mobile/assets/brand/prediqo-lockup.png differ diff --git a/prediqo_mobile/assets/brand/prediqo-mark.png b/prediqo_mobile/assets/brand/prediqo-mark.png index 36ff1c3c..1fd5243d 100644 Binary files a/prediqo_mobile/assets/brand/prediqo-mark.png and b/prediqo_mobile/assets/brand/prediqo-mark.png differ diff --git a/prediqo_mobile/assets/brand/prediqo-mark.svg b/prediqo_mobile/assets/brand/prediqo-mark.svg index 55bf9df0..757a89fc 100644 --- a/prediqo_mobile/assets/brand/prediqo-mark.svg +++ b/prediqo_mobile/assets/brand/prediqo-mark.svg @@ -1,20 +1,4 @@ - - - - - - - - - - - - + + + diff --git a/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png index fb0bef12..35917fa8 100644 Binary files a/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png and b/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png differ diff --git a/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png index e9a3a7ac..138db8bc 100644 Binary files a/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png and b/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png differ diff --git a/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png index 0f8f69ee..5370b9a1 100644 Binary files a/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png and b/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png differ diff --git a/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png index 4463d65c..29f78ec5 100644 Binary files a/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png and b/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png differ diff --git a/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png index 3761906a..30149330 100644 Binary files a/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png and b/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png differ diff --git a/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png index 67234003..8a038459 100644 Binary files a/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png and b/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png differ diff --git a/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png index ce0241d5..2e0b29f4 100644 Binary files a/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png and b/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png differ diff --git a/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png index 0f8f69ee..5370b9a1 100644 Binary files a/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png and b/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png differ diff --git a/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png index d455d110..bf2e658b 100644 Binary files a/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png and b/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png differ diff --git a/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png index b9fc3329..45ac2c84 100644 Binary files a/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png and b/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png differ diff --git a/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@1x.png b/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@1x.png index ad477bcc..cc1cbb6e 100644 Binary files a/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@1x.png and b/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@1x.png differ diff --git a/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@2x.png b/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@2x.png index dd7fb765..2bebb7fb 100644 Binary files a/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@2x.png and b/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-50x50@2x.png differ diff --git a/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@1x.png b/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@1x.png index 19060427..d1a5e6c7 100644 Binary files a/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@1x.png and b/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@1x.png differ diff --git a/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@2x.png b/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@2x.png index c69ba1d4..569437f2 100644 Binary files a/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@2x.png and b/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-57x57@2x.png differ diff --git a/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png index b9fc3329..45ac2c84 100644 Binary files a/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png and b/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png differ diff --git a/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png index 512060aa..e567aa3b 100644 Binary files a/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png and b/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png differ diff --git a/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@1x.png b/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@1x.png index cedc2feb..c179b10c 100644 Binary files a/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@1x.png and b/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@1x.png differ diff --git a/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@2x.png b/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@2x.png index a2fe3d9d..888a57ba 100644 Binary files a/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@2x.png and b/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-72x72@2x.png differ diff --git a/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png index 47d2f521..16613200 100644 Binary files a/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png and b/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png differ diff --git a/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png index ce006f64..0272ec2c 100644 Binary files a/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png and b/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png differ diff --git a/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png index 80d424f9..26cbc7eb 100644 Binary files a/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png and b/prediqo_mobile/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png differ diff --git a/prediqo_mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/prediqo_mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png index d6307fe9..d9cfe115 100644 Binary files a/prediqo_mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png and b/prediqo_mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png differ diff --git a/prediqo_mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/prediqo_mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png index 4c002a37..4aa86efd 100644 Binary files a/prediqo_mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png and b/prediqo_mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png differ diff --git a/prediqo_mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/prediqo_mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png index cbb595b4..681beab4 100644 Binary files a/prediqo_mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png and b/prediqo_mobile/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png differ diff --git a/prediqo_mobile/ios/Runner/Base.lproj/LaunchScreen.storyboard b/prediqo_mobile/ios/Runner/Base.lproj/LaunchScreen.storyboard index 8d2b7d51..7aa6dfbc 100644 --- a/prediqo_mobile/ios/Runner/Base.lproj/LaunchScreen.storyboard +++ b/prediqo_mobile/ios/Runner/Base.lproj/LaunchScreen.storyboard @@ -38,7 +38,7 @@ - + diff --git a/prediqo_mobile/lib/core/di/injection.dart b/prediqo_mobile/lib/core/di/injection.dart index 30179572..a98504b4 100644 --- a/prediqo_mobile/lib/core/di/injection.dart +++ b/prediqo_mobile/lib/core/di/injection.dart @@ -62,6 +62,9 @@ Future configureDependencies({AppConfig? config}) async { if (!sl.isRegistered()) { sl.registerLazySingleton(() => WalletRepositoryImpl(sl())); } + if (!sl.isRegistered()) { + sl.registerLazySingleton(() => sl()); + } if (!sl.isRegistered()) { sl.registerLazySingleton(() => AdminRepositoryImpl(sl())); } @@ -99,7 +102,14 @@ Future configureDependencies({AppConfig? config}) async { sl.registerFactory(() => AuthBloc(sl())..add(const AuthCheckRequested())); } if (!sl.isRegistered()) { - sl.registerFactory(() => WalletBloc(sl())); + sl.registerFactory( + () => WalletBloc( + sl(), + sl(), + sl(), + shareCards: sl(), + ), + ); } if (!sl.isRegistered()) { sl.registerFactory(() => PredictionBloc(sl(), sl(), sl())); diff --git a/prediqo_mobile/lib/data/repositories/advertisement_repository_impl.dart b/prediqo_mobile/lib/data/repositories/advertisement_repository_impl.dart index 0922d3e1..5222777b 100644 --- a/prediqo_mobile/lib/data/repositories/advertisement_repository_impl.dart +++ b/prediqo_mobile/lib/data/repositories/advertisement_repository_impl.dart @@ -4,12 +4,90 @@ import '../../core/network/api_client.dart'; import '../../data/models/advertisement_models.dart'; import '../../domain/repositories/advertisement_repository.dart'; +/// Short TTL + in-flight coalesce for `/api/v1/advertisements`. +/// Shared by Home and Welcome, keyed by placement. +class AdvertisementStore { + static const ttl = Duration(seconds: 45); + + List? _cached; + DateTime? _cachedAt; + Future>? _inFlight; + int fetchStarts = 0; + + List? peekLast() => _cached; + + List? peekFresh() { + if (_cached == null || _cachedAt == null) return null; + if (DateTime.now().difference(_cachedAt!) >= ttl) return null; + return _cached; + } + + void invalidate() { + _cached = null; + _cachedAt = null; + } + + Future> get( + Future> Function() fetch, { + bool force = false, + }) async { + if (!force) { + final hit = peekFresh(); + if (hit != null) return hit; + if (_inFlight != null) return _inFlight!; + } + fetchStarts++; + final future = fetch().then((value) { + _cached = value; + _cachedAt = DateTime.now(); + return value; + }); + _inFlight = future; + try { + return await future; + } finally { + if (identical(_inFlight, future)) _inFlight = null; + } + } +} + class AdvertisementRepositoryImpl implements AdvertisementRepository { AdvertisementRepositoryImpl(this._api); final ApiClient _api; + final Map _stores = {}; + + AdvertisementStore storeFor({String? placement}) => + _stores.putIfAbsent(placement ?? '', AdvertisementStore.new); + @override - Future> list({String? placement}) async { + List? peekCached({String? placement}) => + storeFor(placement: placement).peekFresh(); + + @override + List? peekLast({String? placement}) => + storeFor(placement: placement).peekLast(); + + @override + void invalidate({String? placement}) { + if (placement != null) { + storeFor(placement: placement).invalidate(); + return; + } + for (final store in _stores.values) { + store.invalidate(); + } + } + + @override + Future> list({String? placement, bool force = false}) { + return storeFor(placement: placement).get( + () => _fetch(placement: placement), + force: force, + ); + } + + Future> _fetch({String? placement}) async { try { final res = await _api.dio.get( '/api/v1/advertisements', diff --git a/prediqo_mobile/lib/data/repositories/game_catalog_repository_impl.dart b/prediqo_mobile/lib/data/repositories/game_catalog_repository_impl.dart index 20db3611..c2efa672 100644 --- a/prediqo_mobile/lib/data/repositories/game_catalog_repository_impl.dart +++ b/prediqo_mobile/lib/data/repositories/game_catalog_repository_impl.dart @@ -4,17 +4,92 @@ import '../../core/network/api_client.dart'; import '../../data/models/game_catalog_models.dart'; import '../../domain/repositories/game_catalog_repository.dart'; +/// Short TTL + in-flight coalesce for `/api/v1/games`. +/// Shared by Home, Welcome, and the Predict catalog. +class GameCatalogStore { + static const ttl = Duration(seconds: 45); + + List? _cached; + DateTime? _cachedAt; + Future>? _inFlight; + int fetchStarts = 0; + + List? peekLast() => _cached; + + List? peekFresh() { + if (_cached == null || _cachedAt == null) return null; + if (DateTime.now().difference(_cachedAt!) >= ttl) return null; + return _cached; + } + + void invalidate() { + _cached = null; + _cachedAt = null; + } + + Future> get( + Future> Function() fetch, { + bool force = false, + }) async { + if (!force) { + final hit = peekFresh(); + if (hit != null) return hit; + if (_inFlight != null) return _inFlight!; + } + fetchStarts++; + final future = fetch().then((value) { + _cached = value; + _cachedAt = DateTime.now(); + return value; + }); + _inFlight = future; + try { + return await future; + } finally { + if (identical(_inFlight, future)) _inFlight = null; + } + } +} + class GameCatalogRepositoryImpl implements GameCatalogRepository { GameCatalogRepositoryImpl(this._api); final ApiClient _api; + final GameCatalogStore store = GameCatalogStore(); + final GameCatalogStore featuredStore = GameCatalogStore(); + + GameCatalogStore _store({required bool featured}) => + featured ? featuredStore : store; + @override - Future> list({bool? featured}) async { + List? peekCached({bool featured = false}) => + _store(featured: featured).peekFresh(); + + @override + List? peekLast({bool featured = false}) => + _store(featured: featured).peekLast(); + + @override + void invalidate() { + store.invalidate(); + featuredStore.invalidate(); + } + + @override + Future> list({bool? featured, bool force = false}) { + final isFeatured = featured == true; + return _store(featured: isFeatured).get( + () => _fetch(featured: isFeatured), + force: force, + ); + } + + Future> _fetch({required bool featured}) async { try { final res = await _api.dio.get( '/api/v1/games', queryParameters: { - if (featured == true) 'featured': true, + if (featured) 'featured': true, }, ); final data = res.data; diff --git a/prediqo_mobile/lib/data/repositories/share_card_repository.dart b/prediqo_mobile/lib/data/repositories/share_card_repository.dart index 05a9165e..144ce1c0 100644 --- a/prediqo_mobile/lib/data/repositories/share_card_repository.dart +++ b/prediqo_mobile/lib/data/repositories/share_card_repository.dart @@ -3,30 +3,66 @@ import '../../core/network/api_client.dart'; import '../models/share_card_models.dart'; import 'package:dio/dio.dart'; +/// In-flight coalescing + short TTL for share-card admin/user flags. +/// Not a blind cache: [invalidate] after a ledger mutation (deposit, withdraw…). +class ShareConfigStore { + ShareCardConfig? _cached; + DateTime? _cachedAt; + Future? _inFlight; + + static const ttl = Duration(minutes: 1); + + int fetchStarts = 0; + + void invalidate() { + _cached = null; + _cachedAt = null; + } + + Future get( + Future Function() fetch, { + bool force = false, + }) async { + final now = DateTime.now(); + if (!force && + _cached != null && + _cachedAt != null && + now.difference(_cachedAt!) < ttl) { + return _cached!; + } + if (_inFlight != null) return _inFlight!; + fetchStarts++; + final future = fetch().then((value) { + _cached = value; + _cachedAt = DateTime.now(); + return value; + }); + _inFlight = future; + try { + return await future; + } finally { + if (identical(_inFlight, future)) _inFlight = null; + } + } +} + class ShareCardRepository { ShareCardRepository(this._api); final ApiClient _api; - ShareCardConfig? _cachedConfig; - DateTime? _cachedAt; + final ShareConfigStore configStore = ShareConfigStore(); - Future getConfig({bool force = false}) async { - final now = DateTime.now(); - if (!force && - _cachedConfig != null && - _cachedAt != null && - now.difference(_cachedAt!) < const Duration(minutes: 1)) { - return _cachedConfig!; - } - try { - final res = await _api.dio.get>('/api/v1/share-cards/config'); - final config = ShareCardConfig.fromJson(res.data ?? {}); - _cachedConfig = config; - _cachedAt = now; - return config; - } on DioException catch (e) { - throw AppException.fromDio(e); - } + void invalidateConfig() => configStore.invalidate(); + + Future getConfig({bool force = false}) { + return configStore.get(() async { + try { + final res = await _api.dio.get>('/api/v1/share-cards/config'); + return ShareCardConfig.fromJson(res.data ?? {}); + } on DioException catch (e) { + throw AppException.fromDio(e); + } + }, force: force); } Future getBetShareCard(String betId) async { diff --git a/prediqo_mobile/lib/data/repositories/wallet_repository_impl.dart b/prediqo_mobile/lib/data/repositories/wallet_repository_impl.dart index 1bdfd3be..7255c79d 100644 --- a/prediqo_mobile/lib/data/repositories/wallet_repository_impl.dart +++ b/prediqo_mobile/lib/data/repositories/wallet_repository_impl.dart @@ -9,8 +9,34 @@ import '../models/transaction_model.dart'; import '../models/wallet_type_model.dart'; import '../../core/network/api_client.dart'; +/// Wallet data access used by [WalletBloc] (real API or test fake). +abstract class WalletRepository { + Future> getWalletTypes(); + Future> getBalances(); + Future getDepositAddress(String walletType); + Future> getTransactions({ + int limit = 50, + int offset = 0, + String? category, + }); + Future withdraw( + String walletType, + String toAddress, + String amount, { + String? totpCode, + }); + Future transfer( + String toEmail, + String walletType, + String amount, { + String? totpCode, + }); + Future getTestWalletStatus(); + Future requestTestCredits(); +} + /// Repository for wallet types, balances, transactions, and money movement. -class WalletRepositoryImpl { +class WalletRepositoryImpl implements WalletRepository { WalletRepositoryImpl(this._api); final ApiClient _api; diff --git a/prediqo_mobile/lib/domain/repositories/advertisement_repository.dart b/prediqo_mobile/lib/domain/repositories/advertisement_repository.dart index a85ca034..b5896079 100644 --- a/prediqo_mobile/lib/domain/repositories/advertisement_repository.dart +++ b/prediqo_mobile/lib/domain/repositories/advertisement_repository.dart @@ -1,5 +1,11 @@ import '../../data/models/advertisement_models.dart'; abstract class AdvertisementRepository { - Future> list({String? placement}); + Future> list({String? placement, bool force = false}); + + List? peekCached({String? placement}); + + List? peekLast({String? placement}); + + void invalidate({String? placement}); } diff --git a/prediqo_mobile/lib/domain/repositories/game_catalog_repository.dart b/prediqo_mobile/lib/domain/repositories/game_catalog_repository.dart index 1fbf9b66..42dba919 100644 --- a/prediqo_mobile/lib/domain/repositories/game_catalog_repository.dart +++ b/prediqo_mobile/lib/domain/repositories/game_catalog_repository.dart @@ -1,5 +1,13 @@ import '../../data/models/game_catalog_models.dart'; abstract class GameCatalogRepository { - Future> list({bool? featured}); + Future> list({bool? featured, bool force = false}); + + /// Fresh catalog snapshot (within TTL), or null. + List? peekCached({bool featured = false}); + + /// Last snapshot even if stale — used to paint immediately on return. + List? peekLast({bool featured = false}); + + void invalidate(); } diff --git a/prediqo_mobile/lib/features/home/presentation/home_screen.dart b/prediqo_mobile/lib/features/home/presentation/home_screen.dart index 1d424d50..9c8a9d30 100644 --- a/prediqo_mobile/lib/features/home/presentation/home_screen.dart +++ b/prediqo_mobile/lib/features/home/presentation/home_screen.dart @@ -22,6 +22,7 @@ import '../../../shared/widgets/pred_card.dart'; import '../../../shared/widgets/prediqo_logo.dart'; import '../utils/home_navigation.dart'; import '../../prediction/bloc/prediction_bloc.dart'; +import '../../wallet/bloc/wallet_bloc.dart'; import '../../prediction/utils/game_catalog_ui.dart'; import 'widgets/home_ad_carousel.dart'; @@ -45,11 +46,23 @@ class _HomeScreenState extends State { @override void initState() { super.initState(); + final cachedGames = sl().peekLast(); + if (cachedGames != null && cachedGames.isNotEmpty) { + _games = cachedGames; + } + final cachedAds = sl().peekLast(placement: 'home_hero'); + if (cachedAds != null && cachedAds.isNotEmpty) { + _heroAds = cachedAds; + } + if (_heroAds.isNotEmpty || _games.isNotEmpty) { + _loading = false; + } _load(); - _checkAppUpdate(); WidgetsBinding.instance.addPostFrameCallback((_) { if (!mounted) return; context.read().add(const PredictionLoadRequested(ifStale: true)); + context.read().add(const WalletLoadRequested(ifStale: true)); + _checkAppUpdate(); }); } @@ -59,46 +72,77 @@ class _HomeScreenState extends State { setState(() => _updateAvailable = available); } - Future _load() async { - setState(() { - _loading = true; - _error = null; - }); + Future _soft(Future future) async { try { - // Soft-wrap so parallel 401s (expired session) are not reported as - // unhandled async errors before we await them. - Future soft(Future future) async { - try { - return await future; - } catch (_) { - return null; - } - } + return await future; + } catch (_) { + return null; + } + } - final adsFuture = soft(sl().list(placement: 'home_hero')); - final gamesFuture = soft(sl().list()); - final referralFuture = soft(sl().getDashboard(maxDepth: 1)); - final notifFuture = soft(sl().list(limit: 1)); - final profileFuture = soft(sl().getProfile()); + Future _refreshUnread() async { + final page = await _soft(sl().list(limit: 1)); + if (!mounted || page == null) return; + setState(() => _unreadNotifications = page.unreadCount); + } + + Future _refreshTotp() async { + final profile = await _soft(sl().getProfile()); + if (!mounted || profile == null) return; + setState(() => _totpEnabled = profile.totpEnabled); + } + + Future _load({bool force = false}) async { + final keep = (_heroAds.isNotEmpty || _games.isNotEmpty) && !force; + if (!keep) { + setState(() { + _loading = true; + _error = null; + }); + } + try { + final adsFuture = _soft( + sl().list(placement: 'home_hero', force: force), + ); + final gamesFuture = _soft(sl().list(force: force)); + final extrasFuture = () async { + final referral = await _soft(sl().getDashboard(maxDepth: 1)); + final notifPage = await _soft(sl().list(limit: 1)); + final profile = await _soft(sl().getProfile()); + if (!mounted) return; + setState(() { + if (referral != null) _referral = referral; + if (notifPage != null) _unreadNotifications = notifPage.unreadCount; + if (profile != null) _totpEnabled = profile.totpEnabled; + }); + }(); + + adsFuture.then((ads) { + if (!mounted || ads == null) return; + setState(() { + _heroAds = ads; + _loading = false; + _error = null; + }); + }); + gamesFuture.then((games) { + if (!mounted || games == null) return; + setState(() { + _games = games; + _loading = false; + }); + }); final ads = await adsFuture; final games = await gamesFuture; - final referral = await referralFuture; - final notifPage = await notifFuture; - final profile = await profileFuture; - if (!mounted) return; setState(() { - _heroAds = ads ?? const []; - _games = games ?? const []; - _referral = referral; - _unreadNotifications = notifPage?.unreadCount ?? 0; - _totpEnabled = profile?.totpEnabled ?? false; _loading = false; - if (ads == null && games == null) { + if (ads == null && games == null && _heroAds.isEmpty && _games.isEmpty) { _error = AppException.connectionFailedMessage; } }); + await extrasFuture; } catch (e) { if (!mounted) return; setState(() { @@ -127,7 +171,7 @@ class _HomeScreenState extends State { Widget build(BuildContext context) { final s = context.strings; return RefreshIndicator( - onRefresh: _load, + onRefresh: () => _load(force: true), child: CustomScrollView( physics: const AlwaysScrollableScrollPhysics( parent: BouncingScrollPhysics(), @@ -176,7 +220,7 @@ class _HomeScreenState extends State { badgeLabel: _unreadNotifications > 9 ? '9+' : '$_unreadNotifications', onPressed: () async { await context.push('/notifications'); - if (mounted) _load(); + if (mounted) _refreshUnread(); }, ), const SizedBox(width: 4), @@ -204,27 +248,35 @@ class _HomeScreenState extends State { padding: const EdgeInsets.fromLTRB(20, 8, 20, 32), sliver: SliverList( delegate: SliverChildListDelegate([ - HomeAdCarousel(ads: _heroAds, loading: _loading) - .animate() - .fadeIn(duration: 350.ms) - .slideY(begin: 0.04, end: 0), + _heroAds.isEmpty + ? HomeAdCarousel( + ads: _heroAds, + loading: _loading && _heroAds.isEmpty, + ) + .animate() + .fadeIn(duration: 350.ms) + .slideY(begin: 0.04, end: 0) + : HomeAdCarousel( + ads: _heroAds, + loading: false, + ), const SizedBox(height: 22), _SectionTitle(title: s.playNow, subtitle: s.playNowSubtitle), const SizedBox(height: 12), - if (_loading) - const SizedBox( - height: 110, - child: Center(child: CircularProgressIndicator(strokeWidth: 2.5)), - ) - else if (_games.isEmpty) - _FeaturedPredictCard(onTap: () => context.go('/predict')) - else + if (_games.isNotEmpty) ..._games.take(4).map( (g) => Padding( padding: const EdgeInsets.only(bottom: 10), child: _GameCard(game: g, onTap: () => _openGame(g)), ), - ), + ) + else if (_loading) + const SizedBox( + height: 110, + child: Center(child: CircularProgressIndicator(strokeWidth: 2.5)), + ) + else + _FeaturedPredictCard(onTap: () => context.go('/predict')), const SizedBox(height: 8), _SectionTitle(title: s.shortcuts, subtitle: s.shortcutsSubtitle), const SizedBox(height: 12), @@ -263,7 +315,7 @@ class _HomeScreenState extends State { _TwoFaPromptCard( onTap: () async { await context.push('/totp-setup'); - if (mounted) _load(); + if (mounted) _refreshTotp(); }, ), ], diff --git a/prediqo_mobile/lib/features/home/presentation/widgets/home_ad_carousel.dart b/prediqo_mobile/lib/features/home/presentation/widgets/home_ad_carousel.dart index 71ad63a5..4967a454 100644 --- a/prediqo_mobile/lib/features/home/presentation/widgets/home_ad_carousel.dart +++ b/prediqo_mobile/lib/features/home/presentation/widgets/home_ad_carousel.dart @@ -67,6 +67,9 @@ class _HomeAdCarouselState extends State { @override Widget build(BuildContext context) { final s = context.strings; + if (widget.ads.isNotEmpty) { + return _buildCarousel(); + } if (widget.loading) { return Container( height: 200, @@ -78,33 +81,33 @@ class _HomeAdCarouselState extends State { ); } - if (widget.ads.isEmpty) { - return Container( - height: 180, - padding: const EdgeInsets.all(24), - decoration: BoxDecoration( - borderRadius: BorderRadius.circular(22), - gradient: LinearGradient( - begin: Alignment.topLeft, - end: Alignment.bottomRight, - colors: [ - AppColors.primary.withValues(alpha: 0.22), - AppColors.surfaceCard, - ], - ), - border: Border.all(color: AppColors.border), + return Container( + height: 180, + padding: const EdgeInsets.all(24), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(22), + gradient: LinearGradient( + begin: Alignment.topLeft, + end: Alignment.bottomRight, + colors: [ + AppColors.primary.withValues(alpha: 0.22), + AppColors.surfaceCard, + ], ), - alignment: Alignment.center, - child: Text( - s.promotionsComingSoon, - textAlign: TextAlign.center, - style: Theme.of(context).textTheme.bodyMedium?.copyWith( - color: AppColors.textSecondary, - ), - ), - ); - } + border: Border.all(color: AppColors.border), + ), + alignment: Alignment.center, + child: Text( + s.promotionsComingSoon, + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.bodyMedium?.copyWith( + color: AppColors.textSecondary, + ), + ), + ); + } + Widget _buildCarousel() { return Column( children: [ SizedBox( @@ -188,6 +191,12 @@ class _AdSlide extends StatelessWidget { Image.network( ad.imageUrl!, fit: BoxFit.cover, + gaplessPlayback: true, + filterQuality: FilterQuality.low, + cacheWidth: (MediaQuery.sizeOf(context).width * + MediaQuery.devicePixelRatioOf(context)) + .round() + .clamp(240, 1080), opacity: const AlwaysStoppedAnimation(0.38), errorBuilder: (_, __, ___) => const SizedBox.shrink(), ), diff --git a/prediqo_mobile/lib/features/prediction/bloc/prediction_bloc.dart b/prediqo_mobile/lib/features/prediction/bloc/prediction_bloc.dart index c3b1b831..ef399172 100644 --- a/prediqo_mobile/lib/features/prediction/bloc/prediction_bloc.dart +++ b/prediqo_mobile/lib/features/prediction/bloc/prediction_bloc.dart @@ -8,6 +8,7 @@ import '../../../data/models/prediction_models.dart'; import '../../../data/repositories/prediction_repository_impl.dart'; import '../../../data/repositories/wallet_repository_impl.dart'; import '../../../domain/repositories/prediction_repository.dart'; +import '../utils/prediction_history_filter_store.dart'; import '../utils/server_adjusted_countdown.dart'; part 'prediction_event.dart'; @@ -39,8 +40,8 @@ class PredictionBloc extends Bloc { on(_onRefreshTick, transformer: _sequential()); on(_onWsMessage); on(_onSocketStatusChanged); - on(_onHistoryPage); - on(_onHistoryFilterChanged); + on(_onHistoryPage, transformer: _sequential()); + on(_onHistoryFilterChanged, transformer: _sequential()); on(_onOlderCandles); on(_onPaused); on(_onResumed); @@ -66,14 +67,139 @@ class PredictionBloc extends Bloc { static const historyPageSize = 5; static const _pollJitterRatio = 0.12; - Future _fetchHistoryPage(int page) { + final historyFilterStore = PredictionHistoryFilterStore(); + + String _historyKey({ + int? intervalMinutes, + required String? wallet, + required String? status, + }) => + PredictionHistoryFilterStore.key( + intervalMinutes: intervalMinutes ?? state.selectedIntervalMinutes, + wallet: wallet, + status: status, + ); + + bool _isCurrentHistoryContext({ + required int intervalMinutes, + String? wallet, + String? status, + }) => + state.selectedIntervalMinutes == intervalMinutes && + state.historyWalletFilter == wallet && + state.historyStatusFilter == status; + + void _rememberHistory( + List items, { + required int page, + required int totalPages, + int? intervalMinutes, + String? wallet, + String? status, + }) { + historyFilterStore.put( + _historyKey( + intervalMinutes: intervalMinutes, + wallet: wallet ?? state.historyWalletFilter, + status: status ?? state.historyStatusFilter, + ), + PredictionHistoryFilterPage( + items: items, + page: page, + totalPages: totalPages, + ), + ); + } + + List _applyLiveHistoryOverlays(List items) { + final liveMulti = state.gameState?.userMultiBet; + final liveBet = state.gameState?.userBet; + var next = items; + if (liveMulti != null) { + next = _historyWithMultiProgress(next, liveMulti); + } + if (liveBet != null) { + next = _historyWithPrediction(next, liveBet); + } + return next; + } + + Future _fetchHistoryPage( + int page, { + int? intervalMinutes, + String? wallet, + String? status, + }) { return _repo.getMyBets( page: page, pageSize: historyPageSize, - intervalMinutes: state.selectedIntervalMinutes, + intervalMinutes: intervalMinutes ?? state.selectedIntervalMinutes, + stakeAccountKind: wallet ?? state.historyWalletFilter, + status: status ?? state.historyStatusFilter, ); } + Future _refreshHistoryFromServer( + Emitter emit, { + int page = 1, + bool append = false, + bool showSpinnerIfEmpty = true, + }) async { + final interval = state.selectedIntervalMinutes; + final wallet = state.historyWalletFilter; + final status = state.historyStatusFilter; + if (append || (showSpinnerIfEmpty && state.history.isEmpty)) { + emit(state.copyWith(isLoadingHistory: true)); + } + try { + final result = await _fetchHistoryPage( + page, + intervalMinutes: interval, + wallet: wallet, + status: status, + ); + if (!_isCurrentHistoryContext( + intervalMinutes: interval, + wallet: wallet, + status: status, + )) { + return; + } + final merged = append + ? [ + ...state.history, + ...result.items.where((item) => state.history.every((h) => h.id != item.id)), + ] + : result.items; + final items = append ? merged : _applyLiveHistoryOverlays(merged); + final reachedEnd = append && result.items.isEmpty; + final nextPage = reachedEnd ? state.historyPage : result.page; + final nextTotal = reachedEnd ? state.historyTotalPages : result.totalPages; + _rememberHistory( + items, + page: nextPage, + totalPages: nextTotal, + intervalMinutes: interval, + wallet: wallet, + status: status, + ); + emit(state.copyWith( + history: items, + historyPage: nextPage, + historyTotalPages: nextTotal, + isLoadingHistory: false, + )); + } catch (_) { + if (_isCurrentHistoryContext( + intervalMinutes: interval, + wallet: wallet, + status: status, + )) { + emit(state.copyWith(isLoadingHistory: false)); + } + } + } + bool _matchesHistoryFilters(PredictionModel p) { if (state.historyWalletFilter != null && p.stakeAccountKind != state.historyWalletFilter) { @@ -349,8 +475,15 @@ class PredictionBloc extends Bloc { try { final interval = state.selectedIntervalMinutes; + final historyWallet = state.historyWalletFilter; + final historyStatus = state.historyStatusFilter; final stateFuture = _repo.getState(intervalMinutes: interval); - final historyFuture = _soft(_fetchHistoryPage(1)); + final historyFuture = _soft(_fetchHistoryPage( + 1, + intervalMinutes: interval, + wallet: historyWallet, + status: historyStatus, + )); final balancesFuture = _soft(_loadBalances(state.gameState?.config.walletTypeCode)); final gameState = await stateFuture; @@ -400,28 +533,45 @@ class PredictionBloc extends Bloc { final history = await historyFuture; final labels = await balancesFuture; - final liveMulti = state.gameState?.userMultiBet; - final historyItems = history == null - ? state.history - : (liveMulti != null - ? _historyWithMultiProgress(history.items, liveMulti) - : history.items); - - emit(state.copyWith( - history: historyItems, - historyPage: history?.page, - historyTotalPages: history?.totalPages, - mainBalanceLabel: labels?.mainLabel, - bonusBalanceLabel: labels?.bonusLabel, - testBalanceLabel: labels?.testLabel, - mainAvailable: labels?.main, - bonusAvailable: labels?.bonus, - testAvailable: labels?.test, - )); + if (_isCurrentHistoryContext( + intervalMinutes: interval, + wallet: historyWallet, + status: historyStatus, + ) && + history != null) { + final historyItems = _applyLiveHistoryOverlays(history.items); + _rememberHistory( + historyItems, + page: history.page, + totalPages: history.totalPages, + intervalMinutes: interval, + wallet: historyWallet, + status: historyStatus, + ); + emit(state.copyWith( + history: historyItems, + historyPage: history.page, + historyTotalPages: history.totalPages, + mainBalanceLabel: labels?.mainLabel, + bonusBalanceLabel: labels?.bonusLabel, + testBalanceLabel: labels?.testLabel, + mainAvailable: labels?.main, + bonusAvailable: labels?.bonus, + testAvailable: labels?.test, + )); + } else if (labels != null) { + emit(state.copyWith( + mainBalanceLabel: labels.mainLabel, + bonusBalanceLabel: labels.bonusLabel, + testBalanceLabel: labels.testLabel, + mainAvailable: labels.main, + bonusAvailable: labels.bonus, + testAvailable: labels.test, + )); + } _lastFullStateSyncMs = DateTime.now().millisecondsSinceEpoch; _healthyPollSkips = 0; - await _fillHistoryUntilFilterMatches(emit); _startPolling(); } catch (e) { emit(state.copyWith( @@ -502,11 +652,22 @@ class PredictionBloc extends Bloc { Future _onIntervalChanged(PredictionIntervalChanged event, Emitter emit) async { final prevInterval = state.selectedIntervalMinutes; final gs = state.gameState; + final cached = historyFilterStore.peek( + _historyKey( + intervalMinutes: event.minutes, + wallet: state.historyWalletFilter, + status: state.historyStatusFilter, + ), + ); emit(state.copyWith( selectedIntervalMinutes: event.minutes, candles: const [], hasMoreOlderCandles: true, isLoadingOlderCandles: true, + history: cached?.items ?? const [], + historyPage: cached?.page ?? 1, + historyTotalPages: cached?.totalPages ?? 1, + isLoadingHistory: cached == null, gameState: gs?.copyWith( selectedIntervalMinutes: event.minutes, clearRound: true, @@ -735,6 +896,7 @@ class PredictionBloc extends Bloc { ? _parseStakeKind(multi.stakeAccountKind) : state.stakeAccountKind, )); + _rememberHistory(history, page: state.historyPage, totalPages: state.historyTotalPages); _lastFullStateSyncMs = nowMs; if (hasActiveMulti || multi != null || autoOn || userBetChanged || autoPlaced) { @@ -803,6 +965,7 @@ class PredictionBloc extends Bloc { ? _parseStakeKind(next.userMultiBet!.stakeAccountKind) : state.stakeAccountKind, )); + _rememberHistory(history, page: state.historyPage, totalPages: state.historyTotalPages); if (next.autoSettings?.enabled == true) { _startPolling(); } @@ -875,6 +1038,7 @@ class PredictionBloc extends Bloc { playMode: PredictionPlayMode.multi, stakeAccountKind: _parseStakeKind(parsed.stakeAccountKind), )); + _rememberHistory(history, page: state.historyPage, totalPages: state.historyTotalPages); _startPolling(); } else if (multi == null) { emit(state.copyWith(gameState: gs.copyWith(clearUserMultiBet: true))); @@ -955,6 +1119,7 @@ class PredictionBloc extends Bloc { ? _parseStakeKind(bet.stakeAccountKind) : state.stakeAccountKind, )); + _rememberHistory(history, page: state.historyPage, totalPages: state.historyTotalPages); } add(const PredictionBalancesRefreshRequested()); add(const PredictionHistoryPageRequested(1)); @@ -1003,74 +1168,39 @@ class PredictionBloc extends Bloc { } Future _onHistoryPage(PredictionHistoryPageRequested event, Emitter emit) async { - emit(state.copyWith(isLoadingHistory: true)); - try { - final page = await _fetchHistoryPage(event.page); - final nextHistory = event.append - ? [ - ...state.history, - ...page.items.where((item) => state.history.every((h) => h.id != item.id)), - ] - : page.items; - final reachedEnd = event.append && page.items.isEmpty; - emit(state.copyWith( - history: nextHistory, - historyPage: reachedEnd ? state.historyPage : page.page, - historyTotalPages: reachedEnd ? state.historyPage : page.totalPages, - isLoadingHistory: false, - )); - await _fillHistoryUntilFilterMatches(emit); - } catch (_) { - emit(state.copyWith(isLoadingHistory: false)); - } + await _refreshHistoryFromServer( + emit, + page: event.page, + append: event.append, + showSpinnerIfEmpty: !event.append, + ); } Future _onHistoryFilterChanged( PredictionHistoryFilterChanged event, Emitter emit, ) async { + final cached = historyFilterStore.peek( + _historyKey( + wallet: event.walletFilter, + status: event.statusFilter, + ), + ); emit(state.copyWith( historyWalletFilter: event.walletFilter, historyStatusFilter: event.statusFilter, clearHistoryWalletFilter: event.walletFilter == null, clearHistoryStatusFilter: event.statusFilter == null, + history: cached?.items ?? const [], + historyPage: cached?.page ?? 1, + historyTotalPages: cached?.totalPages ?? 1, + isLoadingHistory: cached == null, )); - await _fillHistoryUntilFilterMatches(emit); - } - - /// When a filter is active and the loaded pages have no matches, keep loading - /// older pages until a match appears or the history is fully loaded. - Future _fillHistoryUntilFilterMatches(Emitter emit) async { - final hasFilter = - state.historyWalletFilter != null || state.historyStatusFilter != null; - if (!hasFilter) return; - - var guard = 0; - while (guard < 50) { - guard++; - if (state.history.any(_matchesHistoryFilters)) return; - if (state.historyPage >= state.historyTotalPages) return; - - emit(state.copyWith(isLoadingHistory: true)); - try { - final page = await _fetchHistoryPage(state.historyPage + 1); - final nextHistory = [ - ...state.history, - ...page.items.where((item) => state.history.every((h) => h.id != item.id)), - ]; - final reachedEnd = page.items.isEmpty; - emit(state.copyWith( - history: nextHistory, - historyPage: reachedEnd ? state.historyPage : page.page, - historyTotalPages: reachedEnd ? state.historyPage : page.totalPages, - isLoadingHistory: false, - )); - if (reachedEnd) return; - } catch (_) { - emit(state.copyWith(isLoadingHistory: false)); - return; - } - } + await _refreshHistoryFromServer( + emit, + page: 1, + showSpinnerIfEmpty: cached == null, + ); } Future _onOlderCandles(PredictionCandlesOlderRequested event, Emitter emit) async { diff --git a/prediqo_mobile/lib/features/prediction/presentation/prediction_games_screen.dart b/prediqo_mobile/lib/features/prediction/presentation/prediction_games_screen.dart index bf6e13e0..ec83c375 100644 --- a/prediqo_mobile/lib/features/prediction/presentation/prediction_games_screen.dart +++ b/prediqo_mobile/lib/features/prediction/presentation/prediction_games_screen.dart @@ -25,36 +25,53 @@ class _PredictionGamesScreenState extends State { bool _loading = true; String? _error; List _games = []; + bool _predictionPrefetchScheduled = false; @override void initState() { super.initState(); + final cached = sl().peekLast(); + if (cached != null && cached.isNotEmpty) { + _games = cached; + _loading = false; + _schedulePredictionPrefetch(); + } _load(); + } + + void _schedulePredictionPrefetch() { + if (_predictionPrefetchScheduled) return; + _predictionPrefetchScheduled = true; WidgetsBinding.instance.addPostFrameCallback((_) { if (!mounted) return; context.read().add(const PredictionLoadRequested(ifStale: true)); }); } - Future _load() async { - setState(() { - _loading = true; - _error = null; - }); + Future _load({bool force = false}) async { + final keepList = _games.isNotEmpty && !force; + if (!keepList) { + setState(() { + _loading = true; + _error = null; + }); + } try { - final games = await sl().list(); + final games = await sl().list(force: force); if (!mounted) return; setState(() { _games = games; _loading = false; + _error = null; }); } catch (e) { if (!mounted) return; setState(() { - _error = e.toString().replaceFirst(RegExp(r'^Exception:\s*'), ''); + _error = keepList ? _error : e.toString().replaceFirst(RegExp(r'^Exception:\s*'), ''); _loading = false; }); } + _schedulePredictionPrefetch(); } void _openGame(GameCatalogItem game) { @@ -71,7 +88,7 @@ class _PredictionGamesScreenState extends State { return Scaffold( key: const Key('prediction_games_screen'), body: RefreshIndicator( - onRefresh: _load, + onRefresh: () => _load(force: true), child: CustomScrollView( physics: const AlwaysScrollableScrollPhysics( parent: BouncingScrollPhysics(), @@ -108,7 +125,7 @@ class _PredictionGamesScreenState extends State { children: [ Text(_error!, textAlign: TextAlign.center), const SizedBox(height: 12), - FilledButton(onPressed: _load, child: Text(s.retry)), + FilledButton(onPressed: () => _load(force: true), child: Text(s.retry)), ], ), ), diff --git a/prediqo_mobile/lib/features/prediction/presentation/prediction_screen.dart b/prediqo_mobile/lib/features/prediction/presentation/prediction_screen.dart index e5616522..6cb6eafe 100644 --- a/prediqo_mobile/lib/features/prediction/presentation/prediction_screen.dart +++ b/prediqo_mobile/lib/features/prediction/presentation/prediction_screen.dart @@ -238,27 +238,14 @@ class _PredictionScreenState extends State with WidgetsBinding const SizedBox(height: 12), Builder( builder: (context) { - final filtered = state.history.where((p) { - if (state.historyWalletFilter != null && - p.stakeAccountKind != state.historyWalletFilter) { - return false; - } - if (state.historyStatusFilter != null && - p.status != state.historyStatusFilter) { - return false; - } - return true; - }).toList(); + final filtered = state.history; final canLoadMore = state.historyPage < state.historyTotalPages; final hasFilters = state.historyWalletFilter != null || state.historyStatusFilter != null; - // End label only after a multi-page history was fully loaded. final showEndLabel = !canLoadMore && state.historyTotalPages > 1 && filtered.isNotEmpty; - // While a filter has no matches, auto-load hides the manual button. - final showLoadMore = canLoadMore && - !(hasFilters && filtered.isEmpty); + final showLoadMore = canLoadMore; if (state.isLoadingHistory && state.history.isEmpty) { return const Padding( diff --git a/prediqo_mobile/lib/features/prediction/utils/prediction_history_filter_store.dart b/prediqo_mobile/lib/features/prediction/utils/prediction_history_filter_store.dart new file mode 100644 index 00000000..cdfa8154 --- /dev/null +++ b/prediqo_mobile/lib/features/prediction/utils/prediction_history_filter_store.dart @@ -0,0 +1,38 @@ +import '../../../data/models/prediction_models.dart'; + +class PredictionHistoryFilterPage { + const PredictionHistoryFilterPage({ + required this.items, + required this.page, + required this.totalPages, + }); + + final List items; + final int page; + final int totalPages; +} + +/// Last known Recent-predictions page, keyed by interval + chip filters. +/// Not a blind TTL skip: opening a chip always refetches; this only paints instantly. +class PredictionHistoryFilterStore { + final Map _pages = {}; + + static String key({ + required int intervalMinutes, + String? wallet, + String? status, + }) => + '$intervalMinutes|${wallet ?? ''}|${status ?? ''}'; + + PredictionHistoryFilterPage? peek(String key) => _pages[key]; + + void put(String key, PredictionHistoryFilterPage page) => _pages[key] = page; + + void invalidate([String? key]) { + if (key == null) { + _pages.clear(); + } else { + _pages.remove(key); + } + } +} diff --git a/prediqo_mobile/lib/features/wallet/bloc/wallet_bloc.dart b/prediqo_mobile/lib/features/wallet/bloc/wallet_bloc.dart index 1ba75cb2..ade67757 100644 --- a/prediqo_mobile/lib/features/wallet/bloc/wallet_bloc.dart +++ b/prediqo_mobile/lib/features/wallet/bloc/wallet_bloc.dart @@ -6,13 +6,21 @@ import 'package:equatable/equatable.dart'; import 'package:dio/dio.dart'; import '../../../core/errors/app_exception.dart'; import '../../../data/models/balance_model.dart'; +import '../../../data/models/test_wallet_models.dart'; import '../../../data/models/transaction_model.dart'; import '../../../data/models/wallet_type_model.dart'; +import '../../../data/repositories/share_card_repository.dart'; import '../../../data/repositories/wallet_repository_impl.dart'; +import '../../../domain/repositories/health_repository.dart'; +import '../../../domain/repositories/referral_repository.dart'; part 'wallet_event.dart'; part 'wallet_state.dart'; +EventTransformer _sequential() { + return (events, mapper) => events.asyncExpand(mapper); +} + /// Extracts a user-friendly message from an error (e.g. API {"error": "..."}). String _errorMessage(Object e) { if (e is DioException) { @@ -30,36 +38,291 @@ String? _errorCode(Object e) { /// Manages wallet data and money-movement operations via [WalletRepositoryImpl]. class WalletBloc extends Bloc { - /// Creates a [WalletBloc] backed by [walletRepo]. - WalletBloc(this._walletRepo) : super(const WalletState.initial()) { - on(_onLoad); + /// Creates a [WalletBloc] backed by wallet, health, and referral APIs. + WalletBloc( + this._walletRepo, + this._healthRepo, + this._referralRepo, { + ShareCardRepository? shareCards, + }) : _shareCards = shareCards, + super(const WalletState.initial()) { + on(_onLoad, transformer: _sequential()); + on(_onActivity, transformer: _sequential()); + on(_onActivityMore, transformer: _sequential()); on(_onDepositAddress); on(_onWithdraw); on(_onTransfer); on(_onClearFeedback); } - final WalletRepositoryImpl _walletRepo; + final WalletRepository _walletRepo; + final HealthRepository _healthRepo; + final ReferralRepository _referralRepo; + final ShareCardRepository? _shareCards; - /// Loads wallet types, balances, and recent transactions from the API. - Future _onLoad(WalletLoadRequested event, Emitter emit) async { - emit(state.copyWith(isLoading: true, clearError: true)); + static const activityPageSize = 10; + static const _freshBalanceSyncMs = 5000; + static const _freshActivitySyncMs = 45000; + + int _lastFullStateSyncMs = 0; + final Map _lastActivitySyncMs = {}; + + Future _soft(Future future) async { try { - final types = await _walletRepo.getWalletTypes(); - final balances = await _walletRepo.getBalances(); - final txs = await _walletRepo.getTransactions(limit: 30); + return await future; + } catch (_) { + return null; + } + } + + bool _activityIsFresh(String category) { + final page = state.activityFor(category); + final lastMs = _lastActivitySyncMs[category] ?? 0; + return page.loaded && + DateTime.now().millisecondsSinceEpoch - lastMs < _freshActivitySyncMs; + } + + void _invalidateAfterLedgerMutation() { + _lastActivitySyncMs.clear(); + _shareCards?.invalidateConfig(); + } + + /// Warm Withdrawals / Transfers after the first paint. Never Predictions. + void _scheduleQuietActivityPrefetch() { + if (!_activityIsFresh('withdrawals')) { + add(const WalletActivityRequested(category: 'withdrawals')); + } + if (!_activityIsFresh('transfers')) { + add(const WalletActivityRequested(category: 'transfers')); + } + } + + Future _emitDepositsPrefetch( + Emitter emit, { + required bool force, + }) async { + if (!force && _activityIsFresh('deposits')) return; + final page = state.deposits; + if (page.loading) return; + emit(state.copyWith( + deposits: page.copyWith(loading: page.items.isEmpty, clearError: true), + )); + try { + final list = await _walletRepo.getTransactions( + limit: activityPageSize, + offset: 0, + category: 'deposits', + ); + emit(state.copyWith( + deposits: WalletActivityPage( + items: list, + loaded: true, + loading: false, + hasMore: list.length >= activityPageSize, + ), + )); + _lastActivitySyncMs['deposits'] = DateTime.now().millisecondsSinceEpoch; + } catch (e) { + emit(state.copyWith( + deposits: page.copyWith(loading: false, error: _errorMessage(e)), + )); + } + } + + /// Loads types + balances + extras in parallel. Prefetches Deposits only. + Future _onLoad(WalletLoadRequested event, Emitter emit) async { + final nowMs = DateTime.now().millisecondsSinceEpoch; + final balancesFresh = state.balances.isNotEmpty && + nowMs - _lastFullStateSyncMs < _freshBalanceSyncMs; + + if (event.ifStale && balancesFresh) { + if (!_activityIsFresh('deposits')) { + await _emitDepositsPrefetch(emit, force: false); + } + _scheduleQuietActivityPrefetch(); + return; + } + + if (!event.ifStale) { + _invalidateAfterLedgerMutation(); + } + + final keepExistingUi = state.balances.isNotEmpty; + if (!keepExistingUi) { + emit(state.copyWith(isLoading: true, clearError: true)); + } else { + emit(state.copyWith(clearError: true)); + } + + try { + final typesFuture = _soft(_walletRepo.getWalletTypes()); + final balancesFuture = _walletRepo.getBalances(); + final extrasFuture = _loadExtras(); + final depositsFuture = _walletRepo.getTransactions( + limit: activityPageSize, + offset: 0, + category: 'deposits', + ); + + final depositsPage = state.deposits; + if (depositsPage.items.isEmpty) { + emit(state.copyWith( + deposits: depositsPage.copyWith(loading: true, clearError: true), + )); + } + + final balances = await balancesFuture; emit(state.copyWith( - walletTypes: types, balances: balances, - transactions: txs, isLoading: false, clearError: true, )); + + try { + final list = await depositsFuture; + emit(state.copyWith( + deposits: WalletActivityPage( + items: list, + loaded: true, + loading: false, + hasMore: list.length >= activityPageSize, + ), + )); + _lastActivitySyncMs['deposits'] = DateTime.now().millisecondsSinceEpoch; + } catch (_) {} + + _scheduleQuietActivityPrefetch(); + + final types = await typesFuture; + if (types != null && types.isNotEmpty) { + emit(state.copyWith(walletTypes: types)); + } + + final extras = await extrasFuture; + emit(state.copyWith( + testWalletStatus: extras.testWalletStatus, + bonusWithdrawable: extras.bonusWithdrawable, + withdrawalsEnabled: extras.withdrawalsEnabled, + withdrawalFeeRaw: extras.withdrawalFeeRaw, + healthLoaded: extras.healthLoaded, + )); + + _lastFullStateSyncMs = DateTime.now().millisecondsSinceEpoch; } catch (e) { - emit(state.copyWith(isLoading: false, errorMessage: _errorMessage(e))); + emit(state.copyWith( + isLoading: false, + errorMessage: keepExistingUi ? state.errorMessage : _errorMessage(e), + )); } } + Future< + ({ + TestWalletStatusModel? testWalletStatus, + bool? bonusWithdrawable, + bool withdrawalsEnabled, + String withdrawalFeeRaw, + bool healthLoaded, + })> _loadExtras() async { + final testFuture = _soft(_walletRepo.getTestWalletStatus()); + final bonusFuture = _soft(_referralRepo.getBonusBalances()); + final healthFuture = _soft(_healthRepo.getHealth()); + final test = await testFuture; + final bonus = await bonusFuture; + final health = await healthFuture; + return ( + testWalletStatus: test ?? state.testWalletStatus, + bonusWithdrawable: bonus?.bonusWithdrawable ?? state.bonusWithdrawable, + withdrawalsEnabled: health?.withdrawalsEnabled ?? state.withdrawalsEnabled, + withdrawalFeeRaw: health?.withdrawalNetworkFeeRaw ?? state.withdrawalFeeRaw, + healthLoaded: health != null || state.healthLoaded, + ); + } + + Future _onActivity( + WalletActivityRequested event, + Emitter emit, + ) async { + final category = event.category; + if (!_isActivityCategory(category)) return; + final nowMs = DateTime.now().millisecondsSinceEpoch; + final page = state.activityFor(category); + final lastMs = _lastActivitySyncMs[category] ?? 0; + if (!event.force && + page.loaded && + nowMs - lastMs < _freshActivitySyncMs) { + return; + } + if (page.loading && !event.force) return; + + emit(state.copyWithActivity( + category, + page.copyWith(loading: page.items.isEmpty, clearError: true), + )); + try { + final list = await _walletRepo.getTransactions( + limit: activityPageSize, + offset: 0, + category: category, + ); + emit(state.copyWithActivity( + category, + WalletActivityPage( + items: list, + loaded: true, + loading: false, + hasMore: list.length >= activityPageSize, + ), + )); + _lastActivitySyncMs[category] = DateTime.now().millisecondsSinceEpoch; + } catch (e) { + emit(state.copyWithActivity( + category, + page.copyWith(loading: false, error: _errorMessage(e)), + )); + } + } + + Future _onActivityMore( + WalletActivityMoreRequested event, + Emitter emit, + ) async { + final category = event.category; + if (!_isActivityCategory(category)) return; + final page = state.activityFor(category); + if (page.loading || page.loadingMore || !page.hasMore) return; + + emit(state.copyWithActivity(category, page.copyWith(loadingMore: true))); + try { + final list = await _walletRepo.getTransactions( + limit: activityPageSize, + offset: page.items.length, + category: category, + ); + emit(state.copyWithActivity( + category, + page.copyWith( + items: [...page.items, ...list], + hasMore: list.length >= activityPageSize, + loadingMore: false, + loaded: true, + ), + )); + } catch (e) { + emit(state.copyWithActivity( + category, + page.copyWith(loadingMore: false, error: _errorMessage(e)), + )); + } + } + + bool _isActivityCategory(String category) { + return category == 'deposits' || + category == 'withdrawals' || + category == 'transfers' || + category == 'predictions'; + } + /// Fetches a blockchain deposit address for the given wallet type code. Future _onDepositAddress(WalletDepositAddressRequested event, Emitter emit) async { final s = state; @@ -90,6 +353,7 @@ class WalletBloc extends Bloc { ); emit(state.copyWith(withdrawTxId: result.transactionId, withdrawStatus: result.status)); add(const WalletLoadRequested()); + add(const WalletActivityRequested(category: 'withdrawals', force: true)); } catch (e) { emit(state.copyWith( errorMessage: _errorMessage(e), @@ -115,6 +379,7 @@ class WalletBloc extends Bloc { ); emit(state.copyWith(transferTxId: result.transactionId, transferStatus: result.status)); add(const WalletLoadRequested()); + add(const WalletActivityRequested(category: 'transfers', force: true)); } catch (e) { emit(state.copyWith( errorMessage: _errorMessage(e), diff --git a/prediqo_mobile/lib/features/wallet/bloc/wallet_event.dart b/prediqo_mobile/lib/features/wallet/bloc/wallet_event.dart index d66cf401..e7712b66 100644 --- a/prediqo_mobile/lib/features/wallet/bloc/wallet_event.dart +++ b/prediqo_mobile/lib/features/wallet/bloc/wallet_event.dart @@ -7,9 +7,36 @@ abstract class WalletEvent extends Equatable { List get props => []; } -/// Reloads wallet types, balances, and recent transactions. +/// Reloads wallet types, balances, and extras (not Activity lists). class WalletLoadRequested extends WalletEvent { - const WalletLoadRequested(); + const WalletLoadRequested({this.ifStale = false}); + + /// Skip the network round-trip when a sync finished a few seconds ago. + final bool ifStale; + + @override + List get props => [ifStale]; +} + +/// Loads one Activity tab on demand (deposits / withdrawals / transfers / predictions). +class WalletActivityRequested extends WalletEvent { + const WalletActivityRequested({required this.category, this.force = false}); + + final String category; + final bool force; + + @override + List get props => [category, force]; +} + +/// Appends the next Activity page for [category]. +class WalletActivityMoreRequested extends WalletEvent { + const WalletActivityMoreRequested({required this.category}); + + final String category; + + @override + List get props => [category]; } /// Requests a deposit address for the given asset code (e.g. TRX, USDT). diff --git a/prediqo_mobile/lib/features/wallet/bloc/wallet_state.dart b/prediqo_mobile/lib/features/wallet/bloc/wallet_state.dart index 5b92d6aa..ec4b9a28 100644 --- a/prediqo_mobile/lib/features/wallet/bloc/wallet_state.dart +++ b/prediqo_mobile/lib/features/wallet/bloc/wallet_state.dart @@ -1,11 +1,61 @@ part of 'wallet_bloc.dart'; +/// One Activity tab (cached in the app-scoped [WalletBloc]). +class WalletActivityPage extends Equatable { + const WalletActivityPage({ + this.items = const [], + this.loading = false, + this.loadingMore = false, + this.loaded = false, + this.hasMore = true, + this.error, + }); + + final List items; + final bool loading; + final bool loadingMore; + final bool loaded; + final bool hasMore; + final String? error; + + WalletActivityPage copyWith({ + List? items, + bool? loading, + bool? loadingMore, + bool? loaded, + bool? hasMore, + String? error, + bool clearError = false, + }) { + return WalletActivityPage( + items: items ?? this.items, + loading: loading ?? this.loading, + loadingMore: loadingMore ?? this.loadingMore, + loaded: loaded ?? this.loaded, + hasMore: hasMore ?? this.hasMore, + error: clearError ? null : (error ?? this.error), + ); + } + + @override + List get props => [items, loading, loadingMore, loaded, hasMore, error]; +} + /// Immutable wallet UI state: balances, transactions, and operation results. class WalletState extends Equatable { const WalletState({ this.walletTypes = const [], this.balances = const [], this.transactions = const [], + this.deposits = const WalletActivityPage(), + this.withdrawals = const WalletActivityPage(), + this.transfers = const WalletActivityPage(), + this.predictions = const WalletActivityPage(), + this.testWalletStatus, + this.bonusWithdrawable, + this.withdrawalsEnabled = false, + this.withdrawalFeeRaw = '0', + this.healthLoaded = false, this.depositAddress, this.depositWalletType, this.withdrawTxId, @@ -37,6 +87,15 @@ class WalletState extends Equatable { final List walletTypes; final List balances; final List transactions; + final WalletActivityPage deposits; + final WalletActivityPage withdrawals; + final WalletActivityPage transfers; + final WalletActivityPage predictions; + final TestWalletStatusModel? testWalletStatus; + final bool? bonusWithdrawable; + final bool withdrawalsEnabled; + final String withdrawalFeeRaw; + final bool healthLoaded; final String? depositAddress; final WalletTypeModel? depositWalletType; final String? withdrawTxId; @@ -47,6 +106,19 @@ class WalletState extends Equatable { final String? errorCode; final bool isLoading; + WalletActivityPage activityFor(String category) { + switch (category) { + case 'withdrawals': + return withdrawals; + case 'transfers': + return transfers; + case 'predictions': + return predictions; + default: + return deposits; + } + } + /// Whether wallet types have been loaded and the bloc is not in a loading state. bool get isLoaded => walletTypes.isNotEmpty && !isLoading; @@ -55,6 +127,15 @@ class WalletState extends Equatable { List? walletTypes, List? balances, List? transactions, + WalletActivityPage? deposits, + WalletActivityPage? withdrawals, + WalletActivityPage? transfers, + WalletActivityPage? predictions, + TestWalletStatusModel? testWalletStatus, + bool? bonusWithdrawable, + bool? withdrawalsEnabled, + String? withdrawalFeeRaw, + bool? healthLoaded, String? depositAddress, WalletTypeModel? depositWalletType, String? withdrawTxId, @@ -73,6 +154,15 @@ class WalletState extends Equatable { walletTypes: walletTypes ?? this.walletTypes, balances: balances ?? this.balances, transactions: transactions ?? this.transactions, + deposits: deposits ?? this.deposits, + withdrawals: withdrawals ?? this.withdrawals, + transfers: transfers ?? this.transfers, + predictions: predictions ?? this.predictions, + testWalletStatus: testWalletStatus ?? this.testWalletStatus, + bonusWithdrawable: bonusWithdrawable ?? this.bonusWithdrawable, + withdrawalsEnabled: withdrawalsEnabled ?? this.withdrawalsEnabled, + withdrawalFeeRaw: withdrawalFeeRaw ?? this.withdrawalFeeRaw, + healthLoaded: healthLoaded ?? this.healthLoaded, depositAddress: clearDeposit ? null : (depositAddress ?? this.depositAddress), depositWalletType: clearDeposit ? null : (depositWalletType ?? this.depositWalletType), withdrawTxId: clearWithdraw ? null : (withdrawTxId ?? this.withdrawTxId), @@ -85,11 +175,33 @@ class WalletState extends Equatable { ); } + WalletState copyWithActivity(String category, WalletActivityPage page) { + switch (category) { + case 'withdrawals': + return copyWith(withdrawals: page); + case 'transfers': + return copyWith(transfers: page); + case 'predictions': + return copyWith(predictions: page); + default: + return copyWith(deposits: page); + } + } + @override List get props => [ walletTypes, balances, transactions, + deposits, + withdrawals, + transfers, + predictions, + testWalletStatus, + bonusWithdrawable, + withdrawalsEnabled, + withdrawalFeeRaw, + healthLoaded, depositAddress, depositWalletType, withdrawTxId, diff --git a/prediqo_mobile/lib/features/wallet/presentation/deposit_asset_select_screen.dart b/prediqo_mobile/lib/features/wallet/presentation/deposit_asset_select_screen.dart index d7c41a73..aa0989f1 100644 --- a/prediqo_mobile/lib/features/wallet/presentation/deposit_asset_select_screen.dart +++ b/prediqo_mobile/lib/features/wallet/presentation/deposit_asset_select_screen.dart @@ -22,7 +22,7 @@ class _DepositAssetSelectScreenState extends State { @override void initState() { super.initState(); - context.read().add(const WalletLoadRequested()); + context.read().add(const WalletLoadRequested(ifStale: true)); } @override diff --git a/prediqo_mobile/lib/features/wallet/presentation/transfer_screen.dart b/prediqo_mobile/lib/features/wallet/presentation/transfer_screen.dart index 63a9806e..c20b643c 100644 --- a/prediqo_mobile/lib/features/wallet/presentation/transfer_screen.dart +++ b/prediqo_mobile/lib/features/wallet/presentation/transfer_screen.dart @@ -38,7 +38,7 @@ class _TransferScreenState extends State { @override void initState() { super.initState(); - context.read().add(const WalletLoadRequested()); + context.read().add(const WalletLoadRequested(ifStale: true)); _loadSecurityContext(); } diff --git a/prediqo_mobile/lib/features/wallet/presentation/wallet_overview_screen.dart b/prediqo_mobile/lib/features/wallet/presentation/wallet_overview_screen.dart index 9e2497c3..6b8d1aaf 100644 --- a/prediqo_mobile/lib/features/wallet/presentation/wallet_overview_screen.dart +++ b/prediqo_mobile/lib/features/wallet/presentation/wallet_overview_screen.dart @@ -11,8 +11,8 @@ import '../../../core/utils/amount_utils.dart'; import '../../../data/models/balance_model.dart'; import '../../../data/models/test_wallet_models.dart'; import '../../../data/models/transaction_model.dart'; +import '../../../data/repositories/share_card_repository.dart'; import '../../../data/repositories/wallet_repository_impl.dart'; -import '../../../domain/repositories/health_repository.dart'; import '../../../domain/repositories/referral_repository.dart'; import '../../../l10n/app_strings.dart'; import '../../../shared/widgets/app_snackbar.dart'; @@ -41,57 +41,27 @@ class _WalletOverviewScreenState extends State late final TabController _tabController; bool _hideBalance = false; bool _prefsLoaded = false; - TestWalletStatusModel? _testWalletStatus; bool _requestingTestCredits = false; - bool? _bonusWithdrawable; bool _transferringBonus = false; - bool _withdrawalsEnabled = false; - String _withdrawalFeeRaw = '0'; - bool _healthLoaded = false; - - final Map _histories = { - 'deposits': _CategoryHistory(), - 'withdrawals': _CategoryHistory(), - 'transfers': _CategoryHistory(), - 'predictions': _CategoryHistory(), - }; static const _categories = ['deposits', 'withdrawals', 'transfers', 'predictions']; - static const _pageSize = 10; @override void initState() { super.initState(); _tabController = TabController(length: 4, vsync: this); _tabController.addListener(_onTabChanged); - context.read().add(const WalletLoadRequested()); + context.read().add(const WalletLoadRequested(ifStale: true)); _loadHidePreference(); - _loadTestWalletStatus(); - _loadBonusPolicy(); - _loadWithdrawHealth(); WidgetsBinding.instance.addPostFrameCallback((_) { - _ensureCategoryLoaded(_categories[_tabController.index]); + if (!mounted) return; + sl().getConfig(); + context.read().add( + WalletActivityRequested(category: _categories[_tabController.index]), + ); }); } - Future _loadWithdrawHealth() async { - try { - final health = await sl().getHealth(); - if (!mounted) return; - setState(() { - _withdrawalsEnabled = health.withdrawalsEnabled; - _withdrawalFeeRaw = health.withdrawalNetworkFeeRaw; - _healthLoaded = true; - }); - } catch (_) { - if (!mounted) return; - setState(() { - _withdrawalsEnabled = false; - _healthLoaded = true; - }); - } - } - @override void dispose() { _tabController.removeListener(_onTabChanged); @@ -108,26 +78,6 @@ class _WalletOverviewScreenState extends State }); } - Future _loadTestWalletStatus() async { - try { - final status = await sl().getTestWalletStatus(); - if (!mounted) return; - setState(() => _testWalletStatus = status); - } catch (_) { - // Best-effort: keep the card usable without the request button status. - } - } - - Future _loadBonusPolicy() async { - try { - final result = await sl().getBonusBalances(); - if (!mounted) return; - setState(() => _bonusWithdrawable = result.bonusWithdrawable); - } catch (_) { - // Best-effort: leave transfer option hidden until policy is known. - } - } - Future _transferBonusToMain(BalanceModel balance) async { if (_transferringBonus) return; final amountRaw = balance.bonusAvailable; @@ -141,7 +91,6 @@ class _WalletOverviewScreenState extends State if (!mounted) return; showSuccessSnackBar(context, context.strings.bonusTransferSuccess); context.read().add(const WalletLoadRequested()); - await _loadBonusPolicy(); } catch (e) { if (!mounted) return; showErrorSnackBar(context, _friendlyError(e)); @@ -158,7 +107,6 @@ class _WalletOverviewScreenState extends State if (!mounted) return; showSuccessSnackBar(context, result.message); context.read().add(const WalletLoadRequested()); - await _loadTestWalletStatus(); } catch (e) { if (!mounted) return; showErrorSnackBar(context, _friendlyError(e)); @@ -177,82 +125,23 @@ class _WalletOverviewScreenState extends State void _onTabChanged() { if (_tabController.indexIsChanging) return; setState(() {}); - _ensureCategoryLoaded(_categories[_tabController.index]); + context.read().add( + WalletActivityRequested(category: _categories[_tabController.index]), + ); } - Future _ensureCategoryLoaded(String category, {bool force = false}) async { - final history = _histories[category]!; - if (!force && (history.loading || history.loaded)) return; - setState(() { - history.loading = true; - history.error = null; - if (force) { - history.items = []; - history.loaded = false; - history.hasMore = true; - } - }); - try { - final list = await sl().getTransactions( - limit: _pageSize, - offset: 0, - category: category, - ); - if (!mounted) return; - setState(() { - history.items = list; - history.loaded = true; - history.loading = false; - history.hasMore = list.length >= _pageSize; - }); - } catch (e) { - if (!mounted) return; - setState(() { - history.loading = false; - history.error = _friendlyError(e); - }); - } - } - - Future _loadMore(String category) async { - final history = _histories[category]!; - if (history.loading || history.loadingMore || !history.hasMore) return; - setState(() => history.loadingMore = true); - try { - final list = await sl().getTransactions( - limit: _pageSize, - offset: history.items.length, - category: category, - ); - if (!mounted) return; - setState(() { - history.items = [...history.items, ...list]; - history.hasMore = list.length >= _pageSize; - history.loadingMore = false; - }); - } catch (e) { - if (!mounted) return; - setState(() { - history.loadingMore = false; - history.error = _friendlyError(e); - }); - } + void _loadMore(String category) { + context.read().add(WalletActivityMoreRequested(category: category)); } Future _refreshAll() async { - context.read().add(const WalletLoadRequested()); - await Future.wait([ - _loadTestWalletStatus(), - _loadBonusPolicy(), - _loadWithdrawHealth(), - ]); - for (final key in _histories.keys) { - final history = _histories[key]!; - history.loaded = false; - history.hasMore = true; - history.loadingMore = false; + final bloc = context.read(); + bloc.add(const WalletLoadRequested()); + final category = _categories[_tabController.index]; + if (category != 'deposits') { + bloc.add(WalletActivityRequested(category: category, force: true)); } - await _ensureCategoryLoaded(_categories[_tabController.index], force: true); + await Future.delayed(const Duration(milliseconds: 350)); } BalanceModel? _usdtBalance(List balances) { @@ -277,7 +166,7 @@ class _WalletOverviewScreenState extends State final balance = _usdtBalance(state.balances); final loading = state.isLoading && state.balances.isEmpty; final category = _categories[_tabController.index]; - final history = _histories[category]!; + final history = state.activityFor(category); // Single CustomScrollView (no NestedScrollView) — NestedScrollView + TabBarView // triggers a known Android overscroll assertion (`activity!.isScrolling`). @@ -321,10 +210,10 @@ class _WalletOverviewScreenState extends State (t) => t.withdrawEnabled == true, ); final eligibility = computeWithdrawEligibility( - withdrawalsEnabled: _withdrawalsEnabled, + withdrawalsEnabled: state.withdrawalsEnabled, hasWithdrawNetwork: hasRail, availableRaw: balance.available, - feeRaw: _withdrawalFeeRaw, + feeRaw: state.withdrawalFeeRaw, ); String? withdrawReason; if (!eligibility.allowed) { @@ -373,9 +262,9 @@ class _WalletOverviewScreenState extends State _WalletAction( icon: Icons.south_west_rounded, label: s.withdraw, - enabled: _healthLoaded && eligibility.allowed, + enabled: state.healthLoaded && eligibility.allowed, onTap: () { - if (!_healthLoaded || !eligibility.allowed) { + if (!state.healthLoaded || !eligibility.allowed) { showAppSnackBar( context, message: withdrawReason ?? @@ -416,7 +305,7 @@ class _WalletOverviewScreenState extends State icon: Icons.card_giftcard_rounded, footer: _BonusWalletFooter( bonusAvailableRaw: balance.bonusAvailable, - bonusWithdrawable: _bonusWithdrawable, + bonusWithdrawable: state.bonusWithdrawable, transferring: _transferringBonus, onTransfer: () => _transferBonusToMain(balance), ), @@ -434,7 +323,7 @@ class _WalletOverviewScreenState extends State accentDeep: AppColors.walletTestDeep, icon: Icons.science_rounded, footer: _TestWalletRequestFooter( - status: _testWalletStatus, + status: state.testWalletStatus, requesting: _requestingTestCredits, onRequest: _requestTestCredits, ), @@ -481,7 +370,7 @@ class _WalletOverviewScreenState extends State List _historySlivers({ required BuildContext context, - required _CategoryHistory history, + required WalletActivityPage history, required String category, required BalanceModel? balance, }) { @@ -595,15 +484,6 @@ class _WalletOverviewScreenState extends State } } -class _CategoryHistory { - List items = []; - bool loading = false; - bool loadingMore = false; - bool loaded = false; - bool hasMore = true; - String? error; -} - enum _HistoryMode { status, prediction } class _WalletAction { diff --git a/prediqo_mobile/lib/features/wallet/presentation/withdraw_screen.dart b/prediqo_mobile/lib/features/wallet/presentation/withdraw_screen.dart index 1b607c02..b5b03cda 100644 --- a/prediqo_mobile/lib/features/wallet/presentation/withdraw_screen.dart +++ b/prediqo_mobile/lib/features/wallet/presentation/withdraw_screen.dart @@ -36,7 +36,7 @@ class _WithdrawScreenState extends State { @override void initState() { super.initState(); - context.read().add(const WalletLoadRequested()); + context.read().add(const WalletLoadRequested(ifStale: true)); _loadNetworkFee(); } diff --git a/prediqo_mobile/lib/features/welcome/presentation/welcome_screen.dart b/prediqo_mobile/lib/features/welcome/presentation/welcome_screen.dart index 5a1bff35..3512a039 100644 --- a/prediqo_mobile/lib/features/welcome/presentation/welcome_screen.dart +++ b/prediqo_mobile/lib/features/welcome/presentation/welcome_screen.dart @@ -34,8 +34,22 @@ class _WelcomeScreenState extends State { @override void initState() { super.initState(); + final cachedGames = sl().peekLast(); + if (cachedGames != null && cachedGames.isNotEmpty) { + _games = cachedGames; + } + final cachedAds = sl().peekLast(placement: 'home_hero'); + if (cachedAds != null && cachedAds.isNotEmpty) { + _heroAds = cachedAds; + } + if (_heroAds.isNotEmpty || _games.isNotEmpty) { + _loading = false; + } _load(); - _checkAppUpdate(); + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + _checkAppUpdate(); + }); } Future _checkAppUpdate() async { @@ -44,23 +58,36 @@ class _WelcomeScreenState extends State { setState(() => _updateAvailable = available); } - Future _load() async { - setState(() => _loading = true); + Future _load({bool force = false}) async { + final keep = (_heroAds.isNotEmpty || _games.isNotEmpty) && !force; + if (!keep) { + setState(() => _loading = true); + } try { - final results = await Future.wait([ - sl().list(placement: 'home_hero').catchError( - (_) => [], - ), - sl().list().catchError( - (_) => [], - ), - ]); - if (!mounted) return; - setState(() { - _heroAds = results[0] as List; - _games = results[1] as List; - _loading = false; + final adsFuture = sl() + .list(placement: 'home_hero', force: force) + .catchError((_) => _heroAds); + final gamesFuture = + sl().list(force: force).catchError((_) => _games); + + adsFuture.then((ads) { + if (!mounted) return; + setState(() { + _heroAds = ads; + _loading = false; + }); }); + gamesFuture.then((games) { + if (!mounted) return; + setState(() { + _games = games; + _loading = false; + }); + }); + + await Future.wait([adsFuture, gamesFuture]); + if (!mounted) return; + setState(() => _loading = false); } catch (_) { if (!mounted) return; setState(() => _loading = false); @@ -181,7 +208,7 @@ class _WelcomeScreenState extends State { const SizedBox(height: 22), HomeAdCarousel( ads: _heroAds, - loading: _loading, + loading: _loading && _heroAds.isEmpty, onAdTap: (_) => _goLogin(), ), const SizedBox(height: 22), @@ -227,12 +254,22 @@ class _WelcomeScreenState extends State { ), ), const SizedBox(height: 12), - if (_loading) + if (_games.isNotEmpty) + ..._games.take(4).map( + (g) => Padding( + padding: const EdgeInsets.only(bottom: 10), + child: _WelcomeGameCard( + game: g, + onTap: _goLogin, + ), + ), + ) + else if (_loading) const SizedBox( height: 80, child: Center(child: CircularProgressIndicator(strokeWidth: 2.5)), ) - else if (_games.isEmpty) + else PredCard( onTap: _goLogin, padding: const EdgeInsets.all(16), @@ -251,17 +288,7 @@ class _WelcomeScreenState extends State { ), ], ), - ) - else - ..._games.take(4).map( - (g) => Padding( - padding: const EdgeInsets.only(bottom: 10), - child: _WelcomeGameCard( - game: g, - onTap: _goLogin, - ), - ), - ), + ), const SizedBox(height: 22), PredCard( onTap: () => context.push('/faq'), diff --git a/prediqo_mobile/lib/shared/widgets/prediqo_logo.dart b/prediqo_mobile/lib/shared/widgets/prediqo_logo.dart index 1bdedcee..046a10ca 100644 --- a/prediqo_mobile/lib/shared/widgets/prediqo_logo.dart +++ b/prediqo_mobile/lib/shared/widgets/prediqo_logo.dart @@ -63,11 +63,57 @@ class _FallbackMark extends StatelessWidget { borderRadius: BorderRadius.circular(size * 0.22), border: Border.all(color: AppColors.accentGold, width: 1.5), ), - child: Icon( - Icons.auto_awesome_rounded, - size: size * 0.45, - color: AppColors.primaryLight, + child: CustomPaint( + size: Size(size, size), + painter: _TlMarkPainter(), ), ); } } + +/// Fallback fused T+L mark when the brand PNG is unavailable. +class _TlMarkPainter extends CustomPainter { + @override + void paint(Canvas canvas, Size size) { + final s = size.shortestSide; + final paint = Paint() + ..color = AppColors.primary + ..style = PaintingStyle.fill; + + final path = Path() + ..moveTo(s * 0.28, s * 0.19) + ..lineTo(s * 0.66, s * 0.19) + ..cubicTo(s * 0.74, s * 0.19, s * 0.80, s * 0.25, s * 0.80, s * 0.32) + ..cubicTo(s * 0.80, s * 0.39, s * 0.74, s * 0.45, s * 0.66, s * 0.45) + ..lineTo(s * 0.42, s * 0.45) + ..lineTo(s * 0.42, s * 0.56) + ..lineTo(s * 0.61, s * 0.56) + ..cubicTo(s * 0.70, s * 0.56, s * 0.76, s * 0.62, s * 0.76, s * 0.70) + ..cubicTo(s * 0.76, s * 0.77, s * 0.70, s * 0.83, s * 0.61, s * 0.83) + ..lineTo(s * 0.28, s * 0.83) + ..cubicTo(s * 0.20, s * 0.83, s * 0.13, s * 0.77, s * 0.13, s * 0.70) + ..lineTo(s * 0.13, s * 0.32) + ..cubicTo(s * 0.13, s * 0.25, s * 0.20, s * 0.19, s * 0.28, s * 0.19) + ..close(); + + canvas.drawPath(path, paint); + + final spark = Paint()..color = AppColors.accentGold; + final c = Offset(s * 0.50, s * 0.35); + final r = s * 0.035; + final star = Path() + ..moveTo(c.dx, c.dy - r * 1.6) + ..lineTo(c.dx + r * 0.35, c.dy - r * 0.35) + ..lineTo(c.dx + r * 1.6, c.dy) + ..lineTo(c.dx + r * 0.35, c.dy + r * 0.35) + ..lineTo(c.dx, c.dy + r * 1.6) + ..lineTo(c.dx - r * 0.35, c.dy + r * 0.35) + ..lineTo(c.dx - r * 1.6, c.dy) + ..lineTo(c.dx - r * 0.35, c.dy - r * 0.35) + ..close(); + canvas.drawPath(star, spark); + } + + @override + bool shouldRepaint(covariant CustomPainter oldDelegate) => false; +} diff --git a/prediqo_mobile/pubspec.yaml b/prediqo_mobile/pubspec.yaml index ba5b0dfe..c6897042 100644 --- a/prediqo_mobile/pubspec.yaml +++ b/prediqo_mobile/pubspec.yaml @@ -44,6 +44,7 @@ dev_dependencies: flutter_launcher_icons: android: true ios: true + remove_alpha_ios: true image_path: assets/brand/prediqo-app-icon.png adaptive_icon_background: "#0B0F1A" adaptive_icon_foreground: assets/brand/prediqo-app-icon.png diff --git a/prediqo_mobile/test/advertisement_store_test.dart b/prediqo_mobile/test/advertisement_store_test.dart new file mode 100644 index 00000000..5f1edd31 --- /dev/null +++ b/prediqo_mobile/test/advertisement_store_test.dart @@ -0,0 +1,65 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:prediqo_mobile/data/models/advertisement_models.dart'; +import 'package:prediqo_mobile/data/repositories/advertisement_repository_impl.dart'; + +AdvertisementModel _ad(String id) => AdvertisementModel( + id: id, + placement: 'home_hero', + title: 'Welcome bonus', + accentColor: '#10B981', + sortOrder: 0, + ); + +void main() { + test('coalesces parallel list() into a single fetch', () async { + final store = AdvertisementStore(); + var fetches = 0; + Future> fetch() async { + fetches++; + await Future.delayed(const Duration(milliseconds: 20)); + return [_ad('a1')]; + } + + final results = await Future.wait([ + store.get(fetch), + store.get(fetch), + store.get(fetch), + ]); + + expect(fetches, 1); + expect(store.fetchStarts, 1); + expect(results, everyElement(hasLength(1))); + }); + + test('returns the fresh snapshot without refetching', () async { + final store = AdvertisementStore(); + var fetches = 0; + Future> fetch() async { + fetches++; + return [_ad('a1')]; + } + + await store.get(fetch); + final again = await store.get(fetch); + + expect(fetches, 1); + expect(again.single.id, 'a1'); + expect(store.peekFresh(), isNotNull); + expect(store.peekLast(), isNotNull); + }); + + test('force bypasses the fresh cache', () async { + final store = AdvertisementStore(); + var fetches = 0; + Future> fetch() async { + fetches++; + return [_ad('a$fetches')]; + } + + await store.get(fetch); + final forced = await store.get(fetch, force: true); + + expect(fetches, 2); + expect(forced.single.id, 'a2'); + }); +} diff --git a/prediqo_mobile/test/game_catalog_store_test.dart b/prediqo_mobile/test/game_catalog_store_test.dart new file mode 100644 index 00000000..6fcbbfbb --- /dev/null +++ b/prediqo_mobile/test/game_catalog_store_test.dart @@ -0,0 +1,79 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:prediqo_mobile/data/models/game_catalog_models.dart'; +import 'package:prediqo_mobile/data/repositories/game_catalog_repository_impl.dart'; + +GameCatalogItem _item(String id) => GameCatalogItem( + id: id, + slug: 'candle-predict', + title: 'Candle Predict', + category: 'prediction', + accentColor: '#10B981', + status: 'active', + isFeatured: true, + sortOrder: 0, + implementationKey: 'candle-predict', + ); + +void main() { + test('coalesces parallel list() into a single fetch', () async { + final store = GameCatalogStore(); + var fetches = 0; + Future> fetch() async { + fetches++; + await Future.delayed(const Duration(milliseconds: 20)); + return [_item('g1')]; + } + + final results = await Future.wait([ + store.get(fetch), + store.get(fetch), + store.get(fetch), + ]); + + expect(fetches, 1); + expect(store.fetchStarts, 1); + expect(results, everyElement(hasLength(1))); + }); + + test('returns the fresh snapshot without refetching', () async { + final store = GameCatalogStore(); + var fetches = 0; + Future> fetch() async { + fetches++; + return [_item('g1')]; + } + + await store.get(fetch); + final again = await store.get(fetch); + + expect(fetches, 1); + expect(again.single.id, 'g1'); + expect(store.peekFresh(), isNotNull); + expect(store.peekLast(), isNotNull); + }); + + test('peekLast keeps the last list after invalidate of freshness only via TTL miss', () async { + final store = GameCatalogStore(); + await store.get(() async => [_item('g1')]); + expect(store.peekLast()?.single.id, 'g1'); + store.invalidate(); + expect(store.peekLast(), isNull); + expect(store.peekFresh(), isNull); + }); + + test('force bypasses the fresh cache', () async { + final store = GameCatalogStore(); + var fetches = 0; + Future> fetch() async { + fetches++; + return [_item('g$fetches')]; + } + + await store.get(fetch); + final forced = await store.get(fetch, force: true); + + expect(fetches, 2); + expect(forced.single.id, 'g2'); + expect(store.peekLast()?.single.id, 'g2'); + }); +} diff --git a/prediqo_mobile/test/prediction_history_filter_test.dart b/prediqo_mobile/test/prediction_history_filter_test.dart new file mode 100644 index 00000000..a3408a21 --- /dev/null +++ b/prediqo_mobile/test/prediction_history_filter_test.dart @@ -0,0 +1,182 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:prediqo_mobile/core/config/app_config.dart'; +import 'package:prediqo_mobile/core/network/api_client.dart'; +import 'package:prediqo_mobile/core/realtime/game_socket_service.dart'; +import 'package:prediqo_mobile/data/models/prediction_models.dart'; +import 'package:prediqo_mobile/data/repositories/wallet_repository_impl.dart'; +import 'package:prediqo_mobile/domain/repositories/prediction_repository.dart'; +import 'package:prediqo_mobile/features/prediction/bloc/prediction_bloc.dart'; + +PredictionModel _bet({ + required String id, + String wallet = 'main', + String status = 'won', +}) => + PredictionModel( + id: id, + direction: 'long', + stakeDisplay: 1, + status: status, + payoutDisplay: 1.9, + createdAt: '2026-09-24T18:00:00.000Z', + stakeAccountKind: wallet, + ); + +class _RecordingPredictionRepo implements PredictionRepository { + final calls = <({int page, String? wallet, String? status})>[]; + Duration delay = const Duration(milliseconds: 20); + Map> pagesByFilter = {}; + + String _key(String? wallet, String? status) => '${wallet ?? ''}|${status ?? ''}'; + + @override + Future getMyBets({ + int page = 1, + int pageSize = 5, + int? intervalMinutes, + String? stakeAccountKind, + String? status, + }) async { + calls.add((page: page, wallet: stakeAccountKind, status: status)); + await Future.delayed(delay); + final items = pagesByFilter[_key(stakeAccountKind, status)] ?? const []; + return PredictionsPageModel( + items: items, + total: items.length, + page: page, + totalPages: 1, + ); + } + + @override + Future getState({int? intervalMinutes}) async => + throw UnimplementedError(); + + @override + Future getCandlesPage({ + int? intervalMinutes, + int limit = 60, + int? beforeOpenMs, + }) async => + throw UnimplementedError(); + + @override + Future placeBet({ + required String direction, + required double stakeAmount, + required int intervalMinutes, + String stakeAccountKind = 'main', + }) async {} + + @override + Future placeMultiBet({ + required int level, + required List sequence, + required double stakeAmount, + required int intervalMinutes, + String stakeAccountKind = 'main', + }) async {} + + @override + Future saveAutoSettings(Map body) async => + throw UnimplementedError(); +} + +PredictionBloc _bloc(_RecordingPredictionRepo repo) { + const config = AppConfig( + apiBaseUrl: 'http://localhost', + isProduction: false, + wsEnabled: false, + ); + final api = ApiClient(config: config); + return PredictionBloc( + repo, + GameSocketService(config, api), + WalletRepositoryImpl(api), + ); +} + +void main() { + test('sends wallet and status filters to the server on chip change', () async { + final repo = _RecordingPredictionRepo() + ..pagesByFilter = { + 'test|': [_bet(id: 't1', wallet: 'test')], + '|won': [_bet(id: 'w1', status: 'won')], + }; + final bloc = _bloc(repo); + + bloc.add(const PredictionHistoryFilterChanged(walletFilter: 'test')); + await bloc.stream.firstWhere( + (s) => s.historyWalletFilter == 'test' && s.history.any((p) => p.id == 't1'), + ); + expect(repo.calls.single.wallet, 'test'); + expect(repo.calls.single.status, isNull); + expect(repo.calls.single.page, 1); + + bloc.add(const PredictionHistoryFilterChanged(statusFilter: 'won')); + await bloc.stream.firstWhere( + (s) => s.historyStatusFilter == 'won' && s.history.any((p) => p.id == 'w1'), + ); + expect(repo.calls.last.wallet, isNull); + expect(repo.calls.last.status, 'won'); + expect(repo.calls.where((c) => c.page > 1), isEmpty); + + await bloc.close(); + }); + + test('paints the last list immediately then refreshes that chip', () async { + final repo = _RecordingPredictionRepo() + ..pagesByFilter = { + '|': [_bet(id: 'all1')], + 'test|': [_bet(id: 't-old', wallet: 'test')], + }; + final bloc = _bloc(repo); + + bloc.add(const PredictionHistoryFilterChanged(walletFilter: 'test')); + await bloc.stream.firstWhere((s) => s.history.any((p) => p.id == 't-old')); + + bloc.add(const PredictionHistoryFilterChanged()); + await bloc.stream.firstWhere((s) => s.historyWalletFilter == null && s.history.any((p) => p.id == 'all1')); + + repo.pagesByFilter['test|'] = [_bet(id: 't-fresh', wallet: 'test')]; + repo.delay = const Duration(milliseconds: 30); + + bloc.add(const PredictionHistoryFilterChanged(walletFilter: 'test')); + final painted = await bloc.stream.firstWhere((s) => s.historyWalletFilter == 'test'); + expect(painted.history.single.id, 't-old'); + expect(painted.isLoadingHistory, isFalse); + + final refreshed = await bloc.stream.firstWhere( + (s) => s.history.any((p) => p.id == 't-fresh'), + ); + expect(refreshed.history.single.id, 't-fresh'); + expect( + repo.calls.where((c) => c.wallet == 'test').every((c) => c.page == 1), + isTrue, + ); + + await bloc.close(); + }); + + test('first visit of a chip shows a spinner instead of another chip list', () async { + final repo = _RecordingPredictionRepo() + ..pagesByFilter = { + '|': [_bet(id: 'all1')], + 'main|': [_bet(id: 'm1')], + }; + final bloc = _bloc(repo); + + bloc.add(const PredictionHistoryPageRequested(1)); + await bloc.stream.firstWhere((s) => s.history.any((p) => p.id == 'all1')); + + bloc.add(const PredictionHistoryFilterChanged(walletFilter: 'main')); + final switching = await bloc.stream.firstWhere((s) => s.historyWalletFilter == 'main'); + expect(switching.history, isEmpty); + expect(switching.isLoadingHistory, isTrue); + + final loaded = await bloc.stream.firstWhere((s) => s.history.any((p) => p.id == 'm1')); + expect(loaded.history.single.id, 'm1'); + + await bloc.close(); + }); +} diff --git a/prediqo_mobile/test/share_config_store_test.dart b/prediqo_mobile/test/share_config_store_test.dart new file mode 100644 index 00000000..758f14a7 --- /dev/null +++ b/prediqo_mobile/test/share_config_store_test.dart @@ -0,0 +1,71 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:prediqo_mobile/data/models/share_card_models.dart'; +import 'package:prediqo_mobile/data/repositories/share_card_repository.dart'; + +ShareCardConfig _config({bool hasDeposited = false}) => ShareCardConfig( + enabled: true, + allowMainWallet: true, + allowBonusWallet: true, + allowTestWallet: true, + allowWon: true, + allowLost: true, + allowRefunded: true, + walletOpsEnabled: true, + allowDeposit: true, + allowWithdrawal: true, + allowTransfer: true, + testWalletShareRequiresRealDeposit: true, + hasDeposited: hasDeposited, + ); + +void main() { + test('coalesces parallel getConfig into a single fetch', () async { + final store = ShareConfigStore(); + var fetches = 0; + Future fetch() async { + fetches++; + await Future.delayed(const Duration(milliseconds: 20)); + return _config(); + } + + final results = await Future.wait([ + store.get(fetch), + store.get(fetch), + store.get(fetch), + ]); + + expect(fetches, 1); + expect(store.fetchStarts, 1); + expect(results, everyElement(isA())); + }); + + test('TTL cache returns the same snapshot without a second fetch', () async { + final store = ShareConfigStore(); + var fetches = 0; + Future fetch() async { + fetches++; + return _config(); + } + + await store.get(fetch); + await store.get(fetch); + expect(fetches, 1); + }); + + test('invalidate drops cache so a mutation can see hasDeposited', () async { + final store = ShareConfigStore(); + var fetches = 0; + Future fetch() async { + fetches++; + return _config(hasDeposited: fetches > 1); + } + + final first = await store.get(fetch); + expect(first.hasDeposited, isFalse); + + store.invalidate(); + final second = await store.get(fetch); + expect(second.hasDeposited, isTrue); + expect(fetches, 2); + }); +} diff --git a/prediqo_mobile/test/support/e2e_fixtures.dart b/prediqo_mobile/test/support/e2e_fixtures.dart index fd247c13..78d4b5a1 100644 --- a/prediqo_mobile/test/support/e2e_fixtures.dart +++ b/prediqo_mobile/test/support/e2e_fixtures.dart @@ -13,6 +13,7 @@ import 'package:prediqo_mobile/data/models/prediction_models.dart'; import 'package:prediqo_mobile/data/models/referral_models.dart'; import 'package:prediqo_mobile/data/repositories/admin_repository_impl.dart'; import 'package:prediqo_mobile/data/repositories/auth_repository_impl.dart'; +import 'package:prediqo_mobile/data/repositories/share_card_repository.dart'; import 'package:prediqo_mobile/data/repositories/wallet_repository_impl.dart'; import 'package:prediqo_mobile/domain/repositories/advertisement_repository.dart'; import 'package:prediqo_mobile/domain/repositories/faq_repository.dart'; @@ -400,7 +401,16 @@ class FakeFaqRepository implements FaqRepository { class FakeAdvertisementRepository implements AdvertisementRepository { @override - Future> list({String? placement}) async => const [ + List? peekCached({String? placement}) => null; + + @override + List? peekLast({String? placement}) => null; + + @override + void invalidate({String? placement}) {} + + @override + Future> list({String? placement, bool force = false}) async => const [ AdvertisementModel( id: 'ad-1', placement: 'home_hero', @@ -432,7 +442,16 @@ class FakeNotificationRepository implements NotificationRepository { class FakeGameCatalogRepository implements GameCatalogRepository { @override - Future> list({bool? featured}) async => const [ + List? peekCached({bool featured = false}) => null; + + @override + List? peekLast({bool featured = false}) => null; + + @override + void invalidate() {} + + @override + Future> list({bool? featured, bool force = false}) async => const [ GameCatalogItem( id: 'g1', slug: 'candle-predict', @@ -482,8 +501,17 @@ Future setupE2eDependencies({bool loggedIn = false, bool wsEnabled = false sl.registerLazySingleton(() => FakeGameCatalogRepository()); sl.registerLazySingleton(() => GameSocketService(sl(), sl())); sl.registerLazySingleton(() => WalletRepositoryImpl(sl())); + sl.registerLazySingleton(() => sl()); + sl.registerLazySingleton(() => ShareCardRepository(sl())); sl.registerLazySingleton(() => AdminRepositoryImpl(sl())); sl.registerFactory(() => AuthBloc(sl())..add(const AuthCheckRequested())); - sl.registerFactory(() => WalletBloc(sl())); + sl.registerFactory( + () => WalletBloc( + sl(), + sl(), + sl(), + shareCards: sl(), + ), + ); sl.registerFactory(() => PredictionBloc(sl(), sl(), sl())); } diff --git a/prediqo_mobile/test/wallet_load_optimization_test.dart b/prediqo_mobile/test/wallet_load_optimization_test.dart new file mode 100644 index 00000000..ed644e32 --- /dev/null +++ b/prediqo_mobile/test/wallet_load_optimization_test.dart @@ -0,0 +1,315 @@ +import 'dart:async'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:prediqo_mobile/data/models/balance_model.dart'; +import 'package:prediqo_mobile/data/models/referral_models.dart'; +import 'package:prediqo_mobile/data/models/test_wallet_models.dart'; +import 'package:prediqo_mobile/data/models/transaction_model.dart'; +import 'package:prediqo_mobile/data/models/wallet_type_model.dart'; +import 'package:prediqo_mobile/data/repositories/wallet_repository_impl.dart'; +import 'package:prediqo_mobile/domain/repositories/health_repository.dart'; +import 'package:prediqo_mobile/domain/repositories/referral_repository.dart'; +import 'package:prediqo_mobile/features/wallet/bloc/wallet_bloc.dart'; + +const _usdt = WalletTypeModel( + id: 1, + code: 'USDT_TRC20', + name: 'USDT', + network: 'TRON', + decimals: 6, +); + +BalanceModel _balance({String available = '10690000'}) => BalanceModel( + walletType: _usdt, + available: available, + locked: '0', + bonusAvailable: '0', + testAvailable: '5000000', + ); + +TransactionModel _tx(String id) => TransactionModel( + id: id, + walletTypeId: 1, + type: 'deposit', + amount: '1000000', + fee: '0', + status: 'completed', + createdAt: '2026-09-24T10:00:00.000Z', + ); + +class _FakeWalletRepo implements WalletRepository { + int typesCalls = 0; + int balancesCalls = 0; + int txCalls = 0; + final List txCategories = []; + final List txOffsets = []; + + Completer? typesHold; + Completer? extrasHold; + List page = [_tx('d1')]; + + @override + Future> getWalletTypes() async { + typesCalls++; + if (typesHold != null) await typesHold!.future; + return const [_usdt]; + } + + @override + Future> getBalances() async { + balancesCalls++; + return [_balance()]; + } + + @override + Future> getTransactions({ + int limit = 50, + int offset = 0, + String? category, + }) async { + txCalls++; + txCategories.add(category); + txOffsets.add(offset); + return page; + } + + @override + Future getTestWalletStatus() async { + if (extrasHold != null) await extrasHold!.future; + return const TestWalletStatusModel( + enabled: true, + balanceRaw: '5000000', + walletTypeId: 1, + decimals: 6, + creditAmountRaw: '10000000', + maxRequests: 3, + requestsUsed: 0, + canRequest: true, + ); + } + + @override + Future requestTestCredits() async { + throw UnimplementedError(); + } + + @override + Future getDepositAddress(String walletType) async { + throw UnimplementedError(); + } + + @override + Future withdraw( + String walletType, + String toAddress, + String amount, { + String? totpCode, + }) async { + return const WithdrawResult(transactionId: 'w1', status: 'pending'); + } + + @override + Future transfer( + String toEmail, + String walletType, + String amount, { + String? totpCode, + }) async { + throw UnimplementedError(); + } +} + +class _FakeHealth implements HealthRepository { + Completer? hold; + + @override + Future getHealth() async { + if (hold != null) await hold!.future; + return const HealthStatus( + network: 'mainnet', + withdrawalsEnabled: true, + env: 'test', + withdrawalNetworkFeeRaw: '1000000', + ); + } +} + +class _FakeReferral implements ReferralRepository { + @override + Future getDashboard({int maxDepth = 10}) async { + throw UnimplementedError(); + } + + @override + Future getCommissions({int limit = 25, int offset = 0}) { + throw UnimplementedError(); + } + + @override + Future<({List balances, bool bonusWithdrawable})> getBonusBalances() async => + (balances: [], bonusWithdrawable: true); + + @override + Future transferBonusToMain({ + required int walletTypeId, + required String amountRaw, + }) async {} +} + +Future _settle() => Future.delayed(const Duration(milliseconds: 20)); + +void main() { + late _FakeWalletRepo wallet; + late _FakeHealth health; + late WalletBloc bloc; + + setUp(() { + wallet = _FakeWalletRepo(); + health = _FakeHealth(); + bloc = WalletBloc(wallet, health, _FakeReferral()); + }); + + tearDown(() async { + await bloc.close(); + }); + + test('emits balances before slower wallet-types (soldes d’abord)', () async { + wallet.typesHold = Completer(); + + bloc.add(const WalletLoadRequested()); + await bloc.stream.firstWhere((s) => s.balances.isNotEmpty); + + expect(bloc.state.balances.single.available, '10690000'); + expect(bloc.state.isLoading, isFalse); + expect(bloc.state.walletTypes, isEmpty); + + wallet.typesHold!.complete(); + await bloc.stream.firstWhere((s) => s.walletTypes.isNotEmpty); + expect(bloc.state.walletTypes, isNotEmpty); + }); + + test('full load prefetches Deposits then Withdrawals and Transfers, not Predictions', () async { + bloc.add(const WalletLoadRequested()); + await bloc.stream.firstWhere( + (s) => s.deposits.loaded && s.withdrawals.loaded && s.transfers.loaded, + ); + await _settle(); + + expect(wallet.balancesCalls, 1); + expect(wallet.txCategories, containsAll(['deposits', 'withdrawals', 'transfers'])); + expect(wallet.txCategories, isNot(contains('predictions'))); + expect(bloc.state.predictions.loaded, isFalse); + }); + + test('ifStale skips a second load within the short cache window', () async { + bloc.add(const WalletLoadRequested()); + await bloc.stream.firstWhere((s) => s.healthLoaded); + await _settle(); + expect(wallet.balancesCalls, 1); + + bloc.add(const WalletLoadRequested(ifStale: true)); + await _settle(); + expect(wallet.balancesCalls, 1); + }); + + test('Predictions stay on-demand and do not reload balances', () async { + bloc.add(const WalletLoadRequested()); + await bloc.stream.firstWhere( + (s) => s.deposits.loaded && s.withdrawals.loaded && s.transfers.loaded, + ); + final balanceCalls = wallet.balancesCalls; + final txBeforePredictions = wallet.txCalls; + + bloc.add(const WalletActivityRequested(category: 'predictions')); + await bloc.stream.firstWhere((s) => s.predictions.loaded); + expect(wallet.txCategories, contains('predictions')); + expect(wallet.txCalls, txBeforePredictions + 1); + expect(wallet.balancesCalls, balanceCalls); + }); + + test('Activity cache skips a repeat visit within the short window', () async { + bloc.add(const WalletActivityRequested(category: 'deposits')); + await bloc.stream.firstWhere((s) => s.deposits.loaded); + expect(wallet.txCalls, 1); + + bloc.add(const WalletActivityRequested(category: 'deposits')); + await _settle(); + expect(wallet.txCalls, 1); + }); + + test('Activity force refetch ignores the short cache', () async { + bloc.add(const WalletActivityRequested(category: 'deposits')); + await bloc.stream.firstWhere((s) => s.deposits.loaded); + + wallet.page = [_tx('forced')]; + bloc.add(const WalletActivityRequested(category: 'deposits', force: true)); + await bloc.stream.firstWhere((s) => + s.deposits.items.length == 1 && s.deposits.items.single.id == 'forced'); + expect(wallet.txCalls, 2); + }); + + test('Activity more appends the next page without a full wallet load', () async { + wallet.page = List.generate(10, (i) => _tx('p$i')); + bloc.add(const WalletActivityRequested(category: 'deposits')); + await bloc.stream.firstWhere((s) => s.deposits.loaded); + expect(bloc.state.deposits.hasMore, isTrue); + + wallet.page = [_tx('extra')]; + bloc.add(const WalletActivityMoreRequested(category: 'deposits')); + await bloc.stream.firstWhere((s) => s.deposits.items.length == 11); + + expect(wallet.txOffsets, [0, 10]); + expect(wallet.balancesCalls, 0); + expect(bloc.state.deposits.hasMore, isFalse); + }); + + test('WalletBloc can be constructed with the WalletRepository interface', () async { + final extra = WalletBloc(wallet, health, _FakeReferral()); + expect(extra, isA()); + await extra.close(); + }); + + test('slow extras do not block the first balances emit', () async { + health.hold = Completer(); + wallet.extrasHold = Completer(); + + bloc.add(const WalletLoadRequested()); + await bloc.stream.firstWhere((s) => s.balances.isNotEmpty); + + expect(bloc.state.healthLoaded, isFalse); + expect(bloc.state.testWalletStatus, isNull); + + health.hold!.complete(); + wallet.extrasHold!.complete(); + await bloc.stream.firstWhere((s) => s.healthLoaded); + expect(bloc.state.bonusWithdrawable, isTrue); + }); + + test('a withdrawal force-refetches the Withdrawals tab so the action is visible', () async { + bloc.add(const WalletLoadRequested()); + await bloc.stream.firstWhere((s) => s.walletTypes.isNotEmpty && s.withdrawals.loaded); + + wallet.page = [_tx('new-withdrawal')]; + bloc.add(const WalletWithdrawRequested( + walletType: 'USDT_TRC20', + toAddress: 'Txyz', + amount: '1000000', + )); + await bloc.stream.firstWhere( + (s) => s.withdrawals.items.any((t) => t.id == 'new-withdrawal'), + ); + }); + + test('force load invalidates Activity TTL and refetches Deposits', () async { + bloc.add(const WalletLoadRequested()); + await bloc.stream.firstWhere((s) => s.deposits.loaded); + final txAfterWarm = wallet.txCalls; + + wallet.page = [_tx('after-mutation')]; + bloc.add(const WalletLoadRequested()); + await bloc.stream.firstWhere( + (s) => s.deposits.items.any((t) => t.id == 'after-mutation'), + ); + expect(wallet.txCalls, greaterThan(txAfterWarm)); + }); +} diff --git a/prediqo_mobile/web/favicon.png b/prediqo_mobile/web/favicon.png index 0d67f0c0..f7cfe355 100644 Binary files a/prediqo_mobile/web/favicon.png and b/prediqo_mobile/web/favicon.png differ diff --git a/prediqo_mobile/web/icons/Icon-192.png b/prediqo_mobile/web/icons/Icon-192.png index 0e7a72ba..12f1b7f4 100644 Binary files a/prediqo_mobile/web/icons/Icon-192.png and b/prediqo_mobile/web/icons/Icon-192.png differ diff --git a/prediqo_mobile/web/icons/Icon-512.png b/prediqo_mobile/web/icons/Icon-512.png index 4c002a37..65d2b950 100644 Binary files a/prediqo_mobile/web/icons/Icon-512.png and b/prediqo_mobile/web/icons/Icon-512.png differ diff --git a/prediqo_mobile/web/icons/Icon-maskable-192.png b/prediqo_mobile/web/icons/Icon-maskable-192.png index 0e7a72ba..12f1b7f4 100644 Binary files a/prediqo_mobile/web/icons/Icon-maskable-192.png and b/prediqo_mobile/web/icons/Icon-maskable-192.png differ diff --git a/prediqo_mobile/web/icons/Icon-maskable-512.png b/prediqo_mobile/web/icons/Icon-maskable-512.png index 4c002a37..65d2b950 100644 Binary files a/prediqo_mobile/web/icons/Icon-maskable-512.png and b/prediqo_mobile/web/icons/Icon-maskable-512.png differ diff --git a/prediqo_web/index.html b/prediqo_web/index.html index bd408aa1..0b5b0794 100644 --- a/prediqo_web/index.html +++ b/prediqo_web/index.html @@ -2,9 +2,11 @@ + + + - - + Tloto diff --git a/prediqo_web/public/apple-touch-icon.png b/prediqo_web/public/apple-touch-icon.png new file mode 100644 index 00000000..c49bdf79 Binary files /dev/null and b/prediqo_web/public/apple-touch-icon.png differ diff --git a/prediqo_web/public/brand/prediqo-app-icon.png b/prediqo_web/public/brand/prediqo-app-icon.png index 36ff1c3c..28d34d54 100644 Binary files a/prediqo_web/public/brand/prediqo-app-icon.png and b/prediqo_web/public/brand/prediqo-app-icon.png differ diff --git a/prediqo_web/public/brand/prediqo-lockup.png b/prediqo_web/public/brand/prediqo-lockup.png index f4ffc9fe..c104326c 100644 Binary files a/prediqo_web/public/brand/prediqo-lockup.png and b/prediqo_web/public/brand/prediqo-lockup.png differ diff --git a/prediqo_web/public/brand/prediqo-lockup.svg b/prediqo_web/public/brand/prediqo-lockup.svg index b85599f2..76710e7f 100644 --- a/prediqo_web/public/brand/prediqo-lockup.svg +++ b/prediqo_web/public/brand/prediqo-lockup.svg @@ -1,13 +1,4 @@ - - - - - - - - - - - + + TLOTO diff --git a/prediqo_web/public/brand/prediqo-mark.png b/prediqo_web/public/brand/prediqo-mark.png index 36ff1c3c..28d34d54 100644 Binary files a/prediqo_web/public/brand/prediqo-mark.png and b/prediqo_web/public/brand/prediqo-mark.png differ diff --git a/prediqo_web/public/brand/prediqo-mark.svg b/prediqo_web/public/brand/prediqo-mark.svg index 55bf9df0..757a89fc 100644 --- a/prediqo_web/public/brand/prediqo-mark.svg +++ b/prediqo_web/public/brand/prediqo-mark.svg @@ -1,20 +1,4 @@ - - - - - - - - - - - - + + + diff --git a/prediqo_web/public/favicon-32.png b/prediqo_web/public/favicon-32.png new file mode 100644 index 00000000..e17c0972 Binary files /dev/null and b/prediqo_web/public/favicon-32.png differ diff --git a/prediqo_web/public/favicon-48.png b/prediqo_web/public/favicon-48.png new file mode 100644 index 00000000..ab8232b8 Binary files /dev/null and b/prediqo_web/public/favicon-48.png differ diff --git a/prediqo_web/public/favicon.png b/prediqo_web/public/favicon.png new file mode 100644 index 00000000..f127668e Binary files /dev/null and b/prediqo_web/public/favicon.png differ diff --git a/prediqo_web/public/favicon.svg b/prediqo_web/public/favicon.svg index fd366256..757a89fc 100644 --- a/prediqo_web/public/favicon.svg +++ b/prediqo_web/public/favicon.svg @@ -1,10 +1,4 @@ - - - - - - - - - + + + diff --git a/prediqo_web/src/shared/brand/PrediqoLogo.tsx b/prediqo_web/src/shared/brand/PrediqoLogo.tsx index 3d46e7d6..96e37297 100644 --- a/prediqo_web/src/shared/brand/PrediqoLogo.tsx +++ b/prediqo_web/src/shared/brand/PrediqoLogo.tsx @@ -34,7 +34,7 @@ export function PrediqoLogo({ >