From d896a996b313e23ee748beac4d9038a175f3f5ae Mon Sep 17 00:00:00 2001 From: JOY <5027251+JOY@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:47:25 +0700 Subject: [PATCH 1/6] docs(proposals): add Phase 8 feature brainstorm HTML report (#1862) * docs(proposals): add Phase 8 feature brainstorm HTML report Author self-contained dark-theme Vietnamese HTML proposal at Docs/Proposals/2026-11-22-de-xuat-tinh-nang-moi-phase-8.html benchmarking EU/Czechia/global price-truth and review-intelligence leaders against DOS/Rate 22-chain codebase assets. Refs #1861 * docs(proposals): address review feedback on Phase 8 HTML report Add primary benchmark citations, require full 30-day history coverage before Omnibus labeling, clarify SSR candidate scope on leaderboard, separate MCP Registry publishing from hosted discovery files, and add ARIA live-region status announcements to the preset demo. Refs #1861 --- ...6-11-22-de-xuat-tinh-nang-moi-phase-8.html | 1351 +++++++++++++++++ 1 file changed, 1351 insertions(+) create mode 100644 Docs/Proposals/2026-11-22-de-xuat-tinh-nang-moi-phase-8.html diff --git a/Docs/Proposals/2026-11-22-de-xuat-tinh-nang-moi-phase-8.html b/Docs/Proposals/2026-11-22-de-xuat-tinh-nang-moi-phase-8.html new file mode 100644 index 00000000..ad3e79bb --- /dev/null +++ b/Docs/Proposals/2026-11-22-de-xuat-tinh-nang-moi-phase-8.html @@ -0,0 +1,1351 @@ + + + + + + + Đề xuất Tính năng Mới Phase 8 - Rate.vn (2026-2027) + + + +
+
+ Đề xuất Chiến lược Phase 8 + Cần JOY chọn hướng + Issue #1861 - Chỉ nghiên cứu, chưa tạo issue con +
+ +

Brainstorm & Nghiên cứu Tính năng Mới Phase 8 cho Rate.vn

+

+ Ngày 22/11/2026 - Người soạn: Brand (Rate Core), theo yêu cầu trực tiếp của JOY trong phiên PO ("Brainstorm research tính năng mới?"). + Tài liệu này đối chiếu các mô hình kiểm chứng giá và đánh giá thành công nhất tại châu Âu / Séc (Hlídač shopů, Heureka.cz, Idealo, Prisjakt), Mỹ / Toàn cầu (RTINGS.com, Keepa, Model Context Protocol) với nỗi đau thực tế của người mua đồ công nghệ tại Việt Nam trên 22 hệ thống bán lẻ và sàn TMĐT vừa hợp nhất. + Chưa tạo bất kỳ issue backlog nào và chưa chạm tới code runtime hay database. +

+ +
+
+
22 sàn & chuỗi
+
10 sàn gốc + 12 chuỗi Wave 1-3 vừa lên repo (#1859)
+
+
+
5 ngành + 3 ngôn ngữ
+
Điện thoại, Tablet, Laptop, Đồng hồ, Tai nghe (vi, en, cs)
+
+
+
6 trục tin cậy v2
+
Điểm Bayes (k=3, mu=4.2), tách rủi ro DOSafe và Seeding
+
+
+
23 REST API v1 + MV3
+
Cache withRateDataCache, DOS ID SSO, Extension Shadow DOM
+
+
+ +

0. Tóm tắt Quyết Nhanh Trong 60 Giây - 3 Gói Lộ Trình Đề Xuất

+

+ Sau khi hoàn tất nền tảng bảo mật, chuẩn hóa dữ liệu và mở rộng lên 22 chuỗi bán lẻ ở Phase 6-7, khoảng trống lớn nhất của rate.vn hiện nay không còn nằm ở tầng cào dữ liệu thô, mà nằm ở 3 điểm bùng nổ phía người dùng cuối: + (1) vũ khí vạch trần giảm giá ảo mùa cao điểm (Black Friday, 12.12, Tết), + (2) cá nhân hóa quyết định mua + kênh lan truyền tự nhiên qua mạng xã hội và AI Agents, và + (3) vòng lặp giữ chân người dùng quay lại tự động. +

+ +
+ + +
+
+ Bước tiếp nối giữ chân +

Gói 8B - Vòng Lặp Cảnh Báo Chủ Động & MV3 3.0

+

Biến khách vãng lai tra cứu 1 lần thành người dùng gắn bó lâu dài qua tài khoản DOS ID và tiện ích trình duyệt MV3.

+
    +
  • F5: Cảnh báo chạm giá mục tiêu, đáy lịch sử (ATL) & có hàng lại đa kênh (Email xác minh sẵn có, mở rộng Web Push / Telegram, có bộ lọc "Chỉ shop Chính hãng").
  • +
  • F6: MV3 Extension 3.0 - Cảnh báo chống hớ ngay trang Giỏ hàng (Checkout Guard), ghim cảnh báo giá 1 chạm trong Side Panel và đồng bộ M2 đủ 22 sàn (#1762).
  • +
+
+
+ Đụng DB: Nhỏ (Pha 1 Email dùng bảng rate.price_alerts sẵn có; Pha 2 Web Push / Telegram cần 1 PR DOS-Me)
+ Khối lượng: 2 cụm cỡ M (~3-4 tuần) +
+
+ +
+
+ Hào lũy sâu thị trường VN +

Gói 8C - Giá Thực Trả VN/A, Thu Cũ & Giỏ Hàng Đa Sàn

+

Giải quyết nỗi đau đặc thù nhất của bán lẻ công nghệ Việt Nam mà các công cụ quốc tế không thể sao chép.

+
    +
  • F7: Bộ tính "Giá Thực Trả", tách bạch Chính hãng VN/A vs Nhập khẩu & Kiểm chứng thực tế "Thu Cũ Đổi Mới" trên 22 chuỗi.
  • +
  • F8: Tối ưu Giỏ hàng Combo đa sàn 2-5 món (Basket Optimizer) kết hợp Huy hiệu Chuỗi Uy Tín 180 ngày (Heureka Ověřeno).
  • +
+
+
+ Đụng DB: Pha đầu 0 DDL (tính trên BFF); Pha sâu cần 1 PR DOS-Me mở rộng promotions / origin
+ Khối lượng: 2 cụm cỡ M - L (~4-5 tuần) +
+
+
+ +
+ Đề xuất của Brand cho JOY: Duyệt triển khai Gói 8A trước (đặc biệt là F1 + F3 + F2 + F4) ngay cho mùa cao điểm mua sắm cuối năm (Black Friday, 12.12, Giáng sinh, Tết Âm lịch) vì 100% dữ liệu nguồn đã nằm trong PostgreSQL và không bị nghẽn bởi bất kỳ bước duyệt DDL nào trên DOS-Me; song song chuẩn bị thiết kế chi tiết cho F5 (Gói 8B). +
+ +

1. Nghiên Cứu Benchmark Quốc Tế (EU / Séc / Mỹ) & Cộng Hưởng Đa Ngôn Ngữ (vi / en / cs)

+

+ Điểm độc đáo của rate.vn là hỗ trợ gốc 3 ngôn ngữ vi, en, cs (1.971 khóa dịch lá trên 21 namespace mỗi ngôn ngữ). Cộng đồng người Việt tại CH Séc và châu Âu vốn rất quen thuộc với Hlídač shopů và Heureka.cz, trong khi thị trường Việt Nam đang thiếu hoàn toàn một công cụ minh bạch tương đương trên 22 chuỗi lớn (Thế Giới Di Động, CellphoneS, FPT Shop, ShopDunk, TopZone, Di Động Việt, Hoàng Hà, Viettel Store, GearVN, HACOM, An Phát, Phong Vũ, MemoryZone, Shopee, Lazada, TikTok Shop...). +

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Benchmark & Nguồn gốc (tra cứu 22/11/2026)Cơ chế gốc đã kiểm chứngNỗi đau tương ứng tại Việt Nam (2026)Chuyển hóa đề xuất riêng cho Rate.vn Phase 8
Hlídač shopů (hlidacshopu.cz) & Chỉ thị EU Omnibus Điều 6a (Directive 2019/2161)Luật EU quy định giá trước giảm phải là mức giá thấp nhất nhà bán áp dụng trong tối thiểu 30 ngày liền trước; Hlídač shopů đối chiếu lịch sử giá thực của các e-shop Séc để vạch trần mức giảm ảo dịp Black Friday.Trước 11.11, 12.12, Black Friday và cận Tết, nhiều gian hàng đẩy "giá gạch ngang" lên bằng giá MSRP lúc mới ra mắt cách đây 1 năm để treo biển giảm 30-45%, dù giá thực bán suốt tháng trước không đổi.Bản địa hóa F1: Hiển thị trực diện con số Đáy 30 ngày trước sale và % Giảm giá thực tế chuẩn Omnibus (chỉ khi đủ chuỗi 30 ngày) ngay cạnh giá gạch ngang của nhà bán.
RTINGS.com (rtings.com - Custom Ratings & Compare)Tài liệu phương pháp chấm điểm của RTINGS tách điểm theo ngữ cảnh dùng (Use-Case Subscores) và cung cấp công cụ Custom Ratings cho phép người đọc tự gán trọng số từng phép đo để xếp lại bảng.Người chạy xe công nghệ cần Pin + Màn sáng + Độ bền, sinh viên cần Đáng tiền + Hiệu năng, người làm nội dung cần Camera + Mic. Một điểm trung bình cứng làm chìm các máy chuyên biệt rất tốt.Bản địa hóa F2: Gắn bộ Preset 1 chạm và thanh trượt 0% - 100% trực tiếp lên bộ tiêu chí getRatingCriteria (rating-criteria.ts) của 5 ngành hàng trên /leaderboard và /compare.
Keepa (keepa.com) & Prisjakt (prisjakt.nu)Keepa vẽ lịch sử giá dài hạn theo phân nhóm hàng mới/cũ kèm cảnh báo ngưỡng giá mục tiêu đa kênh; Prisjakt theo dõi biến động giá đa cửa hàng độc lập có lọc chi phí giao hàng và cảnh báo khi giảm giá / có hàng lại.Người mua điện thoại/laptop 15-40 triệu VND luôn phân vân "Mua hôm nay hay đợi ngày đôi / cận Tết rẻ hơn 1-2 triệu?", dẫn tới trì hoãn hoặc mua đúng đỉnh giá.Bản địa hóa F1 + F5: Nhãn phân vị lịch sử 90 ngày Mua ngay / Giá bình thường / Đang neo cao (thuật toán đề xuất của Rate) kèm nút nhận thông báo DOS ID khi chạm đáy.
Heureka.cz (Ověřeno zákazníky & heureka.cz)Chương trình Ověřeno zákazníky cấp chứng nhận uy tín cho e-shop dựa trên tỷ lệ khuyến nghị từ khảo sát người mua thật trong 90-180 ngày gần nhất, kết hợp so sánh giá đa cửa hàng và lọc khuyến mãi thật.Người mua không phân biệt được gian hàng Mall thật, đại lý ủy quyền Apple (AAR) với shop trộn phụ kiện / hàng dựng hoặc tách đơn nhiều nơi bị đội phí ship.Bản địa hóa F7 + F8: Huy hiệu chuỗi uy tín 180 ngày tự động từ dữ liệu kiểm toán dosafe_risk_score + review_risk_score (không cần khảo sát email như Heureka) và bộ tối ưu giỏ hàng 2-5 món trên 22 sàn.
Model Context Protocol (modelcontextprotocol.io & MCP Registry)Chuẩn mở MCP chuẩn hóa giao tiếp JSON-RPC / Streamable HTTP để các AI host (Claude, Cursor, IDE, custom agents) gọi công cụ tra cứu dữ liệu có cấu trúc thay vì đoán giá hoặc tự cào HTML.Người dùng Việt Nam ngày càng hỏi AI "Tầm 20 triệu mua laptop nào ở đâu uy tín, không bị giá ảo?", nhưng LLM hiện trả lời bằng dữ liệu cũ hoặc thiếu kiểm chứng gian hàng.Bản địa hóa F4: Mở cổng /api/mcp chỉ đọc trên nền cache BFF + gói @dos/rate-mcp và đăng ký lên MCP Registry, biến câu trả lời AI thành nguồn dẫn link về rate.vn.
+
+ +

2. Ma Trận Chấm Điểm Ưu Tiên 8 Tính Năng (Lọc & Sắp Xếp Tương Tác)

+

+ Điểm ưu tiên tổng hợp (thang 100) được tính có trọng số từ: Giá trị người mua (30%) + Tác động Tăng trưởng / SEO / Lan truyền (25%) + Độ sẵn sàng dữ liệu hiện có trong repo (25%) + Tối ưu chi phí & tốc độ triển khai không vướng DDL (20%). +

+ +
+
+ + + + +
+
+ + + +
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Mã & Tính năngGóiGiá trị người muaDữ liệu sẵn cóCỡ (Size)Cần DOS-Me DDL?Chi phí vận hànhHào lũy (Moat)Điểm
F1. Kiểm toán Giá Đáy 30 Ngày chuẩn EU Omnibus & Chỉ báo Mua Ngay / Chờ Sale8ARất cao (chống bẫy sale ngày đôi, Black Friday, Tết)95% (rate.price_history, listing_price_context)SKhông (0 DDL)$0 (tính trong SQL/BFF cache)Lịch sử giá thực đa sàn tích lũy theo thời gian95
F3. Thẻ Sự Thật Giá & Đánh Giá động (Dynamic OG & Xuất ảnh MXH 1 chạm)8ACao (tóm tắt trực quan trong 3 giây khi gửi link)100% (DealRadar, rating_score, 6 trục v2)SKhông (0 DDL)~$0 (Edge/Node OG cache CDN 1h-24h)Thương hiệu thị giác lan truyền trên Zalo, VOZ, Threads, TikTok92
F2. Thanh trượt trọng số theo nhu cầu cá nhân kiểu RTINGS8ARất cao (chọn đúng máy hợp gu dùng & túi tiền)95% (getRatingCriteria, criteria_scores, 10 nhóm spec)S - MKhông (0 DDL)$0 (100% tính toán phía Client + URL state)Ma trận tiêu chí chuẩn hóa + đánh giá thật đã lọc seeding90
F4. Rate Shopping MCP Server & cổng trích dẫn cho AI Agents (/api/mcp)8ACao (tra giá thật 22 sàn ngay trong Claude, ChatGPT, Gemini, DOSClaw)95% (23 REST API v1 + OpenAPI 3.1 + withRateDataCache)MKhông (0 DDL)~$0 (tái sử dụng cache BFF + giới hạn tần suất)Nền tảng đầu tiên tại VN cấp chuẩn MCP kiểm chứng giá & review88
F5. Cảnh báo chạm giá mục tiêu, đáy ATL & có hàng lại đa kênh8BRất cao (không cần tự canh giá mỗi ngày, không bỏ lỡ đáy thật)80% (rate.price_alerts, upsert_price_alert, PriceAlertEvaluator)MPha 1 Email: 0 DDL; Pha 2 Push/Telegram: 1 PR DOS-MeThấp (SMTP/Resend theo sự kiện giảm giá thật, có chống dội thư)Tỷ lệ giữ chân người dùng (Retention) gắn chặt với DOS ID86
F6. MV3 Extension 3.0: Cảnh báo trang Giỏ hàng (Checkout Guard) & Ghim giá 1 chạm8BCao (cứu người mua đúng giây phút sắp bấm thanh toán hớ)85% (Shadow DOM Pill 22 sàn, Side Panel, #1859)MGuard + Ghim: 0 DDL; M2 đủ 22 sàn: chờ #1762$0 (gọi lookup theo phiên giỏ hàng, có cache cục bộ)Hiện diện trực tiếp ngay tại điểm thanh toán trên 22 sàn83
F7. Bộ tính "Giá Thực Trả", tách Chính hãng VN/A & Kiểm chứng Thu Cũ Đổi Mới8CRất cao với flagship 20-50 triệu VND (hiểu rõ chênh lệch bảo hành & trợ giá)70% (ProductNormalizer origin, ProductValueCalculator)M - LPha 1 BFF: 0 DDL; Pha 2 lưu bảng: 1 PR DOS-Me$0 (quy tắc định danh minh bạch, không dùng LLM lúc đọc)Am hiểu sâu luật chơi bán lẻ công nghệ nội địa Việt Nam81
F8. Tối ưu Giỏ hàng Combo đa sàn (2-5 món) & Huy hiệu Chuỗi Uy Tín 180 ngày8CCao khi sắm trọn bộ (Laptop + Màn hình/SSD/Tai nghe hoặc hệ sinh thái Apple)75% (getMasterProductOffersBatch, v_products_with_merchant_trust)M - LPha 1: Không (0 DDL); Huy hiệu lưu sẵn: tuỳ chọn$0 (thuật toán quy hoạch tổ hợp nhỏ chạy trong vài mili-giây)Kết hợp độc nhất giữa Giá tổng + Rủi ro DOSafe trên 22 chuỗi78
+
+ +

3. Hồ Sơ Phân Tích Chi Tiết Từng Tính Năng (Đối Chiếu Codebase Thật)

+ + +
+
+

F1. Kiểm toán "Giá Đáy 30 Ngày Trước Sale" chuẩn EU Omnibus & Chỉ báo Mua Ngay / Chờ Sale

+ Gói 8A + 0 Migration DOS-Me + Size: S +
+

Lấy cảm hứng trực tiếp từ Hlídač shopů (CH Séc - công cụ giám sát tuân thủ Điều 6a Chỉ thị EU Omnibus 2019/2161) kết hợp phân vị chu kỳ giá của Keepa và Prisjakt.

+
+
Nỗi đau người mua
+
Vào dịp 11.11, Black Friday, 12.12 và cận Tết, người mua thấy biển "Giảm sốc 28% - Giá gốc 34.990.000đ chỉ còn 25.190.000đ" nhưng không biết thực chất suốt 30 ngày trước đó máy vốn đã bán ở mức 24.990.000đ (tức thực tế còn đắt hơn 200.000đ). Đồng thời, người mua luôn băn khoăn mức giá hôm nay đã nằm ở vùng đáy 90 ngày để xuống tiền ngay hay nên đợi đợt sale tiếp theo.
+ +
Đã có sẵn trong repo
+
+
    +
  • Bảng rate.price_history có chỉ mục BRIN trên recorded_at và chống trùng theo observation_id.
  • +
  • Hàm SQL rate.listing_price_context (20261106150000_rate_listing_price_context_peer_max_history_first.sql) đã tính trung vị 60 ngày, peer_reference_max và kiểm tra độ tuổi lịch sử tối thiểu 14 ngày cho PriceAnomalyAuditor.
  • +
  • Component PriceHistorySection.tsx đã vẽ biểu đồ 30d / 90d / all và gắn nhãn fake_discount, suspicious_discount, genuine_deal; deal-radar.ts đã có quy tắc từ 3 nơi bán trở lên cho nhãn đáy giá đa sàn (#1145, #1630).
  • +
+
+ +
Cần xây thêm
+
+
    +
  • Hộp kiểm toán chuẩn EU Omnibus ngay trên trang sản phẩm, /deals và /inspect: Tách bạch 3 con số minh bạch cho từng gian hàng đang treo khuyến mãi: (1) Giá gạch ngang shop tự ghi, (2) Giá thấp nhất thực tế trong 30 ngày liền trước (prior_30d_min_price chỉ được gắn nhãn Chuẩn Omnibus 30 ngày khi price_history phủ đủ trọn vẹn cửa sổ tham chiếu từ 30 ngày trở lên và mật độ điểm đo liên tục; nếu mới quan sát được N < 30 ngày thì chỉ hiện "Đáy quan sát trong N ngày qua" và giữ nguyên trạng thái chưa kết luận Omnibus), và (3) Mức giảm/tăng thực chất.
  • +
  • Chỉ báo quyết định Mua Ngay hay Chờ? (Percentile 90 ngày): Tính vị trí giá tốt nhất hiện tại của sản phẩm trong dải 90 ngày (khi đủ số điểm quan sát hợp lệ): vùng <= P15 hiện nhãn xanh "Vùng đáy 90 ngày - Thời điểm tốt để mua"; vùng P15 - P70 hiện "Giá ổn định thị trường"; vùng > P70 (hoặc vừa nảy lên sau đợt sale) hiện "Đang cao hơn đáy gần nhất X đ - Nên bật cảnh báo chờ sale".
  • +
  • Bộ lọc chiến dịch mùa sale trên /deals: Chế độ xem nhanh "Top Giảm Thật Đợt Sale" và "Cảnh Báo Tăng Giá Đệm Trước Sale" trên toàn bộ 22 chuỗi.
  • +
+
+ +
Tác động & Chi phí
+
Tác động truyền thông & báo chí rất mạnh (chủ đề "bóc phốt sale ảo ngày đôi / Black Friday bằng dữ liệu thật 22 chuỗi" cực kỳ thu hút cộng đồng công nghệ VN và kiều bào Séc). Chi phí hạ tầng: $0, không gọi AI, nằm gọn trong luồng đọc lịch sử giá đã cache bởi RATE_CACHE_TAGS.PRICE_HISTORY.
+ +
Rủi ro & Chốt chặn
+
Trung thực tuyệt đối với cửa sổ quan sát: khác với ngưỡng 14 ngày của kiểm toán chênh lệch trung vị nội bộ, nhãn pháp lý/tham chiếu "Đáy 30 ngày chuẩn EU Omnibus" bắt buộc phải có lịch sử phủ đủ trọn 30 ngày liền trước (không dùng dữ liệu 14 ngày để chứng nhận đáy 30 ngày vì điểm giá thấp hơn có thể rơi vào nửa đầu chưa kịp cào). Khi lịch sử dưới 30 ngày hoặc bị đứt quãng dài, giao diện chỉ ghi đúng số ngày thực tế đã quan sát và không kết luận vi phạm Omnibus.
+
+ +
+
Minh họa hiển thị trên trang sản phẩm & /inspect (Dữ liệu mẫu - Giá đang bán: 27.190.000đ)
+
+
+
Giá đang bán vs Giá gạch ngang shop ghi
+
27.190.000đ Shop ghi -22% từ 34,99tr
+
34.990.000đ là giá niêm yết lúc mới ra mắt
+
+
+
Đáy thực 30 ngày trước (Chuẩn Omnibus)
+
27.490.000đ
+
Giảm thực tế so với đáy 30 ngày: -1,1% (-300.000đ)
+
+
+
Phân vị chu kỳ 90 ngày (22 sàn)
+
Top 8% Đáy Giá
+
Khuyến nghị dữ liệu: Mua ngay tại chuỗi uy tín
+
+
+
+
+ + +
+
+

F2. Thanh Trượt Trọng Số Theo Nhu Cầu Cá Nhân ("Chấm Điểm Cho Riêng Bạn" kiểu RTINGS)

+ Gói 8A + 0 Migration DOS-Me + Size: S - M +
+

Lấy cảm hứng từ RTINGS.com Custom Ratings & Use-Case Scoring - biến bảng điểm tĩnh thành công cụ tư vấn khách quan không cần chatbot AI.

+
+
Nỗi đau người mua
+
Trên bảng xếp hạng hiện tại, mỗi ngành hàng có một bộ trọng số cố định (ví dụ điện thoại: Hiệu năng 20%, Camera 20%, Pin 20%, Màn hình 15%, Thiết kế 10%, Đáng tiền 15%). Tuy nhiên, một game thủ mua máy phụ chỉ cần Hiệu năng + Pin + Tản nhiệt và không quan tâm Camera; trong khi người mua tai nghe đi máy bay lại đặt Chống ồn (ANC) và Đeo thoải mái lên tới 70%.
+ +
Đã có sẵn trong repo
+
+
    +
  • packages/shared-data/src/rules/rating-criteria.ts (RATING_CRITERIA_VERSION = 1) đã định nghĩa đầy đủ danh sách tiêu chí đa ngôn ngữ (vi, en, cs), trọng số gốc tổng bằng 100 và ánh xạ SpecGroupKey cho cả 5 ngành thiết bị.
  • +
  • Cột rate.master_products.criteria_scores (20261101120000_rate_criteria_ratings.sql), expert_criteria_scores, cùng hàm weightedCriteriaScore5 trong leaderboard-engine.ts và trang so sánh CompareWorkspace.tsx (tối đa MAX_COMPARE_ITEMS = 4 máy) đã hoạt động trên Production.
  • +
+
+ +
Cần xây thêm
+
+
    +
  • Thanh chọn nhanh kịch bản sử dụng (1-Click Use-Case Presets) theo từng ngành hàng: + Điện thoại (Cân bằng mặc định, Cày Game & Pin trâu, Nhiếp ảnh & Vlog, Bền bỉ & Thực dụng); + Laptop (Văn phòng / Sinh viên di động, Lập trình & Đồ họa nặng, Gaming & Tản nhiệt); + Tai nghe (Nghe nhạc Audiophile, Đi làm / Chống ồn ANC, Họp online & Đàm thoại)...
  • +
  • Thanh trượt tùy chỉnh trọng số 0% - 100% (tự chuẩn hóa tổng về 100%): Tích hợp ngay trên đầu /leaderboard, /compare và trang đối đầu 1v1 /compare/[versus], tự động tính lại Điểm hợp nhu cầu của bạn và đổi ngôi vị người thắng cuộc kèm lời giải thích toán học rõ ràng.
  • +
  • URL có thể chia sẻ trực tiếp: Mã hóa bộ trọng số gọn trên query string (ví dụ /compare/iphone-17-vs-galaxy-s26?preset=camera) mà không tạo rác chỉ mục SEO (giữ rel="canonical" về URL gốc).
  • +
+
+ +
Tác động & Chi phí
+
Tăng mạnh thời gian tương tác trên trang (Time-on-site) và tỷ lệ chuyển đổi sang nhấp chuột gian hàng trên /compare và /leaderboard. Giới hạn phạm vi & chi phí rõ ràng: trên /compare (2-4 máy đã chọn) và trên tập ứng viên mà /leaderboard tải sẵn qua SSR (hiện giới hạn tối đa 100 mẫu xếp cao nhất mỗi ngành hàng khi RATE_ITEM_MODEL tắt), phép tính lại phía trình duyệt tốn $0 nhưng chỉ sắp xếp lại trong tập ứng viên đã tải đó; nếu muốn một mẫu nằm ngoài top 100 mặc định vẫn có thể vươn lên top đầu theo trọng số riêng (ví dụ chuyên Gaming), cần nạp đủ danh sách ứng viên hợp lệ của ngành hàng (vốn gọn nhẹ) hoặc đẩy bộ trọng số chuẩn hóa qua tham số truy vấn của /api/v1/rate/leaderboard có bọc cache.
+ +
Rủi ro & Chốt chặn
+
Tuân thủ nghiêm quyết định thiết kế #1531 D3/D9: luôn giữ nguyên và hiển thị rõ "Điểm chuẩn Rate.vn" ở cột gốc để không gây nhầm lẫn một máy có hai số điểm khác nhau; điểm tùy chỉnh được gắn nhãn riêng "Điểm theo trọng số bạn chọn"; các tiêu chí chưa đủ số lượng đánh giá thật vẫn giữ trạng thái không bịa số.
+
+ +
+
Trải nghiệm thử ngay: Chọn kịch bản để xem thứ hạng 2 mẫu máy minh họa đảo chiều tức thì
+
+ + + +
+
+ Trọng số đang áp dụng: Hiệu năng 20% - Camera 20% - Pin 20% - Màn hình 15% - Thiết kế 10% - Đáng tiền 15% +
+
+
Mẫu A (Chuyên Camera)
+
+
4.5 / 5
+
+
+
Mẫu B (Pin 6500mAh + Chip mạnh)
+
+
4.4 / 5
+
+
+ Kết quả hiện tại: Mẫu A đạt 4.5 / 5 - Mẫu B đạt 4.4 / 5. +
+
+
+ + +
+
+

F3. Thẻ Sự Thật Giá & Đánh Giá Động (Dynamic OG Image & Xuất Ảnh Mạng Xã Hội 1 Chạm)

+ Gói 8A + 0 Migration DOS-Me + Size: S +
+

Biến mỗi lượt dán link trên Zalo, Messenger, Facebook Group, VOZ, Threads, Telegram hay TikTok thành một tấm danh thiếp kiểm chứng giá chuyên nghiệp.

+
+
Nỗi đau người mua
+
Kiểm tra thực tế codebase hiện tại: toàn bộ apps/web/src/app chưa có bất kỳ route opengraph-image hay /api/og nào, còn ProductShareAuditButton.tsx mới chỉ xuất văn bản Markdown / CSV. Khi người dùng gửi link sản phẩm hoặc kèo so sánh /compare/a-vs-b vào nhóm chat gia đình trên Zalo hoặc diễn đàn VOZ để hỏi ý kiến, bản xem trước chỉ hiện logo tĩnh chung chung, đánh mất hoàn toàn sức nặng thuyết phục của dữ liệu 22 sàn.
+ +
Đã có sẵn trong repo
+
+
    +
  • ProductShareAuditButton.tsx đã chuẩn hóa và làm sạch toàn bộ trường dữ liệu chia sẻ (sanitizeShareAuditText, điểm người dùng, điểm chuyên gia, số đánh giá thật, giá thấp nhất, số nơi bán, radarSignal).
  • +
  • Next.js 16.4 hỗ trợ gốc next/og (ImageResponse) ngay trên Node/Edge runtime mà không cần cài thêm trình duyệt headless.
  • +
+
+ +
Cần xây thêm
+
+
    +
  • 3 mẫu Dynamic OpenGraph PNG (1200x630, Dark Theme chuẩn thương hiệu #0f1113 + điểm nhấn đỏ #FF2E29): (1) Trang sản phẩm (Giá thấp nhất đã kiểm chứng trên X/22 sàn + Nhãn Deal Radar + Điểm sao Bayes + % đánh giá thật), (2) Trang so kè 1v1 Versus (Bảng tỷ số đối đầu 2 máy), và (3) Trang tổng hợp Deal Radar.
  • +
  • Nút "Tải Ảnh Thẻ Sự Thật (4:5 / 9:16)" ngay trong menu của ProductShareAuditButton: Cho phép người làm nội dung review TikTok, Threads, Reels, Facebook tải ngay tấm thẻ PNG sắc nét có gắn nguồn rate.vn chỉ bằng 1 cú nhấp.
  • +
+
+ +
Tác động & Chi phí
+
Tăng tỷ lệ nhấp (CTR) khi chia sẻ link xã hội lên gấp nhiều lần và tạo hiệu ứng quảng bá thương hiệu miễn phí mỗi khi KOL/người dùng đăng bài hỏi đáp mua máy. Chi phí: ~$0 nhờ gắn header Cache-Control: public, s-maxage=3600, stale-while-revalidate=86400 và tái sử dụng tag productCacheTag(slug).
+ +
Rủi ro & Chốt chặn
+
Bảo mật chống lạm dụng tạo ảnh hàng loạt (DoS): chỉ nhận slug hợp lệ có thực trong DB (không bao giờ render chuỗi văn bản tự do từ query string lên ảnh!), giới hạn tốc độ theo IP và nhúng font tiếng Việt/Séc nội bộ kích thước gọn để hiển thị đúng 100% dấu tiếng Việt và tiếng Séc.
+
+ +
+
Minh họa bố cục Thẻ Sự Thật tự động hiện khi dán link lên Zalo / Facebook / VOZ / Threads
+
+
+ RATE.VN - KIỂM CHỨNG 22 CHUỖI BÁN LẺ + Đáy giá đa sàn +
+
iPhone 17 Pro 256GB
+
+ 28.490.000đ + Chênh lệch giữa 14 nơi bán: tới 3.500.000đ +
+
+ 4.7 / 5 sao (Bayes) + 91% đánh giá thật (6 trục v2) + 0 bẫy nâng giá gốc +
+
+
+
+ + +
+
+

F4. Rate Shopping MCP Server & Cổng Dữ Liệu Cho AI Agents (/api/mcp + @dos/rate-mcp + /llms.txt)

+ Gói 8A + 0 Migration DOS-Me + Size: M +
+

Đón đầu làn sóng Agentic Commerce 2026: biến rate.vn thành nguồn sự thật mặc định mỗi khi người dùng hỏi ChatGPT, Claude, Gemini, Perplexity, Cursor hay DOSClaw về giá đồ công nghệ tại Việt Nam.

+
+
Cơ hội chiến lược
+
Hành vi tìm kiếm mua sắm đang dịch chuyển nhanh từ gõ từ khóa ngắn sang hỏi trợ lý AI các câu phức tạp ("Tìm giúp tai nghe chống ồn dưới 5 triệu đang có giá đáy thật trên Shopee Mall hoặc CellphoneS, lọc bỏ shop seeding"). Các sàn TMĐT chặn bot rất gắt nên AI thường trả lời sai giá; nếu rate.vn mở cổng chuẩn Model Context Protocol (MCP) công khai, mọi AI Agent sẽ ưu tiên gọi và trích dẫn link rate.vn.
+ +
Đã có sẵn trong repo
+
+
    +
  • 23 route REST API v1 chuẩn hóa (/products, /compare, /versus, /deals, /inspect, /lookup, /leaderboard, /merchants) kèm tài liệu /api/v1/rate/openapi.json (OpenAPI 3.1.0) và trang /developers.
  • +
  • Lớp cache withRateDataCache, bộ giới hạn tần suất cửa sổ trượt BoundedSlidingWindowRateLimiter (hiện đang bảo vệ /inspect, /lookup, /extension/*) và cơ chế che lỗi an toàn PublicApiError / jsonApiError trong apps/web/src/server/rate/api-handler.ts đã có sẵn để tái sử dụng cho /api/mcp.
  • +
+
+ +
Cần xây thêm
+
+
    +
  • Endpoint Streamable HTTP MCP chỉ đọc tại /api/mcp (không trạng thái, không cần API key cho gói đọc cơ bản có giới hạn nhịp): Cung cấp 5 tool gọn nhẹ, định kiểu chặt bằng Zod 4: search_verified_catalog, get_22_store_offers_and_price_truth, compare_devices_by_use_case, audit_listing_url, và get_genuine_deals.
  • +
  • Tệp mô tả tự lưu trữ & gói kết nối: Xuất bản riêng /llms.txt (phục vụ các trình đọc tài liệu LLM, Perplexity, trình duyệt AI đọc ngữ cảnh web) và /.well-known/mcp.json + gói mỏng packages/rate-mcp (phục vụ Claude Desktop, Cursor, Windsurf, VS Code và hệ sinh thái nội bộ DOS.AI / DOSClaw).
  • +
  • Quy trình đăng ký lên Official MCP Registry (tách riêng với việc đặt file tĩnh): Việc xuất bản /llms.txt hay /.well-known/mcp.json không tự động đưa server vào thư mục chính thức; cần thêm bước đóng gói đặc tả server.json, xác thực quyền sở hữu tên miền/namespace (DNS hoặc GitHub OIDC) và phát hành qua công cụ mcp-publisher lên registry.modelcontextprotocol.io.
  • +
  • Bắt buộc đính kèm canonical_citation_url và nhãn thời điểm cập nhật (price_observed_at) trong mọi kết quả trả về để đảm bảo lưu lượng truy cập quay về rate.vn.
  • +
+
+ +
Tác động & Chi phí
+
Kênh thu hút lưu lượng tự nhiên mới (AI SEO / GEO) với chi phí marketing bằng 0, đồng thời khẳng định vị thế Open-Core hiện đại của hệ sinh thái DOS trên GitHub. Chi phí DB gần như không đổi vì 100% tool MCP gọi lại các hàm đọc đã bọc withRateDataCache (không mở truy vấn tùy ý).
+ +
Rủi ro & Chốt chặn
+
Chỉ mở quyền READ-ONLY trên dữ liệu công khai đã kiểm duyệt; áp trần kích thước request body, giới hạn số kết quả mỗi lần gọi (tối đa 10 mục) và áp rate-limit theo IP/token để ngăn đối thủ dùng MCP hút cạn toàn bộ cơ sở dữ liệu (anti-scraping).
+
+
+ + +
+
+

F5. Cảnh Báo Chạm Giá Mục Tiêu, Đáy Lịch Sử (ATL) & Có Hàng Lại Đa Kênh

+ Gói 8B + Pha 1: 0 DDL / Pha 2: 1 PR DOS-Me + Size: M +
+

Khép kín vòng lặp giữ chân người dùng theo mô hình Keepa và Idealo, tận dụng hạ tầng cảnh báo giá đã xây xong 80% trong DB.

+
+
Nỗi đau người mua
+
Hiện tại người dùng đã đăng nhập DOS ID có thể lưu mức giá mong muốn trên /watchlist (lưu vào bảng rate.price_alerts qua RPC rate.upsert_price_alert, tối đa 100 cảnh báo/người), và phía DOS/Rate-Services đã có PriceAlertEvaluator. Tuy nhiên, người mua vẫn thiếu trải nghiệm nhận thông báo chủ động tinh gọn, công tắc "Chỉ báo khi shop Chính hãng giảm giá" (tránh bị đánh thức bởi giá mồi của shop rủi ro cao) và nút hủy đăng ký 1 chạm.
+ +
Đã có sẵn trong repo
+
+
    +
  • Bảng rate.price_alerts + khóa bảo mật 20261018120000_rate_price_alert_auth_gate.sql (bắt buộc email đã xác minh trong auth.users, khóa chống đua pg_advisory_xact_lock, cột last_triggered_at, đa ngôn ngữ vi/en/cs).
  • +
  • API GET/POST /api/v1/rate/watchlist và giao diện WatchlistWorkspace.tsx + xác thực RateAuthPortal.tsx.
  • +
+
+ +
Cần xây thêm
+
+
    +
  • Pha 1 (Không cần DDL): Hoàn thiện luồng gửi Email thông báo đa ngôn ngữ (vi, en, cs) từ worker khi current_min_price <= target_price tại gian hàng hợp lệ (không phải giá mồi, in_stock), có thời gian nghỉ chống gửi lặp (ví dụ tối thiểu 7 ngày cho cùng một mức giá) và link hủy theo chuẩn RFC 8058 List-Unsubscribe ký bằng HMAC.
  • +
  • Pha 2 (Mở rộng qua 1 PR DOS-Me): Thêm tùy chọn official_only (chỉ báo chuỗi is_official = true và threat_risk_score <= 20), notify_on_atl (báo ngay khi lập đáy 90 ngày dù chưa chạm số gõ tay), cảnh báo "Có hàng trở lại" cho các mẫu cháy hàng đợt đầu (như iPhone Pro Max mới ra mắt), cùng kênh Web Push (PWA) và Telegram Bot liên kết DOS ID.
  • +
+
+ +
Tác động & Chi phí
+
Biến Rate.vn từ trang tra cứu một lần thành thói quen quay lại hàng tháng, đồng thời thúc đẩy tỷ lệ đăng ký tài khoản DOS ID thật có xác minh email. Chi phí gửi email rất thấp vì chỉ phát sinh khi có biến động giảm giá thực sự vượt ngưỡng.
+ +
Rủi ro & Chốt chặn
+
Tuyệt đối không cho phép nhập email của người khác (đã được RPC upsert_price_alert khóa chặt theo auth.uid()); kiểm tra nghiêm uy tín tên miền gửi thư (SPF, DKIM, DMARC) và tự động tắt cảnh báo nếu email bị trả lại (bounce).
+
+
+ + +
+
+

F6. MV3 Extension 3.0: Cảnh Báo Giỏ Hàng (Checkout Guard) & Ghim Giá Mục Tiêu 1 Chạm

+ Gói 8B + 0 DDL cho Guard & Ghim + Size: M +
+

Nâng cấp tiện ích trình duyệt Chrome MV3 vừa được mở rộng lên 22 chuỗi ở #1859 để bảo vệ người mua ngay tại bước thanh toán.

+
+
Hiện trạng trung thực
+
Tiện ích MV3 hiện tại (apps/extension/src/content/content-script.ts) đã có sẵn viên thuốc nổi (Shadow DOM Floating Trust Pill) trên trang chi tiết sản phẩm của cả 22 sàn, hiển thị câu pillCheaperAt ("Rẻ hơn tại X nơi, tiết kiệm Y đ"), cờ radar-trap và điểm tin cậy. Điểm còn thiếu là: (1) khi người mua đi thẳng từ quảng cáo vào trang Giỏ hàng / Thanh toán thì chưa có cảnh báo, (2) trong Side Panel chưa có nút bấm 1 chạm để đặt cảnh báo giá mà phải mở tab web mới, và (3) luồng đóng góp quan sát giá M2 mới mở cho 10 sàn gốc, còn 12 chuỗi mới đang chờ mở rộng ràng buộc SQL ở #1762.
+ +
Cần xây thêm
+
+
    +
  • Chế độ Checkout Price-Trap Guard (không xâm lấn, tôn trọng quyền riêng tư): Khi người dùng ở trang giỏ hàng của 1 trong 22 chuỗi và sắp thanh toán một thiết bị đang bị đánh dấu inflated_fake_sale hoặc đắt hơn chuỗi chính hãng khác từ >= 5% (hoặc >= 500.000đ), hiển thị một dải thông báo gọn có thể tắt: chỉ rõ chuỗi chính hãng nào đang còn hàng rẻ hơn bao nhiêu tiền.
  • +
  • Ghim Cảnh Báo Giá 1 chạm ngay trong Side Panel: Cho phép người dùng đã đăng nhập gắn mức giá mong muốn (ví dụ "Báo tôi khi giảm thêm 5%") qua POST /api/v1/rate/watchlist ngay trong Side Panel mà không rời trang mua sắm.
  • +
  • Hoàn tất đồng bộ 22/22 sàn cho M2 Crowd Observation (phối hợp #1762 & #1606): Sau khi JOY duyệt PR mở rộng danh sách sàn trong SQL DOS-Me, toàn bộ 12 chuỗi điện máy và PC mới (GearVN, HACOM, An Phát, ShopDunk, TopZone, Điện Máy Xanh...) sẽ có độ tươi giá thời gian thực ngang hàng 10 sàn đầu.
  • +
+
+ +
Tác động & Chi phí
+
Tạo khoảnh khắc "Rate.vn vừa cứu mình khỏi mất oan 1,5 triệu đồng" - động lực mạnh nhất để người dùng đánh giá 5 sao trên Chrome Web Store và giới thiệu bạn bè. Không cần xin thêm bất kỳ quyền nhạy cảm nào trong manifest.json (giữ nguyên chỉ storage, sidePanel và 38 mẫu URL host_permissions hiện có của 22 sàn và rate.vn).
+ +
Rủi ro & Chốt chặn
+
Không bao giờ đọc thông tin cá nhân, địa chỉ giao hàng, số điện thoại hay thẻ thanh toán trên trang checkout (chỉ trích xuất mã sản phẩm/URL và đơn giá niêm yết của món hàng bằng bộ lọc DOM an toàn sẵn có); có công tắc tắt riêng cho trang giỏ hàng trong phần cài đặt tiện ích.
+
+
+ + +
+
+

F7. Bộ Tính "Giá Thực Trả", Tách Bạch Chính Hãng VN/A & Kiểm Chứng Thu Cũ Đổi Mới

+ Gói 8C + Pha 1: 0 DDL / Pha 2: 1 PR DOS-Me + Size: M - L +
+

Giải quyết vùng mù lớn nhất của thị trường bán lẻ thiết bị công nghệ Việt Nam khi so sánh giữa các chuỗi lớn (TGDĐ, FPT Shop, CellphoneS, ShopDunk, TopZone) với các cửa hàng giá rẻ và sàn TMĐT.

+
+
Nỗi đau người mua
+
Tại Việt Nam, cùng một chiếc iPhone hoặc MacBook có thể chênh nhau 3 triệu VND giữa 2 nơi bán nhưng bản chất khác nhau: một bên là hàng chính hãng VN/A nguyên seal xuất hóa đơn VAT đầy đủ và bảo hành ủy quyền 12 tháng, bên kia là hàng nhập khẩu hoặc đã kích hoạt bảo hành điện tử trước. Thêm vào đó, các biển quảng cáo "Thu cũ đổi mới trợ giá 3 triệu" thường tính trên điều kiện máy cũ "Loại 1 hoàn hảo 100%", khiến khách mang máy ra cửa hàng hay bị trừ tiền xước nhẹ/chai pin xuống Loại 2-3 rất hụt hẫng.
+ +
Đã có sẵn trong repo
+
+
    +
  • ProductNormalizer (apps/importer/src/shopee/product-normalizer.ts) đã có kiểu phân loại ProductOrigin = 'official_vna' | 'imported' | 'unknown' và chặn hàng cũ used ngay từ đầu vào (#1430, #1561).
  • +
  • ProductValueCalculator.tsx đã có công cụ tính chi phí sở hữu thực tế theo chu kỳ 12 / 24 / 36 tháng kèm tỷ lệ giữ giá bán lại (estimateResaleRetentionRatio).
  • +
  • Bảng rate.promotions đã tồn tại trong schema nền (20261005130001_rate_platform_tables.sql).
  • +
+
+ +
Cần xây thêm
+
+
    +
  • Nhãn minh bạch Nguồn gốc & Bảo hành trên bảng so sánh 22 nơi bán (ProductOffersExplorer.tsx): Gắn huy hiệu rõ ràng "Đại lý ủy quyền / Chính hãng VAT", "Gian hàng Mall trên sàn", hoặc "Cửa hàng độc lập - Kiểm tra kỹ điều kiện kích hoạt bảo hành" kèm bộ lọc nhanh.
  • +
  • Mô-đun mở rộng "Kiểm chứng Thu Cũ Đổi Mới vs Tự Bán Lại" ngay trong ProductValueCalculator: Cho người mua chọn tình trạng máy cũ thực tế (Đẹp không tì vết / Xước dăm nhẹ / Pin dưới 85%) để so sánh minh bạch giữa phương án mang ra chuỗi đổi nhanh (tiện, an toàn nhưng có hệ số khấu trừ ngoại hình) và phương án tự bán lại + mua đứt ở chuỗi đang có đáy giá trên rate.vn.
  • +
+
+ +
Tác động & Chi phí
+
Tạo lợi thế cạnh tranh bản địa hóa sâu sắc mà không một trang so sánh giá nước ngoài hay công cụ AI chung chung nào có được. Chi phí vận hành: $0 cho Pha 1.
+ +
Rủi ro & Chốt chặn
+
Không bao giờ khẳng định con số định giá thu cũ là cam kết của nhà bán lẻ: ghi rõ nhãn "Ước tính tham khảo theo khung khấu trừ phổ biến - Giá thu thực tế phụ thuộc thẩm định trực tiếp tại quầy" để đảm bảo tính chuẩn xác pháp lý và trung thực với người dùng.
+
+
+ + +
+
+

F8. Tối Ưu Giỏ Hàng Combo Đa Sàn (2-5 Món) & Huy Hiệu Chuỗi Uy Tín 180 Ngày

+ Gói 8C + Pha 1: 0 Migration DOS-Me + Size: M - L +
+

Kết hợp bài toán tối ưu giỏ hàng đa nhà bán của Prisjakt / BestPrice với chương trình chứng nhận nhà bán hàng tin cậy 180 ngày của Heureka.cz (Ověřeno zákazníky).

+
+
Nỗi đau người mua
+
Sinh viên nhập học hoặc người đi làm thường mua combo 2-4 thiết bị cùng lúc (ví dụ: Laptop + Tai nghe chống ồn + Máy tính bảng/Đồng hồ trên GearVN, HACOM, An Phát, Phong Vũ, CellphoneS, Shopee). Nếu mua gom hết tại 1 chuỗi thì tổng hóa đơn thường đắt hơn 1,5-4 triệu VND; nhưng nếu xé lẻ mỗi món một shop rẻ nhất thì dễ vướng shop rủi ro cao, tốn nhiều lần nhận hàng và rắc rối bảo hành.
+ +
Đã có sẵn trong repo
+
+
    +
  • Hàm getMasterProductOffersBatch và API GET /api/v1/rate/watchlist?slugs=... đã tải song song toàn bộ lời chào bán còn hàng hợp lệ của tối đa 20 sản phẩm trong một lần gọi.
  • +
  • View rate.v_products_with_merchant_trust đã hợp nhất điểm rủi ro an ninh mạng dosafe_risk_score (từ dosafe.threat_intel) và điểm rủi ro đánh giá ảo review_risk_score cho từng nhà bán.
  • +
+
+ +
Cần xây thêm
+
+
    +
  • Chế độ "Tối ưu Mua Trọn Bộ (Combo Optimizer)" ngay trong trang /watchlist: Khi người dùng đánh dấu từ 2 đến 5 sản phẩm trong danh sách theo dõi, hệ thống giải bài toán tối ưu và đề xuất song song 2 phương án: + (A) Phương án Tiết kiệm tối đa (tách tối đa 2-3 chuỗi uy tín, chỉ nhận gian hàng có threat_risk_score <= 20) và + (B) Phương án Tiện lợi 1 điểm đến (1 chuỗi duy nhất đang có đủ hàng với tổng tiền thấp nhất), hiển thị rõ số tiền chênh lệch giữa hai phương án.
  • +
  • Huy hiệu "Chuỗi Đạt Chuẩn Tin Cậy 180 Ngày" trên /merchants và bảng giá: Chỉ cấp tự động cho nhà bán đạt đồng thời 3 ngưỡng cứng: không có cờ cảnh báo DOSafe, tỷ lệ đánh giá thật 6 trục cao ổn định trong 180 ngày và không tái diễn hành vi nâng giá gốc giảm ảo.
  • +
+
+ +
Tác động & Chi phí
+
Khai thác trọn vẹn sức mạnh của danh mục 12 chuỗi điện máy và PC mới thêm vào ở #1859 (đặc biệt hiệu quả với tệp khách hàng mua đồ công nghệ giá trị cao). Thuật toán chạy trên tập tối đa 5 sản phẩm x 22 sàn nên hoàn tất dưới 5ms trên BFF, chi phí $0.
+ +
Rủi ro & Chốt chặn
+
Huy hiệu tin cậy 180 ngày bắt buộc tính hoàn toàn tự động bằng công thức công khai từ dữ liệu kiểm toán (không bán gói quảng cáo mua huy hiệu), giữ vững tôn chỉ trung lập tuyệt đối của rate.vn.
+
+
+ +

4. Ba Ý Tưởng Đã Xét Nhưng KHUYẾN NGHỊ KHÔNG LÀM Ở Phase 8 (Tránh Lãng Phí Nguồn Lực)

+

Để giữ kiến trúc 4 tầng gọn nhẹ, không phát sinh chi phí LLM định kỳ và không làm loãng định vị "Sự thật giá & đánh giá", Brand khuyến nghị gạt bỏ 3 hướng sau trong Phase 8:

+ +
+
+

1. Chatbot AI tư vấn mua sắm tự do trên trang công khai

+

Lý do không làm: Tốn chi phí token LLM liên tục, dễ bị tấn công prompt-injection và nguy hiểm nhất là rủi ro AI "nói nhịu" sai giá sản phẩm. Bộ đôi F2 (Thanh trượt trọng số RTINGS) + F4 (MCP cho AI riêng của người dùng) giải quyết bài toán tư vấn chính xác 100% với chi phí LLM bằng $0 cho Rate.

+
+
+

2. Tự động thử mã giảm giá (Auto-Coupon Injector kiểu Honey cũ)

+

Lý do không làm: Đòi hỏi can thiệp sâu vào ô nhập liệu thanh toán của các sàn, dễ gây xung đột giao diện, làm chậm quy trình duyệt Chrome Web Store và dễ gây nghi ngại về quyền riêng tư. F6 (Checkout Price-Trap Guard chỉ đọc) an toàn, minh bạch và đúng chất kiểm chứng của Rate hơn nhiều.

+
+
+

3. Chợ rao vặt mua bán máy cũ trực tiếp giữa người dùng (P2P)

+

Lý do không làm: Kéo theo rủi ro lừa đảo giao dịch, kiểm duyệt tin đăng rác và hỗ trợ tranh chấp nặng nề, đi chệch khỏi mô hình Open-Core dữ liệu kiểm chứng. Thay vào đó, F7 (Bộ tính tham khảo Thu cũ đổi mới vs Bán lại) hỗ trợ người dùng ra quyết định mà không ôm rủi ro vận hành chợ.

+
+
+ +

5. Bảng Quyết Định Dành Cho JOY

+

+ Theo đúng quy chuẩn Product Owner (AGENTS.md Mục 6), chưa có bất kỳ issue tính năng nào được tạo. Khi JOY chọn một trong các phương án dưới đây trong phiên chat với PO, PO mới tiến hành tách thành các đặc tả issue chuẩn trên GitHub Project #9: +

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Phương án lựa chọnPhạm vi tính năng đưa vào Backlog Phase 8Yêu cầu duyệt Migration DOS-MeKhuyến nghị
Phương án 1 (Khuyến nghị)Triển khai trọn bộ Gói 8A (F1 + F2 + F3 + F4) trước để kịp mùa sale cuối năm, đồng thời lên thiết kế kỹ thuật sẵn cho F5 (Cảnh báo giá Email - Gói 8B Pha 1).Không cần bất kỳ DDL nào trên DOS-Me (chạy thẳng trên DOS/Rate và Rate-Services).Khuyến nghị số 1: Tốc độ ra mắt nhanh nhất, rủi ro bằng 0, tạo ngay cả giá trị chống giá ảo lẫn kênh lan truyền MXH + AI.
Phương án 2 (Tăng tốc toàn diện)Duyệt cả Gói 8A + Gói 8B đầy đủ (F1 đến F6), bao gồm cả Web Push / Telegram cho cảnh báo giá và đồng bộ M2 22 sàn (#1762).Cần JOY duyệt 1-2 PR migration nhỏ bên DOS-Me ở nửa sau của đợt triển khai.Phù hợp nếu JOY muốn đẩy mạnh giữ chân tài khoản DOS ID và Chrome Web Store ngay trong Q4/2026 - Q1/2027.
Phương án 3 (Chọn lẻ theo mã)JOY chỉ định trực tiếp các mã muốn làm (ví dụ: "Chỉ làm F1, F2, F7").Tùy theo mã được chọn (F1, F2, F3, F4, F6-Guard, F8-Pha1 đều 0 DDL).Linh hoạt theo ưu tiên sản phẩm riêng của JOY.
+
+ +

+ Tài liệu tự chứa 100% (không phụ thuộc CDN hay tài nguyên ngoài). Kiểm chứng mã nguồn tại nhánh docs/1861-phase8-feature-brainstorm (dựa trên origin/dev commit 56309d8a). +

+
+ + + + From 1c75b42abb0d64c8be10fe26ba3ba31f333267e6 Mon Sep 17 00:00:00 2001 From: JOY <5027251+JOY@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:37:15 +0700 Subject: [PATCH 2/6] feat(web): add dynamic OpenGraph truth cards and social PNG download (#1868) * feat(web): add dynamic OpenGraph truth cards and social PNG download Implement /api/v1/rate/og and og-truth-card.tsx for product, 1v1 versus, and Deal Radar cards across vi/en/cs in 1200x630 and 1080x1350 formats, wire openGraph and twitter metadata, and add 1-click social PNG download to ProductShareAuditButton. Closes #1865 --- apps/web/locales/cs.json | 2 + apps/web/locales/en.json | 2 + apps/web/locales/vi.json | 2 + .../app/[locale]/compare/[versus]/page.tsx | 21 +- apps/web/src/app/[locale]/deals/page.tsx | 27 +- .../app/[locale]/smartphones/[slug]/page.tsx | 26 +- apps/web/src/app/api/v1/rate/og/route.ts | 432 +++++ .../leaderboard/ProductShareAuditButton.tsx | 85 + .../lib/__tests__/product-detail-copy.test.ts | 72 + apps/web/src/lib/__tests__/seo.test.ts | 420 ++++- apps/web/src/lib/og-truth-card.tsx | 1579 +++++++++++++++++ apps/web/src/lib/seo.ts | 215 +++ 12 files changed, 2865 insertions(+), 18 deletions(-) create mode 100644 apps/web/src/app/api/v1/rate/og/route.ts create mode 100644 apps/web/src/lib/og-truth-card.tsx diff --git a/apps/web/locales/cs.json b/apps/web/locales/cs.json index ea5b02d3..6ad69152 100644 --- a/apps/web/locales/cs.json +++ b/apps/web/locales/cs.json @@ -1221,6 +1221,8 @@ "shareAuditCopyLinkTitle": "Zkopírovat odkaz na produkt", "shareAuditCopiedLinkBtn": "✓ Odkaz zkopírován!", "shareAuditCopyLinkBtn": "Kopírovat odkaz", + "shareAuditDownloadPngTitle": "Stáhnout obrázek karty pravdy (PNG 4:5) pro sítě a chat", + "shareAuditDownloadPngBtn": "Stáhnout kartu (PNG 4:5)", "specsToolbarCopiedMd": "10 skupin parametrů zkopírováno!", "specsToolbarCopyMd": "Kopírovat 10 skupin parametrů MD", "specsToolbarExportCsv": "Exportovat parametry CSV", diff --git a/apps/web/locales/en.json b/apps/web/locales/en.json index 4fb58a61..de00af66 100644 --- a/apps/web/locales/en.json +++ b/apps/web/locales/en.json @@ -1221,6 +1221,8 @@ "shareAuditCopyLinkTitle": "Copy product URL", "shareAuditCopiedLinkBtn": "✓ Copied link!", "shareAuditCopyLinkBtn": "Copy link", + "shareAuditDownloadPngTitle": "Download a 4:5 truth card PNG to share on forums or chat", + "shareAuditDownloadPngBtn": "Download truth card (PNG)", "specsToolbarCopiedMd": "Copied 10-group specs!", "specsToolbarCopyMd": "Copy 10-group specs MD", "specsToolbarExportCsv": "Export specs CSV", diff --git a/apps/web/locales/vi.json b/apps/web/locales/vi.json index 72f4ea0e..e16f32ef 100644 --- a/apps/web/locales/vi.json +++ b/apps/web/locales/vi.json @@ -1221,6 +1221,8 @@ "shareAuditCopyLinkTitle": "Sao chép đường dẫn sản phẩm", "shareAuditCopiedLinkBtn": "✓ Đã chép link!", "shareAuditCopyLinkBtn": "Chép link", + "shareAuditDownloadPngTitle": "Tải ảnh thẻ sự thật (PNG 4:5) để chia sẻ lên diễn đàn hoặc nhóm chat", + "shareAuditDownloadPngBtn": "Tải thẻ sự thật (PNG 4:5)", "specsToolbarCopiedMd": "Đã chép 10 nhóm thông số!", "specsToolbarCopyMd": "Sao chép 10 nhóm thông số MD", "specsToolbarExportCsv": "Xuất CSV thông số", diff --git a/apps/web/src/app/[locale]/compare/[versus]/page.tsx b/apps/web/src/app/[locale]/compare/[versus]/page.tsx index d54f4ca7..a275ea04 100644 --- a/apps/web/src/app/[locale]/compare/[versus]/page.tsx +++ b/apps/web/src/app/[locale]/compare/[versus]/page.tsx @@ -18,7 +18,13 @@ import { import { catalogRowSlug, type ItemCatalogRow } from '@/lib/item-directory'; import { getItemSlugsFor } from '@/server/rate/item-directory'; import { normalizeRateLocale } from '@/lib/rate-i18n'; -import { defaultOpenGraph, fitTitle, fitDescription } from '@/lib/seo'; +import { + buildOgTruthCardImage, + defaultOpenGraph, + defaultTwitterCard, + fitTitle, + fitDescription, +} from '@/lib/seo'; import { scoreMasterProductForLeaderboard } from '@/lib/leaderboard-engine'; import PageShell from '../../components/page-shell'; import CompareWorkspace from '@/components/compare/CompareWorkspace'; @@ -102,9 +108,12 @@ export async function generateMetadata({ return notFoundMeta(); } + const canonicalVersusSlug = plan + ? plan.canonical.replace(/^\/compare\//, '') + : `${pair[0]}-vs-${pair[1]}`; const canonicalUrl = plan ? `https://rate.vn${plan.canonical}` - : `https://rate.vn/compare/${pair[0]}-vs-${pair[1]}`; + : `https://rate.vn/compare/${canonicalVersusSlug}`; const fullTitle = t('versusMetaTitle', { nameA: a.name, nameB: b.name }); // Both names first; the fixed text, then the site name, give way to fit a // search result (DOS/Rate#777). The share card keeps the full title. @@ -124,6 +133,12 @@ export async function generateMetadata({ }), lang ); + const ogImage = buildOgTruthCardImage({ + type: 'versus', + versus: canonicalVersusSlug, + locale: lang, + alt: `${a.name} vs ${b.name}`, + }); return { title, @@ -136,7 +151,9 @@ export async function generateMetadata({ title: fullTitle, description, url: canonicalUrl, + images: [ogImage], }, + twitter: defaultTwitterCard(ogImage), }; } diff --git a/apps/web/src/app/[locale]/deals/page.tsx b/apps/web/src/app/[locale]/deals/page.tsx index dcdc52b2..97bf3498 100644 --- a/apps/web/src/app/[locale]/deals/page.tsx +++ b/apps/web/src/app/[locale]/deals/page.tsx @@ -9,6 +9,11 @@ import { type ItemCatalogRow, } from '@/server/rate'; import { normalizeRateLocale } from '@/lib/rate-i18n'; +import { + buildOgTruthCardImage, + defaultOpenGraph, + defaultTwitterCard, +} from '@/lib/seo'; import PageShell from '../components/page-shell'; import CompareTrayBar from '@/components/compare/CompareTrayBar'; import DealFinderWorkspace from '@/components/deals/DealFinderWorkspace'; @@ -26,12 +31,28 @@ export async function generateMetadata({ const { locale } = await params; const lang = normalizeRateLocale(locale); const t = await getTranslations({ locale: lang, namespace: 'deals' }); + const title = t('metaTitle'); + const description = t('metaDescription'); + const canonicalUrl = 'https://rate.vn/deals'; + const ogImage = buildOgTruthCardImage({ + type: 'deals', + locale: lang, + alt: title, + }); return { - title: t('metaTitle'), - description: t('metaDescription'), + title, + description, alternates: { - canonical: 'https://rate.vn/deals', + canonical: canonicalUrl, + }, + openGraph: { + ...defaultOpenGraph(lang), + title, + description, + url: canonicalUrl, + images: [ogImage], }, + twitter: defaultTwitterCard(ogImage), }; } diff --git a/apps/web/src/app/[locale]/smartphones/[slug]/page.tsx b/apps/web/src/app/[locale]/smartphones/[slug]/page.tsx index 10fd014d..8121bd88 100644 --- a/apps/web/src/app/[locale]/smartphones/[slug]/page.tsx +++ b/apps/web/src/app/[locale]/smartphones/[slug]/page.tsx @@ -72,9 +72,10 @@ import { startRenderTiming } from '@/lib/render-timing'; import { bayesianTierKey, radarExplanation } from '@/lib/product-detail-copy'; import { absoluteUrl, + buildOgTruthCardImage, defaultOpenGraph, + defaultTwitterCard, fitTitle, - SHARE_IMAGE, fitDescription, } from '@/lib/seo'; import JReviewsSection from '@/components/reviews/JReviewsSection'; @@ -246,9 +247,15 @@ export async function generateCategoryProductMetadata( const hasPrice = marketStats.minPrice > 0; const name = (isItemGroup ? itemMeta?.name : null) || product.name; const minPrice = formatNumber(marketStats.minPrice, locale); - const canonicalUrl = `https://rate.vn${categoryBasePath}/${ - itemRoute?.kind === 'render' ? itemRoute.itemSlug : product.slug - }`; + const canonicalSlug = + itemRoute?.kind === 'render' ? itemRoute.itemSlug : product.slug; + const canonicalUrl = `https://rate.vn${categoryBasePath}/${canonicalSlug}`; + const ogImage = buildOgTruthCardImage({ + type: 'product', + slug: canonicalSlug, + locale: lang, + alt: name, + }); return { // The product name first; the site name, then the price give way to fit @@ -285,18 +292,12 @@ export async function generateCategoryProductMetadata( title: t('ogTitle', { name }), description: hasPrice ? t('ogDesc', { minPrice }) : t('ogDescNoStock'), url: canonicalUrl, - // A credited photo carries its notice only on the page, so a share - // preview uses the site image instead (DOS/Rate#1756). - images: [shareImage(firstImageUrl(product.images))], + images: [ogImage], }, + twitter: defaultTwitterCard(ogImage), }; } -/** The Open Graph image: the product photo, unless it needs a credit. */ -function shareImage(src: string | null): string | typeof SHARE_IMAGE { - return src && !deviceImageCredit(src) ? src : SHARE_IMAGE; -} - export async function generateMetadata({ params, }: { @@ -881,6 +882,7 @@ export async function ProductDetailView({ {t('auditPriceBtn', { count: v.offers.length })} Promise; + readonly resolveVersus: ( + pair: readonly [string, string] + ) => Promise; + readonly resolveDeals: () => Promise; + readonly rateLimiter?: BoundedSlidingWindowRateLimiter; +} + +function pickDefaultItemVariant( + variants: readonly RateItemVariant[], + defaultId: string | null | undefined +): RateItemVariant | undefined { + return ( + variants.find((v) => v.id === defaultId && v.min_price > 0) ?? + variants.find((v) => v.min_price > 0) ?? + variants.find((v) => v.id === defaultId) ?? + variants[0] + ); +} + +async function defaultResolveProductTruthCard( + slug: string, + variantKey?: string | null +): Promise { + const lowerSlug = slug.toLowerCase(); + let displaySlug = lowerSlug; + let displayNameOverride: string | null = null; + let itemGroupStats: { + minPrice: number; + maxPrice: number; + sellerCount: number; + } | null = null; + let product = null; + let resolvedViaItemModel = false; + + if (isItemModelOn()) { + try { + const exactRes = await getCachedCatalogSlugResolution(slug); + const resolution = + exactRes ?? + (slug !== lowerSlug + ? await getCachedCatalogSlugResolution(lowerSlug) + : null); + if (resolution?.kind === 'item') { + resolvedViaItemModel = true; + const variants = await getCachedItemVariants(resolution.item); + if (variantKey) { + const explicitVar = variants.find( + (v) => v.variant_key === variantKey + ); + if (!explicitVar) { + return null; + } + product = await getCachedMasterProductBySlug(explicitVar.slug); + if (product) { + displaySlug = product.slug; + } + } else { + const picked = pickDefaultItemVariant( + variants, + resolution.item.default_variant_id + ); + if (picked) { + product = await getCachedMasterProductBySlug(picked.slug); + if (product) { + displaySlug = resolution.item.slug; + displayNameOverride = resolution.item.name || null; + if (variants.length > 1) { + itemGroupStats = itemFromStats(variants); + } + } + } + } + } else if (resolution?.kind === 'variant') { + resolvedViaItemModel = true; + product = await getCachedMasterProductBySlug(resolution.variant.slug); + if (product) { + displaySlug = resolution.variant.slug; + } else { + const variants = await getCachedItemVariants(resolution.item); + const fallbackVar = pickDefaultItemVariant( + variants, + resolution.item.default_variant_id + ); + if (fallbackVar) { + product = await getCachedMasterProductBySlug(fallbackVar.slug); + if (product) { + displaySlug = resolution.item.slug || product.slug; + displayNameOverride = resolution.item.name || null; + if (variants.length > 1) { + itemGroupStats = itemFromStats(variants); + } + } + } + } + } + } catch (err) { + if (!(err instanceof ItemModelUnavailableError)) { + throw err; + } + } + } + + if (!product && !resolvedViaItemModel) { + if (variantKey) { + return null; + } + product = await getCachedMasterProductBySlug(slug); + if (product) { + displaySlug = product.slug; + } + } + + if (!product) { + return null; + } + + const [offers, filteredCounts, categorySlugById] = await Promise.all([ + getCachedMasterProductOffers(product.id), + getCachedFilteredReviewCountsByMaster().catch( + (): Record => ({}) + ), + getCachedCategorySlugById().catch(() => new Map()), + ]); + + const inStockOffers = offers.filter((o) => !isOfferUnavailable(o)); + const radarSignal = computeProductRadarSignal(product, inStockOffers); + const marketStats = itemGroupStats ?? productMarketStats(product); + const href = getMasterProductHref(product, categorySlugById); + const categoryPath = href.split('/').slice(0, 2).join('/') || '/smartphones'; + + const userScore5 = resolveCompareEffectiveUserRating(product); + const expertScore10 = resolveCompareExpertRating10(product); + const authenticReviews = Math.max( + 0, + Math.floor( + Number(product.authentic_review_count ?? product.total_reviews ?? 0) || 0 + ) + ); + const rawFilteredCount = + filteredCounts instanceof Map + ? filteredCounts.get(product.id) + : filteredCounts && + typeof filteredCounts === 'object' && + Object.hasOwn(filteredCounts, product.id) + ? (filteredCounts as Record)[product.id] + : 0; + const filteredReviews = Math.max( + 0, + Math.floor(Number(rawFilteredCount ?? 0) || 0) + ); + + const radarKind = + radarSignal.verdict === 'genuine_deal' + ? isMultiPlatformFloor(radarSignal.genuineDeal) + ? 'multi_platform_floor' + : 'below_median' + : radarSignal.verdict === 'fake_sale_trap' + ? 'fake_sale_trap' + : 'verified'; + + return { + type: 'product', + slug: displaySlug, + categoryPath, + name: displayNameOverride || product.name, + brand: product.brand, + minPriceVnd: marketStats.minPrice, + maxPriceVnd: marketStats.maxPrice, + sellerCount: marketStats.sellerCount, + userScore5, + expertScore10, + authenticReviews, + filteredReviews, + radarKind, + savingsPct: radarSignal.savingsPct, + fakeMarkupPct: radarSignal.fakeMarkupPct, + hasFakeSaleTrap: radarSignal.fakeSaleTrap !== null, + }; +} + +async function defaultResolveVersusTruthCard( + pair: readonly [string, string] +): Promise { + let effectivePlan = await resolveVersusPlan(pair[0], pair[1]); + if (effectivePlan?.kind === 'redirect') { + const redirectedVersus = effectivePlan.to + .split('?')[0]! + .replace(/^\/compare\//, ''); + const redirectPair = parseOgVersusPair(redirectedVersus, 120, true); + if (!redirectPair) { + return null; + } + effectivePlan = await resolveVersusPlan(redirectPair[0], redirectPair[1]); + } + if (effectivePlan && effectivePlan.kind !== 'render') { + return null; + } + + let resolvedPair: [string, string]; + let canonicalVersusSlug: string; + + if (effectivePlan?.kind === 'render') { + resolvedPair = [effectivePlan.slugA, effectivePlan.slugB]; + canonicalVersusSlug = effectivePlan.canonical.replace(/^\/compare\//, ''); + } else { + resolvedPair = canonicalVersusOrder( + pair[0].toLowerCase(), + pair[1].toLowerCase() + ); + canonicalVersusSlug = `${resolvedPair[0]}-vs-${resolvedPair[1]}`; + } + + const compared = await getCachedCompareMasterProducts(resolvedPair.join(',')); + const [prodA, prodB] = inPairOrder(compared, resolvedPair); + if (!prodA || !prodB) { + return null; + } + + const scoreA = scoreMasterProductForLeaderboard( + withScoringSpecs(prodA), + 'combined' + ); + const scoreB = scoreMasterProductForLeaderboard( + withScoringSpecs(prodB), + 'combined' + ); + const overall = computeVersusWeightedResult( + scoreA, + scoreB, + PERSONA_WEIGHTS.default, + 'default' + ); + const criteriaRows = versusCriteriaHeadToHead(scoreA, scoreB); + const winsA = criteriaRows.filter((r) => r.winner === 'A').length; + const winsB = criteriaRows.filter((r) => r.winner === 'B').length; + const statsA = productMarketStats(prodA); + const statsB = productMarketStats(prodB); + + return { + type: 'versus', + versusSlug: canonicalVersusSlug, + itemA: { + slug: prodA.slug, + name: prodA.name, + brand: prodA.brand, + score5: overall.finalA, + minPriceVnd: statsA.minPrice, + sellerCount: statsA.sellerCount, + criterionWins: winsA, + }, + itemB: { + slug: prodB.slug, + name: prodB.name, + brand: prodB.brand, + score5: overall.finalB, + minPriceVnd: statsB.minPrice, + sellerCount: statsB.sellerCount, + criterionWins: winsB, + }, + winnerSide: overall.tie ? 'tie' : overall.winnerSide, + scoreDelta: overall.delta, + }; +} + +async function defaultResolveDealsTruthCard(): Promise { + const radar = await getCrossPlatformDealRadar({ + categorySlug: 'all', + limit: 50, + }); + + return { + type: 'deals', + genuineDealCount: radar.genuineDeals.length, + fakeSaleTrapCount: radar.fakeSaleTraps.length, + totalOffersAnalyzed: radar.totalOffersAnalyzed, + totalClustersAnalyzed: radar.totalClustersAnalyzed, + topDeals: radar.genuineDeals.slice(0, 4).map((deal) => ({ + name: deal.productName, + minPriceVnd: deal.priceCurrent, + savingsPct: deal.savingsVsMedianPct, + offerCount: deal.marketOfferCount, + })), + }; +} + +const DEFAULT_RESOLVERS: OgTruthCardResolvers = { + resolveProduct: defaultResolveProductTruthCard, + resolveVersus: defaultResolveVersusTruthCard, + resolveDeals: defaultResolveDealsTruthCard, +}; + +export async function OPTIONS() { + return new NextResponse(null, { + status: 204, + headers: PUBLIC_API_CORS_HEADERS, + }); +} + +export async function handleOgTruthCardRequest( + request: NextRequest, + resolvers: OgTruthCardResolvers = DEFAULT_RESOLVERS +): Promise { + const limiter = resolvers.rateLimiter ?? ogTruthCardRateLimiter; + const clientKey = extractClientRateLimitKey(request.headers); + if (!limiter.allow(clientKey)) { + return rateLimitExceededResponse( + 'Rate limit exceeded. Maximum 60 OG card renders per minute.', + { + ...PUBLIC_API_CORS_HEADERS, + 'Cache-Control': 'no-store', + }, + 60 + ); + } + + const parsed = parseOgTruthCardQuery( + request.nextUrl.searchParams, + request.nextUrl.search + ); + if (!parsed) { + return jsonApiError( + 400, + 'Invalid or unsupported OG truth card query parameters.', + undefined, + { 'Cache-Control': 'no-store' } + ); + } + + try { + let cardData: OgTruthCardData | null = null; + if (parsed.type === 'product') { + cardData = await resolvers.resolveProduct(parsed.slug, parsed.variant); + } else if (parsed.type === 'versus') { + cardData = await resolvers.resolveVersus(parsed.pair); + } else { + cardData = await resolvers.resolveDeals(); + } + + if (!cardData) { + return jsonApiError( + 404, + 'Catalog entity not found for OG truth card.', + undefined, + { 'Cache-Control': 'public, max-age=0, s-maxage=60' } + ); + } + + return await renderOgTruthCardHttpResponse(cardData, { + format: parsed.format, + locale: parsed.locale, + download: parsed.download, + extraHeaders: PUBLIC_API_CORS_HEADERS, + }); + } catch { + return jsonApiError(500, 'Failed to generate OG truth card.', undefined, { + 'Cache-Control': 'no-store', + }); + } +} + +export async function GET(request: NextRequest): Promise { + return handleOgTruthCardRequest(request, DEFAULT_RESOLVERS); +} diff --git a/apps/web/src/components/leaderboard/ProductShareAuditButton.tsx b/apps/web/src/components/leaderboard/ProductShareAuditButton.tsx index 096fa824..e8909ab1 100644 --- a/apps/web/src/components/leaderboard/ProductShareAuditButton.tsx +++ b/apps/web/src/components/leaderboard/ProductShareAuditButton.tsx @@ -18,8 +18,14 @@ import { localizeDecimalPoints, } from '@/lib/locale-format'; import { formatScoreFixed, roundScore } from '@/lib/rating-display'; +import { + buildOgTruthCardPath, + isValidOgSlug, + isValidOgVariantKey, +} from '@/lib/seo'; interface ProductShareAuditButtonProps { + readonly slug?: string; readonly name: string; readonly brand: string; readonly modelKey: string; @@ -32,6 +38,55 @@ interface ProductShareAuditButtonProps { readonly radarSignal?: RadarSignal; } +const PRODUCT_DETAIL_PATH_SLUG_RE = + /^\/(?:(?:vi|en|cs)\/)?(?:smartphones|tablets|laptops|smartwatches|earbuds)\/([^/?#]+)\/?$/i; + +export function resolveShareAuditOgDownloadUrl(input: { + readonly slug?: string | null; + readonly pathname?: string | null; + readonly search?: string | null; + readonly locale?: string | null; +}): string | null { + const explicitSlug = + typeof input.slug === 'string' + ? input.slug.replace(/\p{Cc}+/gu, '').trim() + : ''; + let resolvedSlug = isValidOgSlug(explicitSlug, 120) ? explicitSlug : ''; + let resolvedVariant: string | null = null; + + if (!resolvedSlug && typeof input.pathname === 'string') { + const match = input.pathname.trim().match(PRODUCT_DETAIL_PATH_SLUG_RE); + if (match?.[1]) { + try { + const decoded = decodeURIComponent(match[1]).trim(); + if (isValidOgSlug(decoded, 120)) { + resolvedSlug = decoded; + } + } catch { + // Ignore malformed percent-encoding in pathname. + } + } + if (resolvedSlug && typeof input.search === 'string' && input.search) { + const rawVar = new URLSearchParams(input.search).get('v'); + const cleanVar = + typeof rawVar === 'string' ? rawVar.trim().toLowerCase() : ''; + if (isValidOgVariantKey(cleanVar)) { + resolvedVariant = cleanVar; + } + } + } + + if (!resolvedSlug) return null; + return buildOgTruthCardPath({ + type: 'product', + slug: resolvedSlug, + variant: resolvedVariant, + locale: input.locale, + format: 'social', + download: true, + }); +} + export function sanitizeShareAuditText( value: unknown, maxLength = 200, @@ -205,6 +260,7 @@ export function normalizeShareAuditFields(input: { } export default function ProductShareAuditButton({ + slug, name, brand, modelKey, @@ -346,11 +402,40 @@ export default function ProductShareAuditButton({ URL.revokeObjectURL(url); }; + const handleDownloadTruthCardPng = () => { + if (typeof window === 'undefined') return; + const downloadUrl = resolveShareAuditOgDownloadUrl({ + slug, + pathname: window.location.pathname, + search: window.location.search, + locale, + }); + if (!downloadUrl) return; + const a = document.createElement('a'); + a.href = downloadUrl; + a.download = `rate-truth-card-${safeModelKeyToken}-4x5.png`; + a.rel = 'noopener'; + document.body.appendChild(a); + a.click(); + a.remove(); + }; + return (
{(close) => ( <> +
+ + {/* RTINGS-style Use-Case Presets & Custom Weight Sliders (#1864) */} + {canWeighCompare && ( +
+ setShowWeightSliders((v) => !v)} + onSelectPreset={handleSelectComparePreset} + onUpdateWeight={handleUpdateCompareWeight} + onReset={handleResetCompareWeights} + locale={locale} + testIdPrefix="compare-weights" + copy={{ + groupLabel: t('useCaseLabel'), + customizeBtn: t('customWeightsBtn'), + customActiveBadge: t('customWeightsActive'), + resetBtn: t('resetWeightsBtn'), + normalizedSummaryPrefix: t('normalizedWeightsPrefix'), + officialKeepNote: t('officialScoreKeepNote'), + }} + /> + +
+ {hasActiveCompareWeights && customCompareWinner && ( +
+
+ + {t('yourCustomScoreLabel')} + + + {customCompareWinner.isTie + ? t('customWinnerTie', { + preset: activeComparePresetTitle, + score: formatRatingValue( + customCompareWinner.leadScore5, + locale, + 2 + ), + }) + : customCompareWinner.delta5 !== null && + customCompareWinner.scoredCount >= 2 + ? t('customWinnerSummary', { + preset: activeComparePresetTitle, + winner: customCompareWinner.leadProduct.name, + score: formatRatingValue( + customCompareWinner.leadScore5, + locale, + 2 + ), + delta: formatRatingValue( + customCompareWinner.delta5, + locale, + 2 + ), + }) + : t('customWinnerSingle', { + preset: activeComparePresetTitle, + winner: customCompareWinner.leadProduct.name, + score: formatRatingValue( + customCompareWinner.leadScore5, + locale, + 2 + ), + })} + +
+
+ )} +
+
+ )} ); @@ -3628,7 +4059,12 @@ export default function CompareWorkspace({ {/* Core Rating Badges First (Per DESIGN.md v3.0) */} -
+
+ {hasActiveCompareWeights && ( + + {t('officialRateScoreLabel')} + + )} + {hasActiveCompareWeights && + (() => { + const customEntry = customCompareScoresById.get( + p.id + ); + const customVal = + customEntry?.customScore5 ?? null; + const isCustomWinner = + highlightWinners && + customVal !== null && + customCompareWinner !== null && + !customCompareWinner.isTie && + customCompareWinner.scoredCount >= 2 && + customCompareWinner.winnerIds.has(p.id); + return ( +
+ {customVal !== null + ? `${t('yourCustomScoreLabel')}: ★ ${formatRatingValue(customVal, locale, 2)}/5` + : `${t('yourCustomScoreLabel')}: ${t('criterionNoData')}`} + {isCustomWinner && ( + + {t('bestBadge')} + + )} +
+ ); + })()} + {/* Neutral Reference Price */}
{t('referencePriceLabel')}{' '} @@ -3739,6 +4213,54 @@ export default function CompareWorkspace({ + {hasActiveCompareWeights && ( + + +
{t('yourCustomScoreLabel')}
+
+ {activeComparePresetTitle} +
+ + {products.map((p) => { + const customVal = + customCompareScoresById.get(p.id)?.customScore5 ?? null; + const isCustomWinner = + highlightWinners && + customVal !== null && + customCompareWinner !== null && + !customCompareWinner.isTie && + customCompareWinner.scoredCount >= 2 && + customCompareWinner.winnerIds.has(p.id); + return ( + + {customVal !== null + ? `★ ${formatRatingValue(customVal, locale, 2)} / 5` + : t('criterionNoData')} + {isCustomWinner && ( + + {t('bestBadge')} + + )} + + ); + })} + {products.length < MAX_COMPARE_ITEMS && ( + - + )} + + )} {t('radarRowMatrixTitle')} @@ -3919,6 +4441,12 @@ export default function CompareWorkspace({ return (
+ + + {controlsBlock} {popularBlock} {summaryBlock} diff --git a/apps/web/src/components/compare/UseCaseWeightBar.tsx b/apps/web/src/components/compare/UseCaseWeightBar.tsx new file mode 100644 index 00000000..c77d85a6 --- /dev/null +++ b/apps/web/src/components/compare/UseCaseWeightBar.tsx @@ -0,0 +1,302 @@ +'use client'; + +import React, { useId } from 'react'; +import { BsArrowCounterclockwise, BsSliders } from 'react-icons/bs'; +import { + getRatingCriteria, + getRatingCriterionLabel, + getRatingUseCasePresetLabel, + type RatingCriterionKey, + type UseCasePresetId, +} from '@repo/shared-data/rules'; +import { formatPercent } from '@/lib/locale-format'; +import { + availableCategoryUseCasePresets, + formatNormalizedWeightSummary, + isDefaultCategoryWeights, + normalizeCategoryWeights, + type ActiveWeightMode, + type CategoryCriterionWeights, +} from '@/lib/use-case-weights'; + +export interface UseCaseWeightBarCopy { + readonly groupLabel: string; + readonly customizeBtn: string; + readonly customActiveBadge: string; + readonly resetBtn: string; + readonly normalizedSummaryPrefix: string; + readonly officialKeepNote: string; + readonly presetLabels?: Readonly>>; + readonly criterionLabels?: Readonly< + Partial> + >; +} + +export interface UseCaseWeightBarProps { + readonly categorySlug: string; + readonly availableCriteria: readonly RatingCriterionKey[]; + readonly mode: ActiveWeightMode; + readonly weights: CategoryCriterionWeights; + readonly showSliders: boolean; + readonly onToggleSliders: () => void; + readonly onSelectPreset: (presetId: UseCasePresetId) => void; + readonly onUpdateWeight: (key: RatingCriterionKey, value: number) => void; + readonly onReset: () => void; + readonly copy: UseCaseWeightBarCopy; + readonly locale?: string; + readonly variant?: 'light' | 'dark'; + readonly groupLabelId?: string; + readonly slidersPanelId?: string; + readonly trailingActions?: React.ReactNode; + readonly testIdPrefix?: string; +} + +export default function UseCaseWeightBar({ + categorySlug, + availableCriteria, + mode, + weights, + showSliders, + onToggleSliders, + onSelectPreset, + onUpdateWeight, + onReset, + copy, + locale = 'vi', + variant = 'light', + groupLabelId: groupLabelIdProp, + slidersPanelId: slidersPanelIdProp, + trailingActions, + testIdPrefix = 'use-case-weights', +}: UseCaseWeightBarProps) { + const reactId = useId(); + const groupLabelId = groupLabelIdProp || `${reactId}-group-label`; + const slidersPanelId = slidersPanelIdProp || `${reactId}-sliders-panel`; + const isDark = variant === 'dark'; + + const presets = availableCategoryUseCasePresets( + categorySlug, + availableCriteria + ); + const criteria = getRatingCriteria(categorySlug); + const availableSet = new Set(availableCriteria); + const sliderCriteria = criteria.filter((c) => availableSet.has(c.key)); + if (presets.length === 0 || sliderCriteria.length === 0) { + return trailingActions ? ( +
+ {trailingActions} +
+ ) : null; + } + + const normalized = normalizeCategoryWeights( + categorySlug, + weights, + availableCriteria + ); + const isDefault = isDefaultCategoryWeights( + categorySlug, + mode, + weights, + availableCriteria + ); + const weightSummary = formatNormalizedWeightSummary( + categorySlug, + normalized.normalizedPercent, + locale, + copy.criterionLabels, + availableCriteria + ); + + const resolvePresetLabel = ( + presetId: UseCasePresetId, + fallbackObj: { label: { vi: string; en: string; cs: string } } + ) => { + const customText = + copy.presetLabels && + Object.prototype.hasOwnProperty.call(copy.presetLabels, presetId) + ? copy.presetLabels[presetId] + : undefined; + return customText && customText.trim() + ? customText + : getRatingUseCasePresetLabel(fallbackObj, locale); + }; + + const resolveCriterionText = ( + criterionKey: RatingCriterionKey, + fallbackObj: { label: { vi: string; en: string; cs: string } } + ) => { + const customText = + copy.criterionLabels && + Object.prototype.hasOwnProperty.call(copy.criterionLabels, criterionKey) + ? copy.criterionLabels[criterionKey] + : undefined; + return customText && customText.trim() + ? customText + : getRatingCriterionLabel(fallbackObj, locale); + }; + + return ( +
+
+
+ + {copy.groupLabel} + + + {presets.map((preset) => { + const isSelected = mode === preset.id; + const btnClass = isDark + ? isSelected + ? 'btn-primary fw-bold text-white' + : 'btn-outline-light' + : isSelected + ? 'btn-primary fw-semibold text-white shadow-sm' + : 'btn-outline-dark'; + return ( + + ); + })} + + + + {!isDefault && ( + + )} +
+ + {trailingActions && ( +
+ {trailingActions} +
+ )} +
+ + {(!isDefault || showSliders) && weightSummary && ( +
+ {copy.normalizedSummaryPrefix}{' '} + {weightSummary} + {!isDefault && copy.officialKeepNote ? ( + {` · ${copy.officialKeepNote}`} + ) : null} +
+ )} + + {showSliders && sliderCriteria.length > 0 && ( +
+
+ {sliderCriteria.map((criterion) => { + const sliderId = `${reactId}-slider-${criterion.key}`; + const labelText = resolveCriterionText(criterion.key, criterion); + const rawVal = normalized.sliderWeights[criterion.key] ?? 0; + const normPct = normalized.normalizedPercent[criterion.key] ?? 0; + return ( +
+
+ + + {formatPercent(normPct, locale)} + +
+ + onUpdateWeight(criterion.key, Number(e.target.value)) + } + className="form-range" + /> +
+ ); + })} +
+
+ )} +
+ ); +} diff --git a/apps/web/src/components/compare/VersusInteractiveScoreboard.tsx b/apps/web/src/components/compare/VersusInteractiveScoreboard.tsx index 94b63089..8e4ab67d 100644 --- a/apps/web/src/components/compare/VersusInteractiveScoreboard.tsx +++ b/apps/web/src/components/compare/VersusInteractiveScoreboard.tsx @@ -1,14 +1,47 @@ 'use client'; -import { useId, useMemo, useState } from 'react'; +import { + Suspense, + useCallback, + useEffect, + useId, + useMemo, + useState, +} from 'react'; +import { useSearchParams } from 'next/navigation'; import { useLocale, useTranslations } from 'next-intl'; -import { BsSliders } from 'react-icons/bs'; +import type { + RatingCriterionKey, + UseCasePresetId, +} from '@repo/shared-data/rules'; import { Link } from '@/lib/navigation'; import { MAX_VALID_VND_PRICE, comparePositiveMinPrices, } from '@/lib/rate-domain'; -import { sharedScoredCriteria } from '@/lib/leaderboard-engine'; +import { + CRITERION_RANK_WRITERS, + sharedScoredCriteria, +} from '@/lib/leaderboard-engine'; +import { + availableCategoryUseCasePresets, + computeCustomWeightedScore5, + defaultCategoryWeights, + extractCategoryCriteriaScores, + isDefaultCategoryWeights, + mergeUseCaseQueryIntoSearch, + normalizeCategoryWeights, + parseUseCaseWeightsFromParams, + resolveCategoryPreset, + resolveLocalizedPresetName, + sanitizeSliderWeight, + sharedCategoryCriteriaForPair, + toLegacyCriteriaWeights, + toLegacyVersusPersona, + type ActiveWeightMode, + type CategoryCriterionWeights, +} from '@/lib/use-case-weights'; +import UseCaseWeightBar from './UseCaseWeightBar'; import { getRadarSignal, RADAR_CSV_HEADERS, @@ -46,6 +79,7 @@ import { displayedScore5, formatRatingValue, formatScoreFixed, + roundScore, } from '@/lib/rating-display'; export { @@ -65,6 +99,9 @@ interface VersusInteractiveScoreboardProps { readonly scoreA: ScoredVersusItem; readonly scoreB: ScoredVersusItem; readonly locale?: string; + readonly initialWeightMode?: ActiveWeightMode; + readonly initialCategoryWeights?: CategoryCriterionWeights; + readonly initialShowSliders?: boolean; } export function sanitizeVersusExportSlug(value: unknown): string { @@ -199,16 +236,41 @@ export function formatVersusWeightedMarkdown( }; } +function VersusUrlWeightsSync({ + categorySlug, + onSync, +}: { + readonly categorySlug: string; + readonly onSync: ( + cat: string, + rawPreset: string | null, + rawWeights: string | null + ) => void; +}) { + const searchParams = useSearchParams(); + const rawPreset = searchParams.get('preset'); + const rawWeights = searchParams.get('weights'); + useEffect( + () => onSync(categorySlug, rawPreset, rawWeights), + [categorySlug, rawPreset, rawWeights, onSync] + ); + return null; +} + export default function VersusInteractiveScoreboard({ scoreA: firstScore, scoreB: secondScore, locale: localeProp, + initialWeightMode = 'default', + initialCategoryWeights, + initialShowSliders = false, }: VersusInteractiveScoreboardProps) { // A pair has one URL, its sides sorted (DOS/Rate#1367), so the swap button // swaps the two sides here instead of linking to the other order. const [swapped, setSwapped] = useState(false); const scoreA = swapped ? secondScore : firstScore; const scoreB = swapped ? firstScore : secondScore; + const catSlug = scoreA.categorySlug || 'smartphones'; const t = useTranslations('compare'); const tStars = useTranslations('starRating'); const hookLocale = useLocale(); @@ -218,26 +280,138 @@ export default function VersusInteractiveScoreboard({ score > 0 ? formatRatingValue(score, locale) : tStars('empty'); const useCaseLabelId = useId(); const slidersPanelId = useId(); - const [persona, setPersona] = useState('default'); - const [weights, setWeights] = useState( - PERSONA_WEIGHTS.default - ); - const [showSliders, setShowSliders] = useState(false); + const [weightMode, setWeightMode] = + useState(initialWeightMode); + const [categoryWeights, setCategoryWeights] = + useState(() => { + if (initialCategoryWeights) { + return normalizeCategoryWeights(catSlug, initialCategoryWeights) + .sliderWeights; + } + if (initialWeightMode !== 'default' && initialWeightMode !== 'custom') { + return normalizeCategoryWeights( + catSlug, + resolveCategoryPreset(catSlug, initialWeightMode).weights + ).sliderWeights; + } + return defaultCategoryWeights(catSlug); + }); + const [showSliders, setShowSliders] = useState(initialShowSliders); const [copiedVerdict, setCopiedVerdict] = useState(false); const radarIndex = useDealRadarIndex(); - const selectPersona = (next: Exclude) => { - setPersona(next); - setWeights(PERSONA_WEIGHTS[next]); + const catScoresA = useMemo( + () => + extractCategoryCriteriaScores( + scoreA.product, + catSlug, + CRITERION_RANK_WRITERS, + scoreA.rankCriteria + ), + [scoreA.product, scoreA.rankCriteria, catSlug] + ); + const catScoresB = useMemo( + () => + extractCategoryCriteriaScores( + scoreB.product, + catSlug, + CRITERION_RANK_WRITERS, + scoreB.rankCriteria + ), + [scoreB.product, scoreB.rankCriteria, catSlug] + ); + const sharedCategoryCriteria = useMemo( + () => sharedCategoryCriteriaForPair(catSlug, catScoresA, catScoresB), + [catSlug, catScoresA, catScoresB] + ); + + const replaceVersusQuery = useCallback( + ( + nextMode: ActiveWeightMode, + nextWeights: CategoryCriterionWeights, + available: readonly RatingCriterionKey[] + ) => { + if (typeof window === 'undefined') return; + const merged = + available.length > 0 + ? mergeUseCaseQueryIntoSearch( + window.location.search, + catSlug, + nextMode, + nextWeights, + available + ) + : mergeUseCaseQueryIntoSearch( + window.location.search, + catSlug, + 'default', + defaultCategoryWeights(catSlug), + [] + ); + window.history.replaceState( + null, + '', + `${window.location.pathname}${merged}` + ); + }, + [catSlug] + ); + + const handleUrlWeightsSync = useCallback( + (cat: string, rawPreset: string | null, rawWeights: string | null) => { + const parsed = parseUseCaseWeightsFromParams(cat, { + preset: rawPreset ?? undefined, + weights: rawWeights ?? undefined, + }); + setWeightMode(parsed.mode); + setCategoryWeights(parsed.weights); + }, + [] + ); + + const selectUseCasePreset = (presetId: UseCasePresetId) => { + const preset = resolveCategoryPreset(catSlug, presetId); + const norm = normalizeCategoryWeights( + catSlug, + preset.weights, + sharedCategoryCriteria + ); + setWeightMode(preset.id); + setCategoryWeights(norm.sliderWeights); + replaceVersusQuery(preset.id, norm.sliderWeights, sharedCategoryCriteria); }; - const updateWeight = (key: keyof CriteriaWeights, val: number) => { - setPersona('custom'); - const safeVal = Number.isFinite(val) ? Math.max(0, Math.min(100, val)) : 0; - setWeights((prev) => ({ - ...prev, - [key]: safeVal, - })); + const updateCategoryWeight = (key: RatingCriterionKey, val: number) => { + const candidate: CategoryCriterionWeights = { + ...categoryWeights, + [key]: sanitizeSliderWeight(val, categoryWeights[key] ?? 0), + }; + const normalized = normalizeCategoryWeights( + catSlug, + candidate, + sharedCategoryCriteria + ); + const collapsesToDefault = + normalized.wasAllZeroReset || + isDefaultCategoryWeights( + catSlug, + 'custom', + normalized.sliderWeights, + sharedCategoryCriteria + ); + const nextMode: ActiveWeightMode = collapsesToDefault + ? 'default' + : 'custom'; + const nextWeights = collapsesToDefault + ? defaultCategoryWeights(catSlug) + : normalized.sliderWeights; + setWeightMode(nextMode); + setCategoryWeights(nextWeights); + replaceVersusQuery(nextMode, nextWeights, sharedCategoryCriteria); + }; + + const resetVersusWeights = () => { + selectUseCasePreset('default'); }; const safeMinPriceA = resolveVersusScoreMinPriceVnd(scoreA); @@ -260,7 +434,85 @@ export default function VersusInteractiveScoreboard({ [scoreA.rankCriteria, scoreB.rankCriteria] ); const availablePersonas = versusAvailablePersonas(sharedCriteria); - const canWeigh = availablePersonas.length > 0; + const availableCategoryPresets = useMemo( + () => availableCategoryUseCasePresets(catSlug, sharedCategoryCriteria), + [catSlug, sharedCategoryCriteria] + ); + const canWeigh = + availablePersonas.length > 0 && availableCategoryPresets.length > 0; + + useEffect(() => { + if (!canWeigh) { + if (weightMode !== 'default' || showSliders) { + const defaults = defaultCategoryWeights(catSlug); + setWeightMode('default'); + setShowSliders(false); + setCategoryWeights(defaults); + replaceVersusQuery('default', defaults, []); + } + return; + } + if ( + weightMode !== 'default' && + (isDefaultCategoryWeights( + catSlug, + weightMode, + categoryWeights, + sharedCategoryCriteria + ) || + (weightMode !== 'custom' && + !availableCategoryPresets.some((p) => p.id === weightMode))) + ) { + const defaults = defaultCategoryWeights(catSlug); + setWeightMode('default'); + setCategoryWeights(defaults); + replaceVersusQuery('default', defaults, sharedCategoryCriteria); + } + }, [ + canWeigh, + weightMode, + categoryWeights, + showSliders, + catSlug, + availableCategoryPresets, + sharedCategoryCriteria, + replaceVersusQuery, + ]); + + const hasActiveCustomWeights = + canWeigh && + !isDefaultCategoryWeights( + catSlug, + weightMode, + categoryWeights, + sharedCategoryCriteria + ); + + const activePresetTitle = resolveLocalizedPresetName( + catSlug, + weightMode, + locale, + undefined, + t('customWeightsActive') + ); + + const persona: PersonaPresetKey = useMemo( + () => + hasActiveCustomWeights ? toLegacyVersusPersona(weightMode) : 'default', + [hasActiveCustomWeights, weightMode] + ); + const weights: CriteriaWeights = useMemo( + () => + !hasActiveCustomWeights + ? PERSONA_WEIGHTS.default + : toLegacyCriteriaWeights( + catSlug, + categoryWeights, + sharedCategoryCriteria + ), + [hasActiveCustomWeights, catSlug, categoryWeights, sharedCategoryCriteria] + ); + // The same result as GET /api/v1/rate/versus (DOS/Rate#1647): the final // winner by the overall stars as shown, whatever weights are picked; a // preset or custom weights only add their own lead, shown apart. @@ -362,10 +614,62 @@ export default function VersusInteractiveScoreboard({ photography: t('personaPhotography'), gaming: t('personaGaming'), endurance: t('personaEndurance'), + business: activePresetTitle, value_hunter: t('personaValueHunter'), custom: t('customWeightsActive'), + ...(hasActiveCustomWeights ? { [activePersona]: activePresetTitle } : {}), }; + const customWeightedPair = useMemo(() => { + if (!hasActiveCustomWeights) return null; + const resA = computeCustomWeightedScore5( + catSlug, + catScoresA, + categoryWeights, + { + onlyCriteria: sharedCategoryCriteria, + officialScore5: overallResult.finalA, + } + ); + const resB = computeCustomWeightedScore5( + catSlug, + catScoresB, + categoryWeights, + { + onlyCriteria: sharedCategoryCriteria, + officialScore5: overallResult.finalB, + } + ); + if (resA.customScore5 == null || resB.customScore5 == null) return null; + const isTie = resA.customScore5 === resB.customScore5; + const gap = roundScore(Math.abs(resA.customScore5 - resB.customScore5), 2); + const leadSide: 'A' | 'B' = + resA.customScore5 >= resB.customScore5 ? 'A' : 'B'; + const leadItem = leadSide === 'A' ? scoreA : scoreB; + const leadScore = leadSide === 'A' ? resA.customScore5 : resB.customScore5; + return { + scoreA5: resA.customScore5, + scoreB5: resB.customScore5, + isTie, + leadSide, + leadSlug: leadItem.slug, + leadName: leadItem.name, + leadScore5: leadScore, + delta5: gap, + }; + }, [ + hasActiveCustomWeights, + catSlug, + catScoresA, + catScoresB, + categoryWeights, + sharedCategoryCriteria, + overallResult.finalA, + overallResult.finalB, + scoreA, + scoreB, + ]); + const handleCopy1v1Markdown = async () => { if (typeof window === 'undefined') return; try { @@ -391,24 +695,51 @@ export default function VersusInteractiveScoreboard({ expertSourceTag: t('overallSourceExpertBadge'), } ); + const customMdBullet = customWeightedPair + ? `- **${sanitizeVersusMarkdownCell(t('yourCustomScoreLabel'))} (${sanitizeVersusMarkdownCell(activePresetTitle)}):** ${ + customWeightedPair.isTie + ? t('customWinnerTie', { + preset: sanitizeVersusMarkdownCell(activePresetTitle), + score: formatRatingValue( + customWeightedPair.leadScore5, + locale, + 2 + ), + }) + : t('customWinnerSummary', { + preset: sanitizeVersusMarkdownCell(activePresetTitle), + winner: sanitizeVersusMarkdownCell( + customWeightedPair.leadName + ), + score: formatRatingValue( + customWeightedPair.leadScore5, + locale, + 2 + ), + delta: formatRatingValue( + customWeightedPair.delta5, + locale, + 2 + ), + }) + }` + : personaLead + ? `- ${t( + personaLead.key, + personaLead.key === 'versusPersonaLead' + ? { + ...personaLead.values, + winner: sanitizeVersusMarkdownCell( + personaResult?.winner.name + ), + } + : personaLead.values + )}` + : null; const lines = [ `### ${t('md1v1Heading', { nameA: safeNameA, nameB: safeNameB })}`, summaryBullet, - ...(personaLead - ? [ - `- ${t( - personaLead.key, - personaLead.key === 'versusPersonaLead' - ? { - ...personaLead.values, - winner: sanitizeVersusMarkdownCell( - personaResult?.winner.name - ), - } - : personaLead.values - )}`, - ] - : []), + ...(customMdBullet ? [customMdBullet] : []), `- **${t('mdAuditUrl')}:** ${window.location.href}`, '', `| ${t('mdColCriterion')} | ${safeNameA} | ${safeNameB} | ${t('mdColAdvantage')} |`, @@ -477,17 +808,29 @@ export default function VersusInteractiveScoreboard({ '-', ], // The lead under the picked weights, apart from the overall row. - ...(personaResult + ...(customWeightedPair ? [ [ - personaLabels[activePersona] ?? personaLabels.custom, + `${t('yourCustomScoreLabel')} (${activePresetTitle})`, 100, - formatScoreFixed(displayedScore5(personaResult.finalA), 1), - formatScoreFixed(displayedScore5(personaResult.finalB), 1), - personaResult.tie ? t('mdRowTie') : personaResult.winner.name, + formatScoreFixed(customWeightedPair.scoreA5, 2), + formatScoreFixed(customWeightedPair.scoreB5, 2), + customWeightedPair.isTie + ? t('mdRowTie') + : customWeightedPair.leadName, ], ] - : []), + : personaResult + ? [ + [ + personaLabels[activePersona] ?? personaLabels.custom, + 100, + formatScoreFixed(displayedScore5(personaResult.finalA), 1), + formatScoreFixed(displayedScore5(personaResult.finalB), 1), + personaResult.tie ? t('mdRowTie') : personaResult.winner.name, + ], + ] + : []), ...criteriaRows.map((r) => [ r.label, activeWeights[r.key], @@ -574,6 +917,26 @@ export default function VersusInteractiveScoreboard({ versusSlug: `${safeSlugA}-vs-${safeSlugB}`, persona: activePersona, weights: activeWeights, + useCaseMode: weightMode, + categoryWeights: normalizeCategoryWeights( + catSlug, + categoryWeights, + sharedCategoryCriteria + ).normalizedPercent, + customWeightedResult: customWeightedPair + ? { + tie: customWeightedPair.isTie, + winnerSlug: customWeightedPair.isTie + ? null + : sanitizeVersusExportSlug(customWeightedPair.leadSlug), + winnerName: customWeightedPair.isTie + ? null + : customWeightedPair.leadName, + scoreA5: customWeightedPair.scoreA5, + scoreB5: customWeightedPair.scoreB5, + delta5: customWeightedPair.delta5, + } + : null, exportedAt: new Date().toISOString(), tie: overallResult.tie, winner: overallResult.tie @@ -652,8 +1015,52 @@ export default function VersusInteractiveScoreboard({ locale ); + const actionButtons = ( + <> + + + + + + ); + return ( <> + + + {/* The verdict names the final winner by the overall stars; the picked weights only add their own lead below (DOS/Rate#1647). */}

0 && ` ${t('versusVerdictExpertSource', { name: verdictExpertNames.join(', ') })}`} - {personaLead && ( + {personaLead && !customWeightedPair && ( {t(personaLead.key, personaLead.values)} )}

- {/* Top Action & Persona Filter Strip */} -
- {/* Presets expose the pressed one, not only its colour (DOS/Rate#1069). */} - {canWeigh ? ( -
- - {t('useCaseLabel')} - - {( - [ - { key: 'default', label: t('personaDefault') }, - { key: 'photography', label: t('personaPhotography') }, - { key: 'gaming', label: t('personaGaming') }, - { key: 'endurance', label: t('personaEndurance') }, - { key: 'value_hunter', label: t('personaValueHunter') }, - ] as const - ) - .filter((item) => availablePersonas.includes(item.key)) - .map((item) => ( - - ))} - -
- ) : ( - - )} - -
- - - - -
+ {/* Top Action & RTINGS-Style Category Use-Case Filter Strip (#1864) */} +
+ setShowSliders((prev) => !prev)} + onSelectPreset={selectUseCasePreset} + onUpdateWeight={updateCategoryWeight} + onReset={resetVersusWeights} + locale={locale} + variant="dark" + groupLabelId={useCaseLabelId} + slidersPanelId={slidersPanelId} + trailingActions={actionButtons} + testIdPrefix="versus-weights" + copy={{ + groupLabel: t('useCaseLabel'), + customizeBtn: t('customWeightsBtn'), + customActiveBadge: t('customWeightsActive'), + resetBtn: t('resetWeightsBtn'), + normalizedSummaryPrefix: t('normalizedWeightsPrefix'), + officialKeepNote: t('officialScoreKeepNote'), + }} + />
- {/* Interactive 5-Criteria Weight Sliders */} - {showSliders && canWeigh && ( -
-
- {criteriaRows - .filter((c) => sharedCriteria.includes(c.key)) - .map((c) => ( -
-
- {c.label} - - {formatPercent(activeWeights[c.key], locale)} - -
- - updateWeight(c.key, Number(e.target.value)) - } - className="form-range" - aria-label={c.label} - /> -
- ))} -
-
- )} - - {/* Dynamic 1v1 Winner Banner */} + {/* Dynamic 1v1 Official Winner Banner (#1531 D3) */}
{overallResult.tie ? t('tie1v1Badge') : t('leading1v1Badge')} + {hasActiveCustomWeights && ( + + {t('officialRateScoreLabel')}: + + )} {overallResult.tie ? ( {overallResult.bothScored @@ -863,6 +1168,57 @@ export default function VersusInteractiveScoreboard({
+ {/* Personalized Custom-Weight Score Callout (#1864, #1531 D3/D9) */} +
+ {customWeightedPair && ( +
+
+ + {t('yourCustomScoreLabel')} + + + {customWeightedPair.isTie + ? t('customWinnerTie', { + preset: activePresetTitle, + score: formatRatingValue( + customWeightedPair.leadScore5, + locale, + 2 + ), + }) + : t('customWinnerSummary', { + preset: activePresetTitle, + winner: customWeightedPair.leadName, + score: formatRatingValue( + customWeightedPair.leadScore5, + locale, + 2 + ), + delta: formatRatingValue( + customWeightedPair.delta5, + locale, + 2 + ), + })} + +
+
+ {scoreA.name}:{' '} + {formatRatingValue(customWeightedPair.scoreA5, locale, 2)}/5 •{' '} + {scoreB.name}:{' '} + {formatRatingValue(customWeightedPair.scoreB5, locale, 2)}/5 +
+
+ )} +
+ {/* Product Headers */}
diff --git a/apps/web/src/components/leaderboard/LeaderboardExplorer.tsx b/apps/web/src/components/leaderboard/LeaderboardExplorer.tsx index 8a0d794e..70fb3940 100644 --- a/apps/web/src/components/leaderboard/LeaderboardExplorer.tsx +++ b/apps/web/src/components/leaderboard/LeaderboardExplorer.tsx @@ -25,12 +25,29 @@ import { type LeaderboardPriceSegment, } from '@/lib/rate-domain'; import { + CRITERION_RANK_WRITERS, LEADERBOARD_SCORE_CRITERIA, displayedScore5, leaderboardCriteriaForCategory, - weightedCriteriaScore5, type LeaderboardCriteriaBreakdown, } from '@/lib/leaderboard-engine'; +import { + availableCategoryUseCasePresets, + computeCustomWeightedScore5, + defaultCategoryWeights, + extractCategoryCriteriaScores, + isDefaultCategoryWeights, + mergeUseCaseQueryIntoSearch, + normalizeCategoryWeights, + parseUseCaseWeightsFromParams, + resolveCategoryPreset, + resolveLocalizedPresetName, + sanitizeSliderWeight, + scoredCategoryCriteriaForProducts, + type ActiveWeightMode, + type CategoryCriterionWeights, +} from '@/lib/use-case-weights'; +import UseCaseWeightBar from '@/components/compare/UseCaseWeightBar'; import { getRadarSignal, radarCsvCells, @@ -45,7 +62,11 @@ import { useDealRadarIndex } from '@/components/radar/use-deal-radar'; import CompareQuickToggle from '@/components/compare/CompareQuickToggle'; import { escapeCsvCell } from '@/lib/csv-safe'; import type { KeySpecs } from '@repo/shared-data'; -import { applyCategorySpecTemplate } from '@repo/shared-data/rules'; +import { + applyCategorySpecTemplate, + type RatingCriterionKey, + type UseCasePresetId, +} from '@repo/shared-data/rules'; import { BsArrowLeftRight, BsAwardFill, @@ -62,7 +83,6 @@ import { BsPhone, BsSearch, BsShieldCheck, - BsSliders, BsSmartwatch, BsStarFill, BsTablet, @@ -71,11 +91,7 @@ import { } from 'react-icons/bs'; import ContentText from '@/components/elementary/ContentText'; import StarRating from '@/components/elementary/StarRating'; -import { - formatDecimal, - formatPercent, - formatPriceVnd, -} from '@/lib/locale-format'; +import { formatDecimal, formatPriceVnd } from '@/lib/locale-format'; import { displayRating, formatRatingValue, @@ -587,6 +603,10 @@ interface LeaderboardExplorerProps { readonly filteredReviewCounts?: FilteredReviewCountsByMaster; /** RATE_ITEM_MODEL on: variant slug to Item slug, for versus links. */ readonly itemSlugBySlug?: Readonly>; + readonly initialCategory?: CanonicalCategorySlug; + readonly initialWeightMode?: ActiveWeightMode; + readonly initialCustomWeights?: CategoryCriterionWeights; + readonly initialShowWeightSliders?: boolean; } interface RankedProductEntry { @@ -689,9 +709,15 @@ function computeProductScores( function TabFromUrl({ onCategory, onCriterion, + onWeightQuery, }: { readonly onCategory: (cat: CanonicalCategorySlug) => void; readonly onCriterion: (crit: LeaderboardCriterionKey) => void; + readonly onWeightQuery: ( + cat: CanonicalCategorySlug, + rawPreset: string | null, + rawWeights: string | null + ) => void; }) { const searchParams = useSearchParams(); // Normalized first, so the effects fire only when the effective tab @@ -699,8 +725,14 @@ function TabFromUrl({ // URL must not count as a category change (and reset the brand). const cat = normalizeLeaderboardCategory(searchParams.get('cat')); const crit = normalizeLeaderboardCriterion(searchParams.get('criterion')); + const rawPreset = searchParams.get('preset'); + const rawWeights = searchParams.get('weights'); useEffect(() => onCategory(cat), [cat, onCategory]); useEffect(() => onCriterion(crit), [crit, onCriterion]); + useEffect( + () => onWeightQuery(cat, rawPreset, rawWeights), + [cat, rawPreset, rawWeights, onWeightQuery] + ); return null; } @@ -710,6 +742,10 @@ export default function LeaderboardExplorer({ locale: localeProp, filteredReviewCounts, itemSlugBySlug, + initialCategory = 'smartphones', + initialWeightMode = 'default', + initialCustomWeights, + initialShowWeightSliders = false, }: LeaderboardExplorerProps) { const t = useTranslations('leaderboard'); const hookLocale = useLocale(); @@ -719,116 +755,62 @@ export default function LeaderboardExplorer({ const categoryTabs = useMemo(() => buildCategoryTabs(t), [t]); const [activeCategory, setActiveCategory] = - useState('smartphones'); + useState(initialCategory); const [activeCriterion, setActiveCriterion] = useState('combined'); - // Keeps the tab in the URL without a server round trip; Next syncs its - // router with the native history API. - const replaceTabUrl = ( - cat: CanonicalCategorySlug, - crit: LeaderboardCriterionKey - ) => { - window.history.replaceState( - null, - '', - `${window.location.pathname}?cat=${cat}&criterion=${crit}` - ); - }; const [priceSegment, setPriceSegment] = useState('all'); const [selectedBrand, setSelectedBrand] = useState('all'); const [searchQuery, setSearchQuery] = useState(''); - const [activePersona, setActivePersona] = - useState('none'); - const [showWeightSliders, setShowWeightSliders] = useState(false); - const [customWeights, setCustomWeights] = useState<{ - screen: number; - performance: number; - camera: number; - battery: number; - value: number; - }>({ - screen: 20, - performance: 20, - camera: 20, - battery: 20, - value: 20, - }); - - const applyPersonaPreset = ( - persona: - | 'none' - | 'photography' - | 'gaming' - | 'endurance' - | 'business' - | 'value_hunter' - ) => { - setActivePersona(persona); - if (persona === 'none') { - setCustomWeights({ - screen: 20, - performance: 20, - camera: 20, - battery: 20, - value: 20, - }); - return; - } - if (persona === 'photography') { - setCustomWeights({ - screen: 25, - performance: 15, - camera: 45, - battery: 10, - value: 5, - }); - } else if (persona === 'gaming') { - setCustomWeights({ - screen: 25, - performance: 45, - camera: 5, - battery: 20, - value: 5, - }); - } else if (persona === 'endurance') { - setCustomWeights({ - screen: 15, - performance: 15, - camera: 10, - battery: 45, - value: 15, - }); - } else if (persona === 'business') { - setCustomWeights({ - screen: 30, - performance: 25, - camera: 10, - battery: 25, - value: 10, - }); - } else if (persona === 'value_hunter') { - setCustomWeights({ - screen: 15, - performance: 20, - camera: 10, - battery: 15, - value: 40, - }); - } - }; + const [weightMode, setWeightMode] = + useState(initialWeightMode); + const [showWeightSliders, setShowWeightSliders] = useState( + initialShowWeightSliders + ); + const [customWeights, setCustomWeights] = useState( + () => + initialCustomWeights + ? normalizeCategoryWeights(initialCategory, initialCustomWeights) + .sliderWeights + : initialWeightMode !== 'default' && initialWeightMode !== 'custom' + ? normalizeCategoryWeights( + initialCategory, + resolveCategoryPreset(initialCategory, initialWeightMode).weights + ).sliderWeights + : defaultCategoryWeights(initialCategory) + ); - const updateSingleWeight = ( - key: 'screen' | 'performance' | 'camera' | 'battery' | 'value', - val: number - ) => { - setActivePersona('custom'); - setCustomWeights((prev) => ({ - ...prev, - [key]: sanitizeLeaderboardWeight(val, prev[key]), - })); - }; + // Keeps the tab and active non-default preset/weights in the URL without a + // server round trip; Next syncs its router with the native history API. + const replaceTabUrl = useCallback( + ( + cat: CanonicalCategorySlug, + crit: LeaderboardCriterionKey, + nextMode: ActiveWeightMode, + nextWeights: CategoryCriterionWeights, + available: readonly RatingCriterionKey[] + ) => { + if (typeof window === 'undefined') return; + const baseQuery = `?cat=${cat}&criterion=${crit}`; + const mergedQuery = + available.length > 0 + ? mergeUseCaseQueryIntoSearch( + baseQuery, + cat, + nextMode, + nextWeights, + available + ) + : baseQuery; + window.history.replaceState( + null, + '', + `${window.location.pathname}${mergedQuery}` + ); + }, + [] + ); const copy = useMemo( () => ({ @@ -837,6 +819,7 @@ export default function LeaderboardExplorer({ chooseCriterion: t('chooseCriterion'), personaTitle: t('personaTitle'), customizeWeightsBtn: t('customizeWeightsBtn'), + customWeightsBtn: t('customWeightsBtn'), personaLabels: { none: t('personaNone'), photography: t('personaPhotography'), @@ -846,6 +829,44 @@ export default function LeaderboardExplorer({ value_hunter: t('personaValueHunter'), custom: t('personaCustom'), }, + presetLabels: { + default: t('preset_default'), + gaming: t('preset_gaming'), + camera: t('preset_camera'), + endurance: t('preset_endurance'), + value: t('preset_value'), + media: t('preset_media'), + study_work: t('preset_study_work'), + office: t('preset_office'), + creator: t('preset_creator'), + fitness: t('preset_fitness'), + smart_daily: t('preset_smart_daily'), + audiophile: t('preset_audiophile'), + commute_anc: t('preset_commute_anc'), + calls_work: t('preset_calls_work'), + } satisfies Record, + weightCriterionLabels: { + performance: t('weightCrit_performance'), + camera: t('weightCrit_camera'), + battery: t('weightCrit_battery'), + display: t('weightCrit_display'), + design: t('weightCrit_design'), + value: t('weightCrit_value'), + sound: t('weightCrit_sound'), + software: t('weightCrit_software'), + keyboard: t('weightCrit_keyboard'), + thermals: t('weightCrit_thermals'), + health: t('weightCrit_health'), + apps: t('weightCrit_apps'), + anc: t('weightCrit_anc'), + comfort: t('weightCrit_comfort'), + calls: t('weightCrit_calls'), + } satisfies Partial>, + resetWeightsBtn: t('resetWeightsBtn'), + normalizedWeightsPrefix: t('normalizedWeightsPrefix'), + officialRateScoreLabel: t('officialRateScoreLabel'), + yourCustomScoreLabel: t('yourCustomScoreLabel'), + officialScoreKeepNote: t('officialScoreKeepNote'), compareTop3Btn: t('compareTop3Btn'), searchPlaceholder: t('searchPlaceholder'), allBrands: t('allBrands'), @@ -898,46 +919,114 @@ export default function LeaderboardExplorer({ // for. A criterion with none gets no tab, no weight and no row cell, not // an empty list (DOS/Rate#1553). A tab and a weight need a score past the // ranking threshold; a cell needs one past the display threshold (D9). - const { scoredCriteria, shownCriteria } = useMemo(() => { - const ranked = new Set(); - const shown = new Set(); - const own = leaderboardCriteriaForCategory(activeCategory); - for (const item of categoryProducts) { - const { criteria, rankCriteria } = computeProductScores( - item, - 'combined', - filteredReviewCounts - ); - for (const c of own) { - if ((criteria[c] ?? 0) > 0) shown.add(c); - if ((rankCriteria[c] ?? 0) > 0) ranked.add(c); + const { scoredCriteria, shownCriteria, scoredCategoryCriteria } = + useMemo(() => { + const ranked = new Set(); + const shown = new Set(); + const own = leaderboardCriteriaForCategory(activeCategory); + const baseEntries: Array<{ + product: ItemCatalogRow; + rankCriteria: LeaderboardCriteriaBreakdown; + }> = []; + for (const item of categoryProducts) { + const { criteria, rankCriteria } = computeProductScores( + item, + 'combined', + filteredReviewCounts + ); + baseEntries.push({ product: item, rankCriteria }); + for (const c of own) { + if ((criteria[c] ?? 0) > 0) shown.add(c); + if ((rankCriteria[c] ?? 0) > 0) ranked.add(c); + } } - if (ranked.size === own.length) break; - } - return { - scoredCriteria: own.filter((c) => ranked.has(c)), - shownCriteria: own.filter((c) => shown.has(c)), - }; - }, [activeCategory, categoryProducts, filteredReviewCounts]); - const hasScoredCriteria = scoredCriteria.length > 0; + return { + scoredCriteria: own.filter((c) => ranked.has(c)), + shownCriteria: own.filter((c) => shown.has(c)), + scoredCategoryCriteria: scoredCategoryCriteriaForProducts( + activeCategory, + baseEntries, + CRITERION_RANK_WRITERS + ), + }; + }, [activeCategory, categoryProducts, filteredReviewCounts]); + const hasScoredCriteria = scoredCategoryCriteria.length > 0; const hasShownCriteria = shownCriteria.length > 0; - // Only the weights of the category's own criteria count: a screen - // weight left over from phones does not empty the earbuds list. - const weightedCriteria = useMemo( - () => leaderboardCriteriaForCategory(activeCategory), - [activeCategory] - ); - const totalWeight = weightedCriteria.reduce( - (sum, c) => sum + customWeights[c], - 0 - ); - const hasActivePersonaWeights = activePersona !== 'none' && totalWeight > 0; - const activeScoreLabel = resolveLeaderboardActiveScoreLabel( - activePersona, - activeCriterion, - copy, - totalWeight - ); + + const applyPersonaPreset = (presetId: UseCasePresetId) => { + const preset = resolveCategoryPreset(activeCategory, presetId); + const norm = normalizeCategoryWeights( + activeCategory, + preset.weights, + scoredCategoryCriteria + ); + setWeightMode(preset.id); + setCustomWeights(norm.sliderWeights); + replaceTabUrl( + activeCategory, + activeCriterion, + preset.id, + norm.sliderWeights, + scoredCategoryCriteria + ); + }; + + const updateSingleWeight = (key: RatingCriterionKey, val: number) => { + const nextCandidate: CategoryCriterionWeights = { + ...customWeights, + [key]: sanitizeSliderWeight(val, customWeights[key] ?? 0), + }; + const normalized = normalizeCategoryWeights( + activeCategory, + nextCandidate, + scoredCategoryCriteria + ); + const collapsesToDefault = + normalized.wasAllZeroReset || + isDefaultCategoryWeights( + activeCategory, + 'custom', + normalized.sliderWeights, + scoredCategoryCriteria + ); + const nextMode: ActiveWeightMode = collapsesToDefault + ? 'default' + : 'custom'; + const nextWeights = collapsesToDefault + ? defaultCategoryWeights(activeCategory) + : normalized.sliderWeights; + setWeightMode(nextMode); + setCustomWeights(nextWeights); + replaceTabUrl( + activeCategory, + activeCriterion, + nextMode, + nextWeights, + scoredCategoryCriteria + ); + }; + + const resetCustomWeights = () => { + applyPersonaPreset('default'); + }; + + const hasActivePersonaWeights = + hasScoredCriteria && + !isDefaultCategoryWeights( + activeCategory, + weightMode, + customWeights, + scoredCategoryCriteria + ); + const activeScoreLabel = hasActivePersonaWeights + ? resolveLocalizedPresetName( + activeCategory, + weightMode, + locale, + undefined, + copy.personaLabels.custom + ) + : resolveLeaderboardActiveScoreLabel('none', activeCriterion, copy, 0); // The one rating shows at 1 decimal (D3); a persona's own weighted score // keeps 2, under the persona's name. const ratingView = @@ -1010,14 +1099,24 @@ export default function LeaderboardExplorer({ ? base.combinedScore5 > 0 : base.activeScore5 > 0) ) { - const weighted5 = weightedCriteriaScore5( - base.rankCriteria, + const catScores = extractCategoryCriteriaScores( + item, + activeCategory, + CRITERION_RANK_WRITERS, + base.rankCriteria + ); + const customRes = computeCustomWeightedScore5( + activeCategory, + catScores, customWeights, - weightedCriteria + { + onlyCriteria: scoredCategoryCriteria, + officialScore5: base.userScore5, + } ); return { ...base, - activeScore5: weighted5 ?? 0, + activeScore5: customRes.customScore5 ?? 0, }; } return base; @@ -1073,8 +1172,9 @@ export default function LeaderboardExplorer({ priceSegment, searchQuery, activeCriterion, + activeCategory, hasActivePersonaWeights, - weightedCriteria, + scoredCategoryCriteria, customWeights, filteredReviewCounts, ]); @@ -1241,7 +1341,7 @@ export default function LeaderboardExplorer({ source: 'Rate.vn JReviews Leaderboard', category: activeCategory, criterion: activeCriterion, - persona: activePersona, + persona: weightMode, exportedAt: new Date().toISOString(), count: rankedEntries.length, items: rankedEntries.map((entry, idx) => @@ -1265,20 +1365,26 @@ export default function LeaderboardExplorer({ const handleSelectCategory = (cat: CanonicalCategorySlug) => { const crit = criterionForCategory(cat, activeCriterion); + const nextDefaults = defaultCategoryWeights(cat); setActiveCategory(cat); setActiveCriterion(crit); setSelectedBrand('all'); - replaceTabUrl(cat, crit); + setWeightMode('default'); + setCustomWeights(nextDefaults); + replaceTabUrl(cat, crit, 'default', nextDefaults, []); }; const handleSelectCriterion = (crit: LeaderboardCriterionKey) => { + const nextDefaults = defaultCategoryWeights(activeCategory); setActiveCriterion(crit); - replaceTabUrl(activeCategory, crit); + setWeightMode('default'); + setCustomWeights(nextDefaults); + replaceTabUrl(activeCategory, crit, 'default', nextDefaults, []); }; // The page is cached with the default tab; TabFromUrl applies the URL's - // ?cat= and ?criterion= on load and on every later navigation, including - // a same-route link to plain /leaderboard (DOS/Rate#508). + // ?cat=, ?criterion=, ?preset=, and ?weights= on load and on every later + // navigation, including a same-route link to plain /leaderboard (DOS/Rate#508). const applyUrlCategory = useCallback((cat: CanonicalCategorySlug) => { setActiveCategory(cat); setSelectedBrand('all'); @@ -1286,6 +1392,21 @@ export default function LeaderboardExplorer({ const applyUrlCriterion = useCallback((crit: LeaderboardCriterionKey) => { setActiveCriterion(crit); }, []); + const applyUrlWeightQuery = useCallback( + ( + cat: CanonicalCategorySlug, + rawPreset: string | null, + rawWeights: string | null + ) => { + const parsed = parseUseCaseWeightsFromParams(cat, { + preset: rawPreset ?? undefined, + weights: rawWeights ?? undefined, + }); + setWeightMode(parsed.mode); + setCustomWeights(parsed.weights); + }, + [] + ); // A URL such as ?cat=earbuds&criterion=screen opens on the combined tab. // So does a criterion no product has a score for yet (DOS/Rate#1553). // Before paint, so an empty list never flashes, and the URL follows. @@ -1301,24 +1422,68 @@ export default function LeaderboardExplorer({ } if (crit === activeCriterion) return; setActiveCriterion(crit); - window.history.replaceState( - null, - '', - `${window.location.pathname}?cat=${activeCategory}&criterion=${crit}` + replaceTabUrl( + activeCategory, + crit, + weightMode, + customWeights, + scoredCategoryCriteria ); - }, [activeCategory, activeCriterion, scoredCriteria]); + }, [ + activeCategory, + activeCriterion, + scoredCriteria, + weightMode, + customWeights, + scoredCategoryCriteria, + replaceTabUrl, + ]); useEffect(() => { - if (hasScoredCriteria || activePersona === 'none') return; - setActivePersona('none'); - setShowWeightSliders(false); - setCustomWeights({ - screen: 20, - performance: 20, - camera: 20, - battery: 20, - value: 20, - }); - }, [hasScoredCriteria, activePersona]); + if (!hasScoredCriteria) { + if (weightMode !== 'default' || showWeightSliders) { + const defaults = defaultCategoryWeights(activeCategory); + setWeightMode('default'); + setShowWeightSliders(false); + setCustomWeights(defaults); + replaceTabUrl(activeCategory, activeCriterion, 'default', defaults, []); + } + return; + } + if ( + weightMode !== 'default' && + (isDefaultCategoryWeights( + activeCategory, + weightMode, + customWeights, + scoredCategoryCriteria + ) || + (weightMode !== 'custom' && + !availableCategoryUseCasePresets( + activeCategory, + scoredCategoryCriteria + ).some((p) => p.id === weightMode))) + ) { + const defaults = defaultCategoryWeights(activeCategory); + setWeightMode('default'); + setCustomWeights(defaults); + replaceTabUrl( + activeCategory, + activeCriterion, + 'default', + defaults, + scoredCategoryCriteria + ); + } + }, [ + hasScoredCriteria, + weightMode, + customWeights, + showWeightSliders, + activeCategory, + activeCriterion, + scoredCategoryCriteria, + replaceTabUrl, + ]); const allCriterionOptions: Array<{ key: LeaderboardCriterionKey; @@ -1380,6 +1545,7 @@ export default function LeaderboardExplorer({ {/* 1. Directory -> 5-Category Hierarchy & Criterion Control Panel */} @@ -1498,7 +1664,6 @@ export default function LeaderboardExplorer({ type="button" aria-pressed={isSelected && !hasActivePersonaWeights} onClick={() => { - setActivePersona('none'); handleSelectCriterion(opt.key); }} className={`btn btn-sm rounded-pill d-inline-flex align-items-center gap-2 px-3 py-2 ${ @@ -1515,122 +1680,33 @@ export default function LeaderboardExplorer({
- {/* 3. Smart Use-Case Persona Recommender & Custom 5-Criteria Weight Sliders (Issue #52) */} + {/* 3. RTINGS-Style Category Use-Case Presets & Normalized Weight Sliders (#1864) */} {hasScoredCriteria && (
-
-
- {copy.personaTitle} -
- -
- -
- {( - [ - 'none', - 'photography', - 'gaming', - 'endurance', - 'business', - 'value_hunter', - ] as const - ).map((presetKey) => { - const isSelected = activePersona === presetKey; - return ( - - ); - })} -
- - {showWeightSliders && ( -
-
- {( - [ - { key: 'screen', label: copy.critLabels.screen }, - { - key: 'performance', - label: copy.critLabels.performance, - }, - { key: 'camera', label: copy.critLabels.camera }, - { key: 'battery', label: copy.critLabels.battery }, - { key: 'value', label: copy.critLabels.value }, - ] as const - ) - .filter((slider) => scoredCriteria.includes(slider.key)) - .map((slider) => ( -
-
- {slider.label} - - {formatPercent(customWeights[slider.key], locale)} - -
- - updateSingleWeight( - slider.key, - Number(e.target.value) - ) - } - className="form-range" - aria-label={slider.label} - /> -
- ))} -
-
- )} + setShowWeightSliders((v) => !v)} + onSelectPreset={applyPersonaPreset} + onUpdateWeight={updateSingleWeight} + onReset={resetCustomWeights} + locale={locale} + variant="light" + groupLabelId="leaderboard-persona-label" + slidersPanelId="leaderboard-weight-sliders" + testIdPrefix="leaderboard-weights" + copy={{ + groupLabel: copy.personaTitle, + customizeBtn: copy.customWeightsBtn, + customActiveBadge: copy.personaLabels.custom, + resetBtn: copy.resetWeightsBtn, + normalizedSummaryPrefix: copy.normalizedWeightsPrefix, + officialKeepNote: copy.officialScoreKeepNote, + }} + />
)} @@ -1887,6 +1963,15 @@ export default function LeaderboardExplorer({ {rankLabel}
+ {hasActivePersonaWeights && ( +
+ {copy.yourCustomScoreLabel} +
+ )} -
+
+ {hasActivePersonaWeights && ( + + {copy.officialRateScoreLabel}: + + )}
-
+
+ {hasActivePersonaWeights && ( + + {copy.officialRateScoreLabel}: + + )}
-
{activeScoreLabel}
+
+ {hasActivePersonaWeights + ? `${copy.yourCustomScoreLabel} (${activeScoreLabel})` + : activeScoreLabel} +
acc + (v ?? 0), + 0 + ); + assert.equal(defaultSum, 100, `${cat} default weights sum to 100`); + + const presets = getRatingUseCasePresets(cat); + assert.ok(presets.length >= 4, `${cat} offers curated use-case presets`); + assert.equal(presets[0]?.id, 'default'); + for (const preset of presets) { + const resolved = resolveCategoryPreset(cat, preset.id); + assert.equal(resolved.id, preset.id); + const norm = normalizeCategoryWeights(cat, preset.weights); + assert.equal(norm.wasAllZeroReset, false); + const pctSum = Object.values(norm.normalizedPercent).reduce( + (acc, v) => acc + (v ?? 0), + 0 + ); + assert.equal( + pctSum, + 100, + `${cat}:${preset.id} normalized percent sums to 100` + ); + } + } + + // Friendly URL preset aliases & category-aware aliases + assert.equal( + resolveCategoryPreset('smartphones', 'photography').id, + 'camera' + ); + assert.equal(resolveCategoryPreset('smartphones', 'VLOG').id, 'camera'); + assert.equal(resolveCategoryPreset('earbuds', 'anc').id, 'commute_anc'); + assert.equal(resolveCategoryPreset('earbuds', 'music').id, 'audiophile'); + assert.equal(resolveCategoryPreset('laptops', 'business').id, 'office'); + assert.equal(resolveCategoryPreset('tablets', 'business').id, 'study_work'); + assert.equal( + resolveCategoryPreset('smartwatches', 'business').id, + 'smart_daily' + ); + + // Prototype-key & malformed preset guards + for (const badPreset of [ + '__proto__', + 'constructor', + 'prototype', + 'toString', + 'valueOf', + 'unknown_preset', + 'gaming;drop', + '', + ' ', + null, + undefined, + 42, + {}, + ]) { + assert.equal( + resolveCategoryPreset('smartphones', badPreset).id, + 'default', + `Unsafe preset ${String(badPreset)} falls back to default` + ); + } + + // 3. Slider clamping, Hare-Niemeyer exact 100% normalization & all-zero reset + assert.equal(sanitizeSliderWeight(-25, 10), 0); + assert.equal(sanitizeSliderWeight(180, 10), 100); + assert.equal(sanitizeSliderWeight('35.6', 0), 36); + assert.equal(sanitizeSliderWeight(Number.NaN, 15), 15); + assert.equal(sanitizeSliderWeight(Number.POSITIVE_INFINITY, 20), 20); + assert.equal(sanitizeSliderWeight('0x20', 12), 12); + assert.equal(sanitizeSliderWeight('25\u0000', 12), 12); + assert.equal(sanitizeSliderWeight({ valueOf: () => 50 }, 12), 12); + + const threeEqual = normalizeCategoryWeights('smartphones', { + performance: 10, + camera: 10, + battery: 10, + display: 0, + design: 0, + value: 0, + }); + assert.equal(threeEqual.wasAllZeroReset, false); + assert.equal(threeEqual.normalizedPercent.performance, 34); + assert.equal(threeEqual.normalizedPercent.camera, 33); + assert.equal(threeEqual.normalizedPercent.battery, 33); + assert.equal( + Object.values(threeEqual.normalizedPercent).reduce((a, b) => a + b, 0), + 100 + ); + + const allZero = normalizeCategoryWeights('laptops', { + performance: 0, + display: 0, + battery: 0, + keyboard: 0, + thermals: 0, + design: 0, + value: 0, + }); + assert.equal(allZero.wasAllZeroReset, true); + assert.deepEqual(allZero.sliderWeights, defaultCategoryWeights('laptops')); + assert.equal( + Object.values(allZero.normalizedPercent).reduce((a, b) => a + b, 0), + 100 + ); + + const protoPayload = JSON.parse( + '{"__proto__":{"polluted":true},"constructor":80,"toString":50,"valueOf":50}' + ) as Record; + const protoNormalized = normalizeCategoryWeights('smartphones', protoPayload); + assert.equal( + protoNormalized.wasAllZeroReset, + true, + 'Prototype keys alone do not count as active weights and reset to default' + ); + assert.equal( + ({} as Record).polluted, + undefined, + 'Object.prototype was never polluted' + ); + + // 4. URL query serialization, strict parsing & canonical-safe query merging + const customQuery = serializeWeightsParam('smartphones', { + camera: 60, + battery: 40, + }); + assert.equal(customQuery, 'camera:60,battery:40'); + const reparsed = parseWeightsParam('smartphones', customQuery); + assert.ok(reparsed); + assert.equal(reparsed.camera, 60); + assert.equal(reparsed.battery, 40); + assert.equal(reparsed.performance, 0); + + // Legacy screen key maps cleanly per category + assert.equal( + parseWeightsParam('smartphones', 'screen:50,battery:50')?.display, + 50 + ); + assert.equal(parseWeightsParam('earbuds', 'screen:50,battery:50')?.sound, 50); + + for (const invalidWeights of [ + '', + ' ', + 'camera:-20,battery:50', + 'camera:NaN,battery:50', + 'camera:Infinity,battery:50', + 'camera:999999,battery:10', + 'camera:101,battery:10', + 'camera:0x10,battery:20', + 'camera:0,battery:0', + '__proto__:50,camera:50', + 'constructor:50,camera:50', + 'toString:50,camera:50', + 'anc:50,battery:50', // anc is invalid on smartphones + 'camera:50:10', + 'camera:50,\u0000battery:50', + `camera:50,${'a'.repeat(300)}:50`, + ]) { + assert.equal( + parseWeightsParam('smartphones', invalidWeights), + null, + `Invalid weights param "${invalidWeights.slice(0, 40)}" must be rejected` + ); + const fallbackState = parseUseCaseWeightsFromParams('smartphones', { + weights: invalidWeights, + }); + assert.equal(fallbackState.mode, 'default'); + assert.deepEqual( + fallbackState.weights, + defaultCategoryWeights('smartphones') + ); + } + + const mergedPreset = mergeUseCaseQueryIntoSearch( + '?slugs=iphone-16,galaxy-s24', + 'smartphones', + 'gaming', + resolveCategoryPreset('smartphones', 'gaming').weights + ); + assert.equal(mergedPreset, '?slugs=iphone-16%2Cgalaxy-s24&preset=gaming'); + + const mergedCustom = mergeUseCaseQueryIntoSearch( + mergedPreset, + 'smartphones', + 'custom', + { camera: 70, battery: 30 } + ); + assert.equal( + mergedCustom, + '?slugs=iphone-16%2Cgalaxy-s24&weights=camera%3A70%2Cbattery%3A30' + ); + + const mergedReset = mergeUseCaseQueryIntoSearch( + mergedCustom, + 'smartphones', + 'default', + defaultCategoryWeights('smartphones') + ); + assert.equal( + mergedReset, + '?slugs=iphone-16%2Cgalaxy-s24', + 'Resetting to Balanced Default strips both preset and weights from URL' + ); + assert.equal( + isDefaultCategoryWeights( + 'smartphones', + 'custom', + defaultCategoryWeights('smartphones') + ), + true + ); + + // 5. Decimal rounding parity with weightedCriteriaScore5 & Design Rule #1531 D3/D9 + const parityScores = { + display: 4.15, + performance: 4.25, + camera: 4.35, + battery: 4.05, + value: 4.45, + design: null, + }; + const legacyParity = weightedCriteriaScore5( + { + screen: 4.15, + performance: 4.25, + camera: 4.35, + battery: 4.05, + value: 4.45, + }, + { + screen: 15, + performance: 40, + camera: 10, + battery: 25, + value: 10, + }, + ['screen', 'performance', 'camera', 'battery', 'value'] + ); + const customParity = computeCustomWeightedScore5( + 'smartphones', + parityScores, + { + display: 15, + performance: 40, + camera: 10, + battery: 25, + value: 10, + design: 0, + }, + { officialScore5: 4.6 } + ); + assert.equal(customParity.customScore5, legacyParity); + assert.equal(customParity.officialScore5, 4.6); + assert.equal(customParity.displayedOfficialScore5, 4.6); + assert.equal(customParity.ratedCriteriaCount, 5); + + // Partial criteria renormalize over rated criteria without inventing 0s + const partialRes = computeCustomWeightedScore5( + 'earbuds', + { + sound: 4.8, + anc: 4.2, + battery: null, + comfort: null, + calls: null, + value: null, + }, + resolveCategoryPreset('earbuds', 'audiophile').weights, + { officialScore5: 4.3 } + ); + // Audiophile puts sound:50, anc:10 among rated criteria => (4.8*50 + 4.2*10)/60 = 4.70 + assert.equal(partialRes.customScore5, 4.7); + assert.equal(partialRes.displayedCustomScore5, 4.7); + assert.equal(partialRes.ratedCriteriaCount, 2); + assert.equal(partialRes.officialScore5, 4.3); + + // Unrated product returns null customScore5 instead of fabricating a score + const unratedRes = computeCustomWeightedScore5( + 'earbuds', + { + sound: null, + anc: null, + battery: null, + comfort: null, + calls: null, + value: null, + }, + resolveCategoryPreset('earbuds', 'commute_anc').weights, + { officialScore5: 4.1 } + ); + assert.equal(unratedRes.customScore5, null); + assert.equal(unratedRes.displayedCustomScore5, null); + assert.equal(unratedRes.officialScore5, 4.1); + + // Winner flip between Camera preset and Gaming preset while official scores stay intact + const phoneCameraPro = { + slug: 'camera-pro', + category_slug: 'smartphones', + rating_score: 4.4, + authentic_review_count: 18, + criteria_scores: { + camera: { score: 4.9, writers: 12 }, + display: { score: 4.7, writers: 12 }, + performance: { score: 3.6, writers: 12 }, + battery: { score: 3.9, writers: 12 }, + design: { score: 4.5, writers: 12 }, + value: { score: 3.8, writers: 12 }, + }, + }; + const phoneGamingBeast = { + slug: 'gaming-beast', + category_slug: 'smartphones', + rating_score: 4.2, + authentic_review_count: 15, + criteria_scores: { + camera: { score: 3.6, writers: 10 }, + display: { score: 4.4, writers: 10 }, + performance: { score: 4.9, writers: 10 }, + battery: { score: 4.8, writers: 10 }, + design: { score: 4.0, writers: 10 }, + value: { score: 4.6, writers: 10 }, + }, + }; + const scoresCamPro = extractCategoryCriteriaScores( + phoneCameraPro as never, + 'smartphones' + ); + const scoresGameBeast = extractCategoryCriteriaScores( + phoneGamingBeast as never, + 'smartphones' + ); + const shared = sharedCategoryCriteriaForPair( + 'smartphones', + scoresCamPro, + scoresGameBeast + ); + assert.equal(shared.length, getRatingCriteria('smartphones').length); + assert.equal( + scoredCategoryCriteriaForProducts('smartphones', [ + { product: phoneCameraPro as never }, + ]).length, + 6 + ); + assert.equal( + availableCategoryUseCasePresets('smartphones', []).length, + 0, + 'No presets offered when zero criteria have scores (#1553/#1556)' + ); + + const camPresetWeights = resolveCategoryPreset( + 'smartphones', + 'camera' + ).weights; + const gamePresetWeights = resolveCategoryPreset( + 'smartphones', + 'gaming' + ).weights; + const camProOnCam = computeCustomWeightedScore5( + 'smartphones', + scoresCamPro, + camPresetWeights, + { product: phoneCameraPro as never } + ); + const gameBeastOnCam = computeCustomWeightedScore5( + 'smartphones', + scoresGameBeast, + camPresetWeights, + { product: phoneGamingBeast as never } + ); + assert.ok( + (camProOnCam.customScore5 ?? 0) > (gameBeastOnCam.customScore5 ?? 0) + ); + + const camProOnGame = computeCustomWeightedScore5( + 'smartphones', + scoresCamPro, + gamePresetWeights, + { product: phoneCameraPro as never } + ); + const gameBeastOnGame = computeCustomWeightedScore5( + 'smartphones', + scoresGameBeast, + gamePresetWeights, + { product: phoneGamingBeast as never } + ); + assert.ok( + (gameBeastOnGame.customScore5 ?? 0) > (camProOnGame.customScore5 ?? 0), + 'Switching to Gaming preset flips custom winner to gaming-beast' + ); + assert.equal(camProOnGame.officialScore5, 4.4); + assert.equal(gameBeastOnGame.officialScore5, 4.2); + + // Summary formatting & legacy bridges across locales + for (const locale of ['vi', 'en', 'cs'] as const) { + const summary = formatNormalizedWeightSummary( + 'earbuds', + normalizeCategoryWeights( + 'earbuds', + resolveCategoryPreset('earbuds', 'commute_anc').weights + ).normalizedPercent, + locale + ); + assert.ok(summary.length > 10); + assert.doesNotMatch(summary, /[\u2013\u2014]/); + } + const legacyEarbuds = toLegacyCriteriaWeights( + 'earbuds', + resolveCategoryPreset('earbuds', 'commute_anc').weights + ); + assert.equal( + legacyEarbuds.screen + + legacyEarbuds.performance + + legacyEarbuds.camera + + legacyEarbuds.battery + + legacyEarbuds.value, + 100 + ); + assert.equal(toLegacyVersusPersona('gaming'), 'gaming'); + assert.equal(toLegacyVersusPersona('commute_anc'), 'photography'); + assert.equal(toLegacyVersusPersona('custom'), 'custom'); + + // 6. Round-1 review regressions: duplicate query keys, foreign availableCriteria, + // explicit empty / outside-onlyCriteria null score, and URL round-trip parity + assert.equal(parseWeightsParam('smartphones', 'camera:50,camera:0'), null); + assert.equal(parseWeightsParam('smartphones', 'screen:50,display:0'), null); + assert.deepEqual( + defaultCategoryWeights(' LAPTOPS\u0000 '), + defaultCategoryWeights('laptops') + ); + assert.equal( + availableCategoryUseCasePresets('smartphones', ['anc']).length, + 0, + 'Foreign-only availableCriteria returns zero presets' + ); + assert.equal( + computeCustomWeightedScore5( + 'smartphones', + scoresCamPro, + { camera: 80, display: 20 }, + { onlyCriteria: [] } + ).customScore5, + null, + 'Explicit empty onlyCriteria returns null instead of scoring all criteria' + ); + assert.equal( + computeCustomWeightedScore5( + 'smartphones', + scoresCamPro, + { camera: 80, display: 20, performance: 0, battery: 0 }, + { onlyCriteria: ['performance', 'battery'] } + ).customScore5, + null, + 'Weights placed solely outside onlyCriteria return null instead of Balanced Default' + ); + + // Live vs serialized ?weights= round-trip parity (10/10/10 -> 34%/33%/33%) + const rawEqualThree = { + performance: 10, + camera: 10, + battery: 10, + display: 0, + design: 0, + value: 0, + }; + const roundTripScores = { + performance: 5.0, + camera: 4.0, + battery: 4.0, + display: 4.0, + design: 4.0, + value: 4.0, + }; + const liveThreeRes = computeCustomWeightedScore5( + 'smartphones', + roundTripScores, + rawEqualThree + ); + const encodedThree = serializeWeightsParam('smartphones', rawEqualThree); + assert.equal(encodedThree, 'performance:10,camera:10,battery:10'); + assert.equal(liveThreeRes.customScore5, 4.33); + const reloadedThreeRes = computeCustomWeightedScore5( + 'smartphones', + roundTripScores, + parseWeightsParam('smartphones', encodedThree) + ); + assert.equal( + liveThreeRes.customScore5, + reloadedThreeRes.customScore5, + 'Live custom score matches shared/reloaded ?weights= URL score exactly' + ); + + // Small positive slider weight (camera:1 alongside five 100s) is preserved in URL + const tinyCameraEncoded = serializeWeightsParam('smartphones', { + performance: 100, + camera: 1, + battery: 100, + display: 100, + design: 100, + value: 100, + }); + assert.match(tinyCameraEncoded, /\bcamera:1\b/); + + // Exact proportion comparison in isDefaultCategoryWeights + assert.equal( + isDefaultCategoryWeights('smartphones', 'custom', { + performance: 40, + camera: 40, + battery: 40, + display: 30, + design: 20, + value: 30, + }), + true, + 'Exact 2x multiple of smartphone default weights collapses cleanly to default' + ); + assert.equal( + isDefaultCategoryWeights('smartphones', 'custom', { + performance: 100, + camera: 99, + battery: 100, + display: 75, + design: 50, + value: 75, + }), + false, + 'Near-default weights with distinct exact proportions retain custom URL state' + ); +} + +console.log('✅ compare params & RTINGS use-case weights'); diff --git a/apps/web/src/lib/__tests__/leaderboard-criteria.test.ts b/apps/web/src/lib/__tests__/leaderboard-criteria.test.ts index c6b3ee23..8f62d50c 100644 --- a/apps/web/src/lib/__tests__/leaderboard-criteria.test.ts +++ b/apps/web/src/lib/__tests__/leaderboard-criteria.test.ts @@ -3224,3 +3224,596 @@ test('an all-bare leaderboard link records the published masters it represents', assert.equal(query.get('variant.acme'), 'acme-retail-1tb'); assert.equal(query.get('variant.peer'), 'peer-512gb'); }); + +test('RTINGS-style UseCaseWeightBar SSR, Official vs Custom Score parity & WCAG 2.1 AA a11y across vi/en/cs (#1864)', () => { + const IntlProvider = + NextIntlClientProvider as unknown as React.ComponentType<{ + locale: string; + messages: Record; + timeZone: string; + children?: React.ReactNode; + }>; + const stubRouter: AppRouterInstance = { + bfcacheId: '', + back: () => {}, + forward: () => {}, + refresh: () => {}, + push: () => {}, + replace: () => {}, + prefetch: () => {}, + }; + + const HTML_ENTITY_MAP: Readonly> = { + amp: '&', + quot: '"', + '#x27': "'", + '#39': "'", + lt: '<', + gt: '>', + }; + + const extractMarkupText = ( + fragment: string, + skipAriaHidden = false + ): string => { + const out: string[] = []; + let hiddenDepth = 0; + let i = 0; + while (i < fragment.length) { + if (fragment[i] === '<') { + let end = i + 1; + let quote: string | null = null; + while (end < fragment.length) { + const ch = fragment[end]!; + if (quote) { + if (ch === quote) quote = null; + } else if (ch === '"' || ch === "'") { + quote = ch; + } else if (ch === '>') { + break; + } + end += 1; + } + const tagInner = fragment.slice(i + 1, end).trim(); + const isClosing = tagInner.startsWith('/'); + const isSelfClosing = tagInner.endsWith('/'); + if (isClosing) { + if (hiddenDepth > 0) hiddenDepth -= 1; + } else if (hiddenDepth > 0) { + if (!isSelfClosing) hiddenDepth += 1; + } else if ( + skipAriaHidden && + /\baria-hidden\s*=\s*(?:"true"|'true')/i.test(tagInner) + ) { + if (!isSelfClosing) hiddenDepth = 1; + } + if (hiddenDepth === 0) out.push(' '); + i = end + 1; + continue; + } + if (hiddenDepth === 0) { + out.push(fragment[i]!); + } + i += 1; + } + return out + .join('') + .replace( + /&(amp|quot|#x27|#39|lt|gt);/g, + (full, key: string) => HTML_ENTITY_MAP[key] ?? full + ) + .replace(/\s+/g, ' ') + .trim(); + }; + + const assertAccessibleControls = (html: string, context: string) => { + assert.doesNotMatch( + html, + /[\u2013\u2014]|—|–/, + `${context}: zero em-dashes or en-dashes` + ); + + const rangeInputs = [ + ...html.matchAll(/]*type="range"[^>]*>/g), + ].map((m) => m[0]); + assert.ok( + rangeInputs.length >= 5, + `${context}: renders category criterion range sliders` + ); + for (const inputTag of rangeInputs) { + const idMatch = /\bid="([^"]+)"/.exec(inputTag); + assert.ok(idMatch?.[1], `${context}: range input must carry an id`); + const escapedId = idMatch[1].replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + const labelRe = new RegExp( + `]*\\bfor="${escapedId}"[^>]*>([\\s\\S]*?)<\\/label>` + ); + const labelMatch = labelRe.exec(html); + assert.ok( + labelMatch && extractMarkupText(labelMatch[1] ?? '').length > 0, + `${context}: range input #${idMatch[1]} must have a non-empty
)} + {/* Seasonal Sale Campaign Filter Chips (#1863) */} +
+ + {t('campaignFilterLabel')} + + {( + [ + { + key: 'all', + label: t('campaignAll'), + }, + { + key: 'genuine_sale_drops', + label: t('campaignGenuineDrops', { + count: seasonalCampaignCounts.genuineSaleCount, + }), + }, + { + key: 'inflated_presale_warnings', + label: t('campaignInflatedTraps', { + count: seasonalCampaignCounts.inflatedWarningCount, + }), + }, + ] as const + ).map((chip) => ( + + ))} +
+ {/* Budget Slider & Search */}
@@ -1035,133 +1116,152 @@ export default function DealFinderWorkspace({
-
-

-

- {filteredGenuineDeals.length > 0 ? ( -
    - {filteredGenuineDeals.slice(0, 6).map((g) => { - const safeMedian = sanitizeDealRadarPriceVnd( - g.marketMedianPrice - ); - return ( -
  • -
    - - {g.productName} - - - - {g.platform} + {campaignFilter !== 'inflated_presale_warnings' && ( +
    +

    +

    + {filteredGenuineDeals.length > 0 ? ( +
      + {filteredGenuineDeals.slice(0, 6).map((g) => { + const safeMedian = sanitizeDealRadarPriceVnd( + g.marketMedianPrice + ); + return ( +
    • +
      + + {g.productName} + + + + {g.platform} + + + {safeMedian != null && ( + <> + {' '} + ·{' '} + {t('medianPriceLabel', { + price: formatNumber(safeMedian, locale), + })} + + )} - - {safeMedian != null && ( - <> - {' '} - ·{' '} - {t('medianPriceLabel', { - price: formatNumber(safeMedian, locale), - })} - - )} - -
      -
      - - {formatDealRadarPriceVnd(g.priceCurrent, locale)} - - - {t('savingsVsMedianBadge', { - pct: formatPlainNumber( - g.savingsVsMedianPct, +
      +
      + + {formatDealRadarPriceVnd( + g.priceCurrent, locale - ), - })} - -
      -
    • - ); - })} -
    - ) : ( -

    {t('radarNoGenuine')}

    - )} -
    + )} +
    + + {t('savingsVsMedianBadge', { + pct: formatPlainNumber( + g.savingsVsMedianPct, + locale + ), + })} + +
    +
  • + ); + })} +
+ ) : ( +

{t('radarNoGenuine')}

+ )} +
+ )} -
-

-

- {filteredFakeSaleTraps.length > 0 ? ( -
    - {filteredFakeSaleTraps.slice(0, 6).map((trap) => { - const claimedOrig = resolveClaimedOriginalPriceVnd( - trap.priceOriginal, - trap.priceCurrent - ); - return ( -
  • -
    - - {trap.productName} - - - - {trap.platform} + {campaignFilter !== 'genuine_sale_drops' && ( +
    +

    +

    + {filteredFakeSaleTraps.length > 0 ? ( +
      + {filteredFakeSaleTraps.slice(0, 6).map((trap) => { + const claimedOrig = resolveClaimedOriginalPriceVnd( + trap.priceOriginal, + trap.priceCurrent + ); + return ( +
    • +
      + + {trap.productName} + + + + {trap.platform} + + + {claimedOrig != null && ( + <> + {' '} + · {t('claimedOrigLabel')}{' '} + {formatPriceVnd(claimedOrig, locale)} + + )} - - {claimedOrig != null && ( - <> - {' '} - · {t('claimedOrigLabel')}{' '} - {formatPriceVnd(claimedOrig, locale)} - - )} - -
      -
      - - {formatDealRadarPriceVnd( - trap.priceCurrent, - locale - )} - - - {t('fakeMarkupBadge', { - pct: formatPlainNumber( - trap.fakeMarkupPct, +
      +
      + + {formatDealRadarPriceVnd( + trap.priceCurrent, locale - ), - })} - -
      -
    • - ); - })} -
    - ) : ( -

    {t('radarNoTraps')}

    - )} -
    + )} +
    + + {t('fakeMarkupBadge', { + pct: formatPlainNumber( + trap.fakeMarkupPct, + locale + ), + })} + +
    +
  • + ); + })} +
+ ) : ( +

{t('radarNoTraps')}

+ )} +
+ )}
{filteredPriceSpreadLeaders.length > 0 && ( @@ -1216,114 +1316,190 @@ export default function DealFinderWorkspace({ {rankedDeals.length === 0 ? (

- {t('emptyBudgetText', { - budget: formatNumber(maxBudgetVnd, locale), - })} + {campaignFilter === 'genuine_sale_drops' && + baseRankedDeals.length > 0 + ? t('campaignEmptyGenuine') + : campaignFilter === 'inflated_presale_warnings' && + baseRankedDeals.length > 0 + ? t('campaignEmptyTraps') + : t('emptyBudgetText', { + budget: formatNumber(maxBudgetVnd, locale), + })}

) : ( <>
- {rankedDeals.slice(0, visibleCount).map((deal) => ( -
-
-
-
-
- - {t('rankDealBadge', { rank: deal.rank })} - - {deal.brand} - - - {deal.expertScore10 != null - ? `Lab ${formatDecimal(deal.expertScore10, locale, 1)}/10` - : t('labNoScore')} - - + {rankedDeals.slice(0, visibleCount).map((deal) => { + const dealSignal = getRadarSignal(radarIndex, deal.slug); + const trapOrig = dealSignal.fakeSaleTrap + ? resolveClaimedOriginalPriceVnd( + dealSignal.fakeSaleTrap.priceOriginal, + dealSignal.fakeSaleTrap.priceCurrent + ) + : null; + const genuineSavingsVnd = dealSignal.genuineDeal + ? sanitizeDealRadarPriceVnd( + dealSignal.genuineDeal.savingsVsMedianVnd + ) + : null; + return ( +
+
+
+
+
+ + {t('rankDealBadge', { rank: deal.rank })} + + {deal.brand} + + + {deal.expertScore10 != null + ? `Lab ${formatDecimal(deal.expertScore10, locale, 1)}/10` + : t('labNoScore')} + + +
+ {deal.spreadSavingsVnd > 0 && ( + + {t('spreadSavingsBadge', { + amount: formatNumber( + deal.spreadSavingsVnd, + locale + ), + })} + + )}
- {deal.spreadSavingsVnd > 0 && ( - - {t('spreadSavingsBadge', { - amount: formatNumber(deal.spreadSavingsVnd, locale), - })} - - )} -
-
- {deal.name} -
- - {deal.name} - -
- {formatPriceVnd(deal.minPrice, locale)}{' '} - {deal.costPerPointVnd > 0 && ( - - {t('costPerPointSub', { - cost: formatNumber( - deal.costPerPointVnd, - locale - ), - })} - - )} +
+ {deal.name} +
+ + {deal.name} + +
+ {formatPriceVnd(deal.minPrice, locale)}{' '} + {deal.costPerPointVnd > 0 && ( + + {t('costPerPointSub', { + cost: formatNumber( + deal.costPerPointVnd, + locale + ), + })} + + )} +
+ + {campaignFilter === 'inflated_presale_warnings' && + dealSignal.fakeSaleTrap && + trapOrig != null && ( +
+ {t('campaignCardTrapNote', { + platform: + dealSignal.fakeSaleTrap.platform.toUpperCase(), + claimed: formatPriceVnd(trapOrig, locale), + pct: formatPlainNumber( + dealSignal.fakeSaleTrap.fakeMarkupPct, + locale + ), + })} +
+ )} + + {campaignFilter === 'genuine_sale_drops' && + dealSignal.genuineDeal && + genuineSavingsVnd != null && ( +
+ {t('campaignCardGenuineNote', { + platform: + dealSignal.genuineDeal.platform.toUpperCase(), + savings: formatPriceVnd( + genuineSavingsVnd, + locale + ), + pct: formatPlainNumber( + dealSignal.genuineDeal.savingsVsMedianPct, + locale + ), + })} +
+ )}
-
-
- - - {t('audit10PlatformsLink')} - +
+ + + {t('audit10PlatformsLink')} + +
-
- ))} + ); + })}
{rankedDeals.length > visibleCount && (
diff --git a/apps/web/src/components/inspect/DeepInspectWorkspace.tsx b/apps/web/src/components/inspect/DeepInspectWorkspace.tsx index 7f2fa602..f5111284 100644 --- a/apps/web/src/components/inspect/DeepInspectWorkspace.tsx +++ b/apps/web/src/components/inspect/DeepInspectWorkspace.tsx @@ -12,12 +12,21 @@ import { discountVerdictCopy, type VerdictTranslator, } from '@/lib/discount-verdict-copy'; +import { + evaluateOmnibusPriceAudit, + formatOmnibusAuditCopy, + resolveOmnibusReferenceAnchorMs, + sanitizeOmnibusPriceVnd, + type OmnibusPriceAuditResult, + type OmnibusVerdictTranslator, +} from '@/lib/omnibus-price-audit'; import { formatScoreFixed, roundScore } from '@/lib/rating-display'; import AnalyzerText from '@/components/reviews/AnalyzerText'; import { useDetailsDismiss } from '@/components/elementary/use-details-dismiss'; import { Link, useRouter } from '@/lib/navigation'; import { MAX_VALID_VND_PRICE, + getMasterProductCategorySlug, getMasterProductHref, resolveCompareBatteryMah, resolveCompareEffectiveUserRating, @@ -69,6 +78,7 @@ import { implausiblyLowIndexes, isImplausiblyLowPrice, isOfferImplausiblyLowAgainstInStock, + minimumListingPriceVnd, normalizeOfferId, plausibleMinPrice, plausibleOffers, @@ -1318,6 +1328,166 @@ export default function DeepInspectWorkspace({ ? resolveCompareExpertRating10(master) : null; + const explicitMatchedOffer = result?.matchedOffer ?? null; + + const inspectOmnibusState = useMemo<{ + audit: OmnibusPriceAuditResult; + listingScoped: boolean; + } | null>(() => { + if ( + offerImplausiblyLow || + matchedOfferUnavailable || + verdictPrices.currentPriceVnd <= 0 || + !priceHistory || + !Array.isArray(priceHistory.points) || + priceHistory.points.length === 0 + ) { + return null; + } + + const minValidPriceVnd = + master && getMasterProductCategorySlug(master) === 'earbuds' + ? MINIMUM_EARBUDS_PRICE_FLOOR_VND + : minimumListingPriceVnd([ + master?.name ?? '', + explicitMatchedOffer?.title ?? matchedOffer?.title ?? '', + result?.query ?? '', + ]); + + const anchorMs = resolveOmnibusReferenceAnchorMs({ + points: priceHistory.points, + referenceOffers: result?.allOffers, + implausibleOfferIds, + minValidPriceVnd, + }); + + if (explicitMatchedOffer?.id) { + if ( + isOfferUnavailable(explicitMatchedOffer) || + isInspectOfferBait( + explicitMatchedOffer, + implausibleOfferIds, + plausibilityOffers + ) + ) { + return null; + } + const listingCurrentVnd = sanitizeOmnibusPriceVnd( + explicitMatchedOffer.price_current, + minValidPriceVnd + ); + if (listingCurrentVnd == null) { + return null; + } + const rawListingOrig = sanitizeInspectOriginalPriceVnd( + explicitMatchedOffer.price_original, + listingCurrentVnd + ); + const listingOrigVnd = rawListingOrig > 0 ? rawListingOrig : null; + + const targetCanon = normalizeOfferId(explicitMatchedOffer.id); + const offerPts = priceHistory.points.filter((pt) => { + if (pt.source === 'live_listing') return false; + if (pt.product_id === explicitMatchedOffer.id) return true; + return Boolean( + targetCanon && normalizeOfferId(pt.product_id) === targetCanon + ); + }); + const marketCycleForListing = evaluateOmnibusPriceAudit({ + points: priceHistory.points, + currentPriceVnd: listingCurrentVnd, + claimedOriginalPriceVnd: listingOrigVnd, + currentInStockPriceVnd: listingCurrentVnd, + mode: 'market', + referenceOffers: result?.allOffers, + implausibleOfferIds, + minValidPriceVnd, + referenceTimestampMs: anchorMs, + }); + const offerAudit = evaluateOmnibusPriceAudit({ + points: offerPts, + currentPriceVnd: listingCurrentVnd, + claimedOriginalPriceVnd: listingOrigVnd, + currentInStockPriceVnd: listingCurrentVnd, + mode: 'offer', + referenceOffers: result?.allOffers, + implausibleOfferIds, + minValidPriceVnd, + referenceTimestampMs: anchorMs, + }); + return { + audit: { + ...offerAudit, + cycle90d: + marketCycleForListing.cycle90d.signal !== 'insufficient_data' + ? marketCycleForListing.cycle90d + : offerAudit.cycle90d, + }, + listingScoped: true, + }; + } + + const inStockFloorVnd = + safeMasterMinPriceVnd > 0 + ? safeMasterMinPriceVnd + : verdictPrices.currentPriceVnd; + let bestInStockOrig: number | null = null; + for (const off of inStockOffers) { + if (isInspectOfferBait(off, implausibleOfferIds, plausibilityOffers)) { + continue; + } + if (sanitizeInspectPriceVnd(off.price_current) !== inStockFloorVnd) { + continue; + } + const orig = sanitizeInspectOriginalPriceVnd( + off.price_original, + inStockFloorVnd + ); + if (orig > 0 && (bestInStockOrig == null || orig > bestInStockOrig)) { + bestInStockOrig = orig; + } + } + + const marketAudit = evaluateOmnibusPriceAudit({ + points: priceHistory.points, + currentPriceVnd: inStockFloorVnd, + claimedOriginalPriceVnd: bestInStockOrig, + currentInStockPriceVnd: + safeMasterMinPriceVnd > 0 ? safeMasterMinPriceVnd : null, + mode: 'market', + referenceOffers: result?.allOffers, + implausibleOfferIds, + minValidPriceVnd, + referenceTimestampMs: anchorMs, + }); + + return { + audit: marketAudit, + listingScoped: false, + }; + }, [ + explicitMatchedOffer, + implausibleOfferIds, + inStockOffers, + master, + matchedOffer?.title, + matchedOfferUnavailable, + offerImplausiblyLow, + plausibilityOffers, + priceHistory, + result?.allOffers, + result?.query, + safeMasterMinPriceVnd, + verdictPrices.currentPriceVnd, + ]); + + const tOmnibus: OmnibusVerdictTranslator = (key, values) => + tVerdict(key, values); + const inspectOmnibusCopy = + inspectOmnibusState && inspectOmnibusState.audit.currentPriceVnd != null + ? formatOmnibusAuditCopy(inspectOmnibusState.audit, tOmnibus, locale) + : null; + const handleCopyAuditMarkdown = async () => { if (typeof window === 'undefined') return; try { @@ -1755,6 +1925,157 @@ export default function DeepInspectWorkspace({
)} + {/* 3-Column EU Omnibus 30-Day Floor Audit & 90-Day Cycle (#1863) */} + {inspectOmnibusCopy && inspectOmnibusState && ( +
+
+
+

+

+
+ {inspectOmnibusState.listingScoped && + explicitMatchedOffer + ? (() => { + const resolvedMerchantName = + explicitMatchedOffer.merchant?.name || + merchant?.name || + t('unknownShop'); + const scopeParts = t('omnibusScopeListing', { + merchant: '\u0000', + platform: + resolveInspectOfferPlatform( + explicitMatchedOffer + ).toUpperCase(), + }).split('\u0000'); + return ( + <> + {scopeParts[0]} + + {scopeParts[1] ?? ''} + + ); + })() + : t('omnibusScopeProduct')} +
+
+ + {inspectOmnibusCopy.statusBadgeText} + +
+ +
+
+
+
+ {inspectOmnibusCopy.colCurrentTitle} +
+
+ + {inspectOmnibusCopy.currentPriceText} + + {inspectOmnibusCopy.claimedBadgeText && ( + + {inspectOmnibusCopy.claimedBadgeText} + + )} +
+
+ {inspectOmnibusCopy.currentSubText} +
+
+
+ +
+
+
+ {inspectOmnibusCopy.colFloorTitle} +
+
+ {inspectOmnibusCopy.floorPriceText} +
+
+ {inspectOmnibusCopy.floorDeltaText} +
+ {inspectOmnibusCopy.floorDisclaimerText && ( +
+ {inspectOmnibusCopy.floorDisclaimerText} +
+ )} +
+
+ +
+
+
+ {inspectOmnibusCopy.colCycleTitle} +
+
+ {inspectOmnibusCopy.cycleValueText} +
+
+ {inspectOmnibusCopy.cycleSubText} +
+
+
+
+
+ )} + {((matchedGenuineDeal && sanitizeInspectPriceVnd(matchedGenuineDeal.priceCurrent) > 0) || diff --git a/apps/web/src/components/price-history/PriceHistorySection.tsx b/apps/web/src/components/price-history/PriceHistorySection.tsx index ede93d34..2fbae3ca 100644 --- a/apps/web/src/components/price-history/PriceHistorySection.tsx +++ b/apps/web/src/components/price-history/PriceHistorySection.tsx @@ -15,6 +15,22 @@ import { BsGraphUp, BsSearch, } from 'react-icons/bs'; +import { + evaluateOmnibusPriceAudit, + formatOmnibusAuditCopy, + resolveOmnibusReferenceAnchorMs, + type OmnibusPriceAuditResult, + type OmnibusReferenceOfferInput, + type OmnibusVerdictTranslator, +} from '@/lib/omnibus-price-audit'; +import { + minimumListingPriceVnd, + normalizeOfferId, +} from '@repo/shared-data/rules'; +import { + isOfferUnavailable, + type OfferAvailability, +} from '@/lib/product-market-stats'; import { MAX_VALID_VND_PRICE, type DiscountVerdictType, @@ -48,6 +64,7 @@ interface PriceHistorySectionProps { productName: string; history: MasterProductPriceHistorySummary; radarSignal?: RadarSignal | null; + offers?: readonly OmnibusReferenceOfferInput[] | null; } type TimeRangeKey = '30d' | '90d' | 'all'; @@ -331,6 +348,7 @@ export default function PriceHistorySection({ productName, history, radarSignal, + offers, }: PriceHistorySectionProps) { const t = useTranslations('productDetail'); const tVerdict = useTranslations('priceVerdict'); @@ -648,6 +666,243 @@ export default function PriceHistorySection({ const hasAuditEvidence = validPoints.length > 0 || offerAnalyses.length > 0; + const minValidPriceVnd = useMemo( + () => minimumListingPriceVnd([productName]), + [productName] + ); + + const safeCurrentMinPrice = useMemo(() => { + const raw = Number(history.currentMinPrice); + if (!Number.isFinite(raw) || raw <= 0 || raw > MAX_VALID_VND_PRICE) { + return null; + } + return Math.round(raw); + }, [history.currentMinPrice]); + + // Identify unavailable (sold-out / discontinued) offers from explicit `offers`, + // optional `availability` on `offerAnalyses`, prices strictly below the + // verified in-stock minimum (DOS/Rate#1141), or `rate-api`'s unavailable + // suppression signature (`normal_price` despite qualifying for `genuine_deal`). + const unavailableOfferIds = useMemo>(() => { + const ids = new Set(); + const addId = (rawId: string | null | undefined) => { + if (!rawId) return; + ids.add(rawId); + const canon = normalizeOfferId(rawId); + if (canon) ids.add(canon); + }; + + if (Array.isArray(offers)) { + for (const off of offers) { + if (off && isOfferUnavailable(off)) { + addId(off.id); + } + } + } + + for (const oa of offerAnalyses) { + const maybeAvail = (oa as { availability?: OfferAvailability | null }) + .availability; + if (maybeAvail && isOfferUnavailable({ availability: maybeAvail })) { + addId(oa.product_id); + continue; + } + const p = Number(oa.price_current); + if ( + safeCurrentMinPrice != null && + Number.isFinite(p) && + p > 0 && + Math.round(p) < safeCurrentMinPrice + ) { + addId(oa.product_id); + continue; + } + // In rate-api.ts, an offer with real_discount_vs_median_pct >= 3 (or at + // multi-point historical min below max) that is neither fake nor + // suspicious is assigned `normal_price` ONLY when `offerUnavailable` is true. + const claimsDiscount = + oa.price_original != null && oa.claimed_discount_pct >= 5; + const wouldBeFakeOrSuspicious = + claimsDiscount && + oa.claimed_discount_pct - oa.real_discount_vs_median_pct >= 6; + const qualifiesForGenuine = + oa.real_discount_vs_median_pct >= 3 || + (!claimsDiscount && + oa.observation_count >= 2 && + oa.price_current <= oa.historical_min_price && + oa.historical_min_price < oa.historical_max_price) || + (claimsDiscount && oa.price_current <= oa.historical_min_price); + if ( + oa.verdict === 'normal_price' && + !wouldBeFakeOrSuspicious && + qualifiesForGenuine + ) { + addId(oa.product_id); + } + } + return ids; + }, [offerAnalyses, offers, safeCurrentMinPrice]); + + const isUnavailId = useCallback( + (id: string) => + unavailableOfferIds.has(id) || + unavailableOfferIds.has(normalizeOfferId(id)), + [unavailableOfferIds] + ); + + const effectiveReferenceOffers = useMemo( + () => + Array.isArray(offers) && offers.length > 0 + ? [...offers] + : offerAnalyses.map((oa) => ({ + id: oa.product_id, + price_current: oa.price_current, + availability: isUnavailId(oa.product_id) + ? ('out_of_stock' as const) + : ('in_stock' as const), + })), + [isUnavailId, offerAnalyses, offers] + ); + + // Historical anchor uses the exact same evidence-eligibility rules as the + // Omnibus evaluator so rows below `minValidPriceVnd`, `live_listing` rows, + // bait listings, and unavailable offers never advance the anchor (#1863). + const omnibusAnchorMs = useMemo( + () => + resolveOmnibusReferenceAnchorMs({ + points: validPoints, + referenceOffers: effectiveReferenceOffers, + unavailableOfferIds, + minValidPriceVnd, + }), + [ + effectiveReferenceOffers, + minValidPriceVnd, + unavailableOfferIds, + validPoints, + ] + ); + + const omnibusSharedOpts = useMemo( + () => ({ + referenceOffers: effectiveReferenceOffers, + unavailableOfferIds, + minValidPriceVnd, + referenceTimestampMs: omnibusAnchorMs, + }), + [ + effectiveReferenceOffers, + minValidPriceVnd, + omnibusAnchorMs, + unavailableOfferIds, + ] + ); + + const omnibusByOffer = useMemo>(() => { + const map = new Map(); + if ( + validPoints.length === 0 || + offerAnalyses.length === 0 || + safeCurrentMinPrice == null + ) { + return map; + } + const pointsByOfferId = new Map(); + for (const pt of validPoints) { + if (pt.source === 'live_listing') continue; + const list = pointsByOfferId.get(pt.product_id); + if (list) list.push(pt); + else pointsByOfferId.set(pt.product_id, [pt]); + } + for (const oa of offerAnalyses) { + if (isUnavailId(oa.product_id)) continue; + const pts = pointsByOfferId.get(oa.product_id); + if (!pts) continue; + map.set( + oa.product_id, + evaluateOmnibusPriceAudit({ + ...omnibusSharedOpts, + points: pts, + currentPriceVnd: oa.price_current, + claimedOriginalPriceVnd: oa.price_original, + currentInStockPriceVnd: oa.price_current, + mode: 'offer', + }) + ); + } + return map; + }, [ + isUnavailId, + offerAnalyses, + omnibusSharedOpts, + safeCurrentMinPrice, + validPoints, + ]); + + const omnibusAudit = useMemo(() => { + if (selectedProductId !== 'ALL') { + const cached = omnibusByOffer.get(selectedProductId); + if (cached) return cached; + const selectedOa = offerAnalyses.find( + (oa) => oa.product_id === selectedProductId + ); + return evaluateOmnibusPriceAudit({ + ...omnibusSharedOpts, + points: validPoints.filter((pt) => pt.product_id === selectedProductId), + currentPriceVnd: selectedOa?.price_current ?? null, + claimedOriginalPriceVnd: selectedOa?.price_original ?? null, + currentInStockPriceVnd: null, + currentOfferUnavailable: true, + mode: 'offer', + }); + } + + let bestClaimedOrig: number | null = null; + if (safeCurrentMinPrice != null) { + const atMin = offerAnalyses.filter( + (oa) => + Math.round(Number(oa.price_current)) === safeCurrentMinPrice && + !isUnavailId(oa.product_id) + ); + const genuines = atMin.filter((oa) => oa.verdict === 'genuine_deal'); + for (const oa of genuines.length > 0 ? genuines : atMin) { + const orig = Number(oa.price_original); + if ( + Number.isFinite(orig) && + orig > safeCurrentMinPrice && + orig <= MAX_VALID_VND_PRICE && + (bestClaimedOrig == null || orig > bestClaimedOrig) + ) { + bestClaimedOrig = Math.round(orig); + } + } + } + + return evaluateOmnibusPriceAudit({ + ...omnibusSharedOpts, + points: validPoints, + currentPriceVnd: safeCurrentMinPrice, + claimedOriginalPriceVnd: bestClaimedOrig, + currentInStockPriceVnd: safeCurrentMinPrice, + mode: 'market', + }); + }, [ + isUnavailId, + offerAnalyses, + omnibusByOffer, + omnibusSharedOpts, + safeCurrentMinPrice, + selectedProductId, + validPoints, + ]); + + const tOmnibus: OmnibusVerdictTranslator = (key, values) => + tVerdict(key, values); + const omnibusCopy = + validPoints.length > 0 && omnibusAudit.currentPriceVnd != null + ? formatOmnibusAuditCopy(omnibusAudit, tOmnibus, locale) + : null; + const activeNode = chartGeometry && activePointIndex != null ? chartGeometry.mapped[activePointIndex] || @@ -824,6 +1079,111 @@ export default function PriceHistorySection({
+ {/* 3-Column EU Omnibus 30-Day Floor Audit & 90-Day Cycle Signal (#1863) */} + {omnibusCopy && ( +
+
+

+

+ + {omnibusCopy.statusBadgeText} + +
+ +
+ {[ + { + k: 'cur', + title: omnibusCopy.colCurrentTitle, + val: omnibusCopy.currentPriceText, + valCls: 'h5 fw-bold text-danger rate-tabular mb-0', + badge: omnibusCopy.claimedBadgeText, + sub: omnibusCopy.currentSubText, + subCls: + omnibusCopy.currentSubTone === 'bad' + ? 'text-danger fw-semibold' + : omnibusCopy.currentSubTone === 'good' + ? 'text-success' + : 'text-muted', + note: null, + testId: undefined, + }, + { + k: 'flr', + title: omnibusCopy.colFloorTitle, + val: omnibusCopy.floorPriceText, + valCls: 'h5 fw-bold text-dark rate-tabular mb-1', + badge: null, + sub: omnibusCopy.floorDeltaText, + subCls: + omnibusCopy.floorDeltaTone === 'good' + ? 'text-success fw-semibold' + : omnibusCopy.floorDeltaTone === 'bad' + ? 'text-danger fw-semibold' + : 'text-secondary', + note: omnibusCopy.floorDisclaimerText, + testId: undefined, + }, + { + k: 'cyc', + title: omnibusCopy.colCycleTitle, + val: omnibusCopy.cycleValueText, + valCls: `fw-bold mb-1 ${ + omnibusCopy.cycleValueTone === 'good' + ? 'text-success' + : omnibusCopy.cycleValueTone === 'bad' + ? 'text-danger' + : 'text-dark' + }`, + badge: null, + sub: omnibusCopy.cycleSubText, + subCls: 'text-muted', + note: null, + testId: 'omnibus-cycle-signal', + }, + ].map((col) => ( +
+
+
{col.title}
+ {col.badge ? ( +
+ {col.val} + + {col.badge} + +
+ ) : ( +
+ {col.val} +
+ )} +
{col.sub}
+ {col.note && ( +
{col.note}
+ )} +
+
+ ))} +
+
+ )} + {/* Controls: Merchant Filter & Time Range. Single-select groups that expose the pressed choice, not only its colour (DOS/Rate#1069). */}
@@ -1276,6 +1636,33 @@ export default function PriceHistorySection({ {formatVnd(oa.historical_max_price, locale)} + {(() => { + const offerOmnibus = omnibusByOffer.get(oa.product_id); + if ( + !offerOmnibus || + offerOmnibus.priorFloorPriceVnd == null || + (offerOmnibus.windowStatus !== + 'omnibus_30d_certified' && + offerOmnibus.windowStatus !== 'partial_window') + ) { + return null; + } + const floorFormatted = formatVnd( + offerOmnibus.priorFloorPriceVnd, + locale + ); + return ( + + {offerOmnibus.windowStatus === 'omnibus_30d_certified' + ? tOmnibus('oOk') + : tOmnibus('oPart', { + days: offerOmnibus.windowDaysUsed, + })} + {': '} + {floorFormatted} + + ); + })()}

diff --git a/apps/web/src/lib/__tests__/discount-verdict-copy.test.ts b/apps/web/src/lib/__tests__/discount-verdict-copy.test.ts index 7f618956..e8040eae 100644 --- a/apps/web/src/lib/__tests__/discount-verdict-copy.test.ts +++ b/apps/web/src/lib/__tests__/discount-verdict-copy.test.ts @@ -5,6 +5,12 @@ import { discountVerdictCopy, type VerdictTranslator, } from '../discount-verdict-copy'; +import { + evaluateOmnibusPriceAudit, + formatOmnibusAuditCopy, + type OmnibusVerdictTranslator, +} from '../omnibus-price-audit'; +import { NBSP } from '../locale-format'; import type { OfferDiscountAnalysis } from '../rate-api'; const LOCALES = ['vi', 'en', 'cs'] as const; @@ -141,6 +147,246 @@ function main() { ); assert.equal(fallbackNull.label, messages.en.labelNormal); + // ========================================================================= + // EU Omnibus 30-Day Price-Floor Audit & Locale Parity (#1863) + // ========================================================================= + const DAY_MS = 86_400_000; + const ANCHOR_MS = Date.UTC(2026, 10, 22, 12, 0, 0); + const isoDaysAgo = (days: number) => + new Date(ANCHOR_MS - days * DAY_MS).toISOString(); + + const omnibusTranslator = ( + dict: Record + ): OmnibusVerdictTranslator => { + return (key, values = {}) => { + const msg = dict[key]; + assert.ok(msg, `missing priceVerdict.${key}`); + return msg.replace(/\{(\w+)\}/g, (_, name: string) => { + assert.ok(name in values, `${key} missing {${name}}`); + return String(values[name]); + }); + }; + }; + + // 1. Key parity & zero em/en-dash check across deals, inspect, priceVerdict + const fullCatalogs = Object.fromEntries( + LOCALES.map((loc) => [ + loc, + JSON.parse( + readFileSync( + join(__dirname, '..', '..', '..', 'locales', `${loc}.json`), + 'utf8' + ) + ) as Record>, + ]) + ) as Record<(typeof LOCALES)[number], Record>>; + + for (const ns of ['deals', 'inspect', 'priceVerdict'] as const) { + const viKeys = Object.keys(fullCatalogs.vi[ns]!).sort(); + for (const loc of LOCALES) { + assert.deepEqual( + Object.keys(fullCatalogs[loc][ns]!).sort(), + viKeys, + `${loc}.${ns} key parity` + ); + for (const [k, v] of Object.entries(fullCatalogs[loc][ns]!)) { + assert.ok( + !/[\u2013\u2014]/.test(String(v)), + `${loc}.${ns}.${k} must not contain en-dash or em-dash` + ); + } + } + } + + // 2. Proposal real flash-sale scenario: 27.49M prior 30d floor -> 27.19M today + // while seller claims -22.3% from 34.99M. + const flashSaleAudit = evaluateOmnibusPriceAudit({ + points: [ + { product_id: 'o1', price: 27_490_000, recorded_at: isoDaysAgo(35) }, + { product_id: 'o1', price: 27_990_000, recorded_at: isoDaysAgo(24) }, + { product_id: 'o1', price: 27_490_000, recorded_at: isoDaysAgo(14) }, + { product_id: 'o1', price: 27_690_000, recorded_at: isoDaysAgo(6) }, + { product_id: 'o1', price: 27_190_000, recorded_at: isoDaysAgo(1) }, + { product_id: 'o1', price: 27_190_000, recorded_at: isoDaysAgo(0) }, + ], + currentPriceVnd: 27_190_000, + claimedOriginalPriceVnd: 34_990_000, + referenceTimestampMs: ANCHOR_MS, + }); + assert.equal(flashSaleAudit.isOmnibusCertified, true); + assert.equal(flashSaleAudit.windowStatus, 'omnibus_30d_certified'); + assert.equal(flashSaleAudit.priorFloorPriceVnd, 27_490_000); + assert.equal(flashSaleAudit.deltaVsPriorFloorVnd, -300_000); + assert.equal(flashSaleAudit.deltaVsPriorFloorPct, -1.1); + assert.equal(flashSaleAudit.verdict, 'exaggerated_strikethrough'); + + for (const loc of LOCALES) { + const copy = formatOmnibusAuditCopy( + flashSaleAudit, + omnibusTranslator(messages[loc]), + loc + ); + assert.equal(copy.statusBadgeTone, 'good'); + assert.equal(copy.floorDeltaTone, 'good'); + if (loc === 'cs') { + assert.ok(copy.floorDeltaText.includes(`-1,1${NBSP}%`)); + assert.ok(copy.floorDeltaText.includes(`300${NBSP}000${NBSP}₫`)); + } else { + assert.ok(copy.floorDeltaText.includes('-1.1%')); + assert.ok(copy.floorDeltaText.includes('300.000 ₫')); + } + } + + // 3. Hlidac shopu pre-sale bump / fake strikethrough trap: + // Sold at 24.99M 25 days ago, bumped to 34.99M 10 days ago, now 25.19M. + const preSaleBumpAudit = evaluateOmnibusPriceAudit({ + points: [ + { product_id: 'o1', price: 24_990_000, recorded_at: isoDaysAgo(32) }, + { product_id: 'o1', price: 24_990_000, recorded_at: isoDaysAgo(22) }, + { product_id: 'o1', price: 34_990_000, recorded_at: isoDaysAgo(10) }, + { product_id: 'o1', price: 25_190_000, recorded_at: isoDaysAgo(0) }, + ], + currentPriceVnd: 25_190_000, + claimedOriginalPriceVnd: 34_990_000, + referenceTimestampMs: ANCHOR_MS, + }); + assert.equal(preSaleBumpAudit.isOmnibusCertified, true); + assert.equal(preSaleBumpAudit.priorFloorPriceVnd, 24_990_000); + assert.equal(preSaleBumpAudit.deltaVsPriorFloorVnd, 200_000); + assert.equal(preSaleBumpAudit.deltaVsPriorFloorPct, 0.8); + assert.equal(preSaleBumpAudit.verdict, 'fake_strikethrough_above_floor'); + const bumpEnCopy = formatOmnibusAuditCopy( + preSaleBumpAudit, + omnibusTranslator(messages.en), + 'en' + ); + assert.equal(bumpEnCopy.statusBadgeTone, 'bad'); + assert.equal(bumpEnCopy.floorDeltaTone, 'bad'); + assert.ok(bumpEnCopy.floorDeltaText.includes('+200.000 ₫')); + assert.ok(bumpEnCopy.floorDeltaText.includes('+0.8%')); + + // 4. Strict < 30d window honesty: 18 days of history never claims 30d Omnibus + const shortWindowAudit = evaluateOmnibusPriceAudit({ + points: [ + { product_id: 'o1', price: 24_990_000, recorded_at: isoDaysAgo(18) }, + { product_id: 'o1', price: 26_990_000, recorded_at: isoDaysAgo(10) }, + { product_id: 'o1', price: 25_490_000, recorded_at: isoDaysAgo(4) }, + { product_id: 'o1', price: 25_490_000, recorded_at: isoDaysAgo(0) }, + ], + currentPriceVnd: 25_490_000, + claimedOriginalPriceVnd: 32_990_000, + referenceTimestampMs: ANCHOR_MS, + }); + assert.equal(shortWindowAudit.isOmnibusCertified, false); + assert.equal(shortWindowAudit.windowStatus, 'partial_window'); + assert.equal(shortWindowAudit.windowDaysUsed, 18); + assert.equal(shortWindowAudit.verdict, 'unverified_window'); + for (const loc of LOCALES) { + const shortCopy = formatOmnibusAuditCopy( + shortWindowAudit, + omnibusTranslator(messages[loc]), + loc + ); + assert.ok(shortCopy.statusBadgeText.includes('18')); + assert.ok(shortCopy.floorDisclaimerText?.includes('18/30')); + assert.equal(shortCopy.statusBadgeTone, 'warn'); + } + + // 5. Blackout gap (> 18d inside 30d window) withholds 30d Omnibus certification + const gappedAudit = evaluateOmnibusPriceAudit({ + points: [ + { product_id: 'o1', price: 24_990_000, recorded_at: isoDaysAgo(35) }, + { product_id: 'o1', price: 26_990_000, recorded_at: isoDaysAgo(2) }, + { product_id: 'o1', price: 25_990_000, recorded_at: isoDaysAgo(0) }, + ], + currentPriceVnd: 25_990_000, + claimedOriginalPriceVnd: 29_990_000, + referenceTimestampMs: ANCHOR_MS, + }); + assert.equal(gappedAudit.hasBlackoutGap, true); + assert.equal(gappedAudit.isOmnibusCertified, false); + assert.equal(gappedAudit.windowStatus, 'blackout_gap'); + assert.equal(gappedAudit.verdict, 'unverified_window'); + + // 6. Step-function boundary: an expired 40-day-old flash low superseded at d=31 + // does not leak into the 30-day window. + const supersededAudit = evaluateOmnibusPriceAudit({ + points: [ + { product_id: 'o1', price: 19_990_000, recorded_at: isoDaysAgo(40) }, + { product_id: 'o1', price: 27_990_000, recorded_at: isoDaysAgo(31) }, + { product_id: 'o1', price: 27_990_000, recorded_at: isoDaysAgo(20) }, + { product_id: 'o1', price: 27_990_000, recorded_at: isoDaysAgo(10) }, + { product_id: 'o1', price: 26_990_000, recorded_at: isoDaysAgo(0) }, + ], + currentPriceVnd: 26_990_000, + claimedOriginalPriceVnd: 27_990_000, + referenceTimestampMs: ANCHOR_MS, + }); + assert.equal(supersededAudit.isOmnibusCertified, true); + assert.equal(supersededAudit.priorFloorPriceVnd, 27_990_000); + assert.equal(supersededAudit.verdict, 'verified_omnibus_reduction'); + + // 7. Insufficient (< 1d) history with claimed strikethrough never claims alignment + const brandNewListingAudit = evaluateOmnibusPriceAudit({ + points: [ + { product_id: 'o1', price: 25_990_000, recorded_at: isoDaysAgo(0) }, + ], + currentPriceVnd: 25_990_000, + claimedOriginalPriceVnd: 31_990_000, + referenceTimestampMs: ANCHOR_MS, + }); + assert.equal(brandNewListingAudit.windowStatus, 'insufficient_history'); + const brandNewCopy = formatOmnibusAuditCopy( + brandNewListingAudit, + omnibusTranslator(messages.en), + 'en' + ); + assert.equal(brandNewCopy.currentSubTone, 'neutral'); + assert.equal(brandNewCopy.currentSubText, messages.en.oNeed); + + // 8. Round-1 regressions: trailing unobserved silence (`seriesSpanMs < 30d`), + // blackout_gap windowDaysUsed = 0, and sub-0.05% precision without -0%/+0%. + const trailingSilenceAudit = evaluateOmnibusPriceAudit({ + points: [ + { product_id: 'o1', price: 24_990_000, recorded_at: isoDaysAgo(32) }, + { product_id: 'o1', price: 25_490_000, recorded_at: isoDaysAgo(22) }, + { product_id: 'o1', price: 25_490_000, recorded_at: isoDaysAgo(12) }, + { product_id: 'o1', price: 25_490_000, recorded_at: isoDaysAgo(8) }, + ], + currentPriceVnd: 25_490_000, + claimedOriginalPriceVnd: 29_990_000, + referenceTimestampMs: ANCHOR_MS, + }); + assert.equal(trailingSilenceAudit.observedSpanDays, 24); + assert.equal(trailingSilenceAudit.isOmnibusCertified, false); + assert.equal(trailingSilenceAudit.windowStatus, 'partial_window'); + assert.equal(trailingSilenceAudit.windowDaysUsed, 24); + + assert.equal(gappedAudit.windowDaysUsed, 0); + + const microStepAudit = evaluateOmnibusPriceAudit({ + points: [ + { product_id: 'o1', price: 25_000_000, recorded_at: isoDaysAgo(32) }, + { product_id: 'o1', price: 25_000_000, recorded_at: isoDaysAgo(20) }, + { product_id: 'o1', price: 25_000_000, recorded_at: isoDaysAgo(10) }, + { product_id: 'o1', price: 24_990_000, recorded_at: isoDaysAgo(0) }, + ], + currentPriceVnd: 24_990_000, + claimedOriginalPriceVnd: 25_000_000, + referenceTimestampMs: ANCHOR_MS, + }); + assert.equal(microStepAudit.deltaVsPriorFloorPct, -0.04); + assert.equal(microStepAudit.claimedDiscountPct, 0.04); + assert.equal(microStepAudit.verdict, 'verified_omnibus_reduction'); + const microStepCopy = formatOmnibusAuditCopy( + microStepAudit, + omnibusTranslator(messages.en), + 'en' + ); + assert.ok(!microStepCopy.floorDeltaText.includes('-0%')); + assert.ok(microStepCopy.floorDeltaText.includes('-0.04%')); + assert.equal(microStepCopy.currentSubTone, 'good'); + console.warn('✅ Discount verdict copy suite passed'); } diff --git a/apps/web/src/lib/__tests__/sale-state.test.ts b/apps/web/src/lib/__tests__/sale-state.test.ts index f68438fe..edc17eb6 100644 --- a/apps/web/src/lib/__tests__/sale-state.test.ts +++ b/apps/web/src/lib/__tests__/sale-state.test.ts @@ -1,5 +1,8 @@ import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; +import React from 'react'; +import { renderToStaticMarkup } from 'react-dom/server'; +import { NextIntlClientProvider } from 'next-intl'; import { SALE_STATES, listingCountForSaleState, @@ -7,6 +10,21 @@ import { saleStateLabelKey, saleStateOfMaster, } from '../sale-state'; +import { + countSeasonalSaleCampaignDeals, + evaluateOmnibusPriceAudit, + matchesSeasonalSaleFilter, +} from '../omnibus-price-audit'; +import { pickClientMessages } from '../client-messages'; +import { parseEcommerceUrlOrQuery } from '../rate-domain'; +import { + AppRouterContext, + type AppRouterInstance, +} from 'next/dist/shared/lib/app-router-context.shared-runtime'; +import PriceHistorySection from '../../components/price-history/PriceHistorySection'; +import DealFinderWorkspace from '../../components/deals/DealFinderWorkspace'; +import DeepInspectWorkspace from '../../components/inspect/DeepInspectWorkspace'; +import { GLOBAL_ERROR_CATALOG } from '../../app/global-error'; function main() { console.warn('🧪 Sale state suite (DOS/Rate#1188)'); @@ -123,6 +141,849 @@ function main() { assert.ok(messages.saleState[`${key}Hint`], `${locale} ${key}Hint`); } } + + // ========================================================================= + // 90-Day Buy-vs-Wait Percentile, Plausibility/Availability & SSR (#1863) + // ========================================================================= + const DAY_MS = 86_400_000; + const ANCHOR_MS = Date.UTC(2026, 10, 22, 12, 0, 0); + const isoDaysAgo = (days: number) => + new Date(ANCHOR_MS - days * DAY_MS).toISOString(); + + // 1. <= P15 buy_now_floor: 1 dip day at 23.99M vs 9 days at 27.99M..28.99M + const buyNowAudit = evaluateOmnibusPriceAudit({ + points: [ + { product_id: 'o1', price: 28_990_000, recorded_at: isoDaysAgo(80) }, + { product_id: 'o1', price: 28_490_000, recorded_at: isoDaysAgo(70) }, + { product_id: 'o1', price: 27_990_000, recorded_at: isoDaysAgo(60) }, + { product_id: 'o1', price: 28_290_000, recorded_at: isoDaysAgo(50) }, + { product_id: 'o1', price: 27_990_000, recorded_at: isoDaysAgo(40) }, + { product_id: 'o1', price: 28_190_000, recorded_at: isoDaysAgo(30) }, + { product_id: 'o1', price: 27_990_000, recorded_at: isoDaysAgo(20) }, + { product_id: 'o1', price: 27_890_000, recorded_at: isoDaysAgo(12) }, + { product_id: 'o1', price: 27_990_000, recorded_at: isoDaysAgo(5) }, + { product_id: 'o1', price: 23_990_000, recorded_at: isoDaysAgo(0) }, + ], + currentPriceVnd: 23_990_000, + referenceTimestampMs: ANCHOR_MS, + }); + assert.equal(buyNowAudit.cycle90d.signal, 'buy_now_floor'); + assert.equal(buyNowAudit.cycle90d.percentile, 5); + assert.equal(buyNowAudit.cycle90d.low90dVnd, 23_990_000); + + // 2. Flat 90d price -> P50 fair_market (never falsely buy_now_floor or wait) + const flat90dAudit = evaluateOmnibusPriceAudit({ + points: [0, 7, 14, 21, 28, 35].map((d) => ({ + product_id: 'o1', + price: 25_000_000, + recorded_at: isoDaysAgo(d), + })), + currentPriceVnd: 25_000_000, + referenceTimestampMs: ANCHOR_MS, + }); + assert.equal(flat90dAudit.cycle90d.signal, 'fair_market'); + assert.equal(flat90dAudit.cycle90d.percentile, 50); + + // 3. > P70 above_recent_floor: exact VND gap above 90d low + const waitAudit = evaluateOmnibusPriceAudit({ + points: [ + { product_id: 'o1', price: 24_000_000, recorded_at: isoDaysAgo(45) }, + { product_id: 'o1', price: 24_500_000, recorded_at: isoDaysAgo(36) }, + { product_id: 'o1', price: 25_000_000, recorded_at: isoDaysAgo(27) }, + { product_id: 'o1', price: 25_500_000, recorded_at: isoDaysAgo(18) }, + { product_id: 'o1', price: 26_000_000, recorded_at: isoDaysAgo(9) }, + { product_id: 'o1', price: 27_500_000, recorded_at: isoDaysAgo(0) }, + ], + currentPriceVnd: 27_500_000, + referenceTimestampMs: ANCHOR_MS, + }); + assert.equal(waitAudit.cycle90d.signal, 'above_recent_floor'); + assert.ok((waitAudit.cycle90d.percentile ?? 0) > 70); + assert.equal(waitAudit.cycle90d.aboveFloorVnd, 3_500_000); + + // 4. Sufficiency guards: < 5 days, < 14d span, and same-day burst crawls + const fourDaysOnly = evaluateOmnibusPriceAudit({ + points: [0, 7, 14, 30].map((d) => ({ + product_id: 'o1', + price: 25_000_000 + d * 100_000, + recorded_at: isoDaysAgo(d), + })), + currentPriceVnd: 25_000_000, + referenceTimestampMs: ANCHOR_MS, + }); + assert.equal(fourDaysOnly.cycle90d.signal, 'insufficient_data'); + assert.equal(fourDaysOnly.cycle90d.observedPointDays, 4); + + const burstSameDay = evaluateOmnibusPriceAudit({ + points: [ + ...Array.from({ length: 15 }, (_, idx) => ({ + product_id: 'o1', + price: 25_000_000, + recorded_at: new Date(ANCHOR_MS - idx * 60_000).toISOString(), + })), + { product_id: 'o1', price: 26_000_000, recorded_at: isoDaysAgo(10) }, + { product_id: 'o1', price: 26_500_000, recorded_at: isoDaysAgo(20) }, + ], + currentPriceVnd: 25_000_000, + referenceTimestampMs: ANCHOR_MS, + }); + assert.equal(burstSameDay.cycle90d.signal, 'insufficient_data'); + assert.equal(burstSameDay.cycle90d.observedPointDays, 3); + + // 5. Bait-price, unavailable (out_of_stock / discontinued), and live_listing exclusions + const baitAndSoldOutAudit = evaluateOmnibusPriceAudit({ + points: [ + // Bait offer at 1.25M (< 40% of 26M..27M median) + ...[0, 7, 14, 21, 28, 35].map((d) => ({ + product_id: 'offer-bait', + price: 1_250_000, + recorded_at: isoDaysAgo(d), + })), + // Out-of-stock offer at 18M + ...[0, 7, 14, 21, 28, 35].map((d) => ({ + product_id: 'offer-soldout', + price: 18_000_000, + recorded_at: isoDaysAgo(d), + })), + // Valid in-stock peers at 26M..27M + ...[0, 7, 14, 21, 28, 35].map((d) => ({ + product_id: 'offer-good-a', + price: 26_000_000 + (d > 0 ? 500_000 : 0), + recorded_at: isoDaysAgo(d), + })), + ...[0, 7, 14, 21, 28, 35].map((d) => ({ + product_id: 'offer-good-b', + price: 27_000_000, + recorded_at: isoDaysAgo(d), + })), + // Synthetic fallback row must be ignored + { + product_id: 'offer-good-a', + price: 19_000_000, + recorded_at: isoDaysAgo(15), + source: 'live_listing', + }, + ], + currentPriceVnd: 26_000_000, + mode: 'market', + referenceOffers: [ + { id: 'offer-bait', price_current: 1_250_000, availability: 'in_stock' }, + { + id: 'offer-soldout', + price_current: 18_000_000, + availability: 'out_of_stock', + }, + { + id: 'offer-good-a', + price_current: 26_000_000, + availability: 'in_stock', + }, + { + id: 'offer-good-b', + price_current: 27_000_000, + availability: 'in_stock', + }, + ], + referenceTimestampMs: ANCHOR_MS, + }); + assert.equal(baitAndSoldOutAudit.priorFloorPriceVnd, 26_500_000); + assert.equal(baitAndSoldOutAudit.cycle90d.low90dVnd, 26_000_000); + assert.equal(baitAndSoldOutAudit.cycle90d.signal, 'buy_now_floor'); + + // Out-of-stock current product suppresses Buy-Now signal + const soldOutProductCycle = evaluateOmnibusPriceAudit({ + points: [0, 7, 14, 21, 28, 35].map((d) => ({ + product_id: 'offer-good-a', + price: 26_000_000, + recorded_at: isoDaysAgo(d), + })), + currentPriceVnd: 26_000_000, + currentInStockPriceVnd: null, + referenceTimestampMs: ANCHOR_MS, + }); + assert.equal(soldOutProductCycle.cycle90d.signal, 'insufficient_data'); + + // Micro-spread (< 1%) stays fair_market rather than Wait/Buy-Now on +1,000 VND + const microSpread90d = evaluateOmnibusPriceAudit({ + points: [7, 14, 21, 28, 35].map((d) => ({ + product_id: 'offer-good-a', + price: 25_000_000, + recorded_at: isoDaysAgo(d), + })), + currentPriceVnd: 25_001_000, + referenceTimestampMs: ANCHOR_MS, + }); + assert.equal(microSpread90d.cycle90d.signal, 'fair_market'); + + // Live price drop below historical low clamps low90dVnd to live price + const liveDropBelowHist = evaluateOmnibusPriceAudit({ + points: [2, 9, 16, 23, 30].map((d) => ({ + product_id: 'offer-good-a', + price: 26_000_000 + d * 50_000, + recorded_at: isoDaysAgo(d), + })), + currentPriceVnd: 24_500_000, + referenceTimestampMs: ANCHOR_MS, + }); + assert.equal(liveDropBelowHist.cycle90d.low90dVnd, 24_500_000); + assert.equal(liveDropBelowHist.cycle90d.signal, 'buy_now_floor'); + + // 6. Seasonal campaign filter helper & SSR rendering across vi, en, cs + const mockGenuineSig = { + verdict: 'genuine_deal' as const, + savingsPct: 12.5, + fakeMarkupPct: 0, + spreadPct: 14, + genuineDeal: { + id: 'g1', + verdict: 'genuine_all_time_low' as const, + verdictBadgeVi: 'Đáy giá', + productSlug: 'phone-a', + productName: 'Phone A', + brand: 'Apple', + categorySlug: 'smartphones' as const, + productHref: '/smartphones/phone-a', + imageUrl: null, + platform: 'shopee', + merchantId: 'm1', + merchantName: 'Shop A', + isOfficialMall: true, + merchantRiskScore: 4, + offerUrl: 'https://shopee.vn/a', + priceCurrent: 24_000_000, + priceOriginal: null, + marketMedianPrice: 27_400_000, + marketMinPrice: 24_000_000, + marketMaxPrice: 28_000_000, + savingsVsMedianVnd: 3_400_000, + savingsVsMedianPct: 12.5, + marketOfferCount: 3, + claimedDiscountPct: 0, + fakeMarkupPct: 0, + jreviewsScore10: 8.8, + explanationVi: 'Tốt', + }, + fakeSaleTrap: null, + priceSpread: null, + }; + const mockTrapSig = { + verdict: 'fake_sale_trap' as const, + savingsPct: 0, + fakeMarkupPct: 26.4, + spreadPct: 0, + genuineDeal: null, + fakeSaleTrap: { + ...mockGenuineSig.genuineDeal, + id: 't1', + verdict: 'inflated_fake_sale' as const, + productSlug: 'phone-b', + productName: 'Phone B', + priceCurrent: 27_400_000, + priceOriginal: 34_630_000, + savingsVsMedianVnd: 0, + savingsVsMedianPct: 0, + claimedDiscountPct: 20.9, + fakeMarkupPct: 26.4, + }, + priceSpread: null, + }; + assert.equal( + matchesSeasonalSaleFilter(mockGenuineSig, 'genuine_sale_drops'), + true + ); + assert.equal( + matchesSeasonalSaleFilter(mockGenuineSig, 'inflated_presale_warnings'), + false + ); + assert.equal( + matchesSeasonalSaleFilter(mockTrapSig, 'inflated_presale_warnings'), + true + ); + assert.equal( + matchesSeasonalSaleFilter( + { + ...mockTrapSig, + fakeSaleTrap: { + ...mockTrapSig.fakeSaleTrap, + priceOriginal: 20_000_000, + }, + }, + 'inflated_presale_warnings' + ), + false + ); + assert.equal( + matchesSeasonalSaleFilter( + { + ...mockGenuineSig, + genuineDeal: { + ...mockGenuineSig.genuineDeal, + savingsVsMedianVnd: 0, + }, + }, + 'genuine_sale_drops' + ), + false + ); + assert.deepEqual( + countSeasonalSaleCampaignDeals( + [{ slug: 'phone-a' }, { slug: 'phone-b' }, { slug: 'phone-c' }], + (slug) => + slug === 'phone-a' + ? mockGenuineSig + : slug === 'phone-b' + ? mockTrapSig + : null + ), + { genuineSaleCount: 1, inflatedWarningCount: 1 } + ); + + const IntlProvider = NextIntlClientProvider as React.ComponentType<{ + locale: string; + messages: Record; + timeZone: string; + children?: React.ReactNode; + }>; + + for (const locale of ['vi', 'en', 'cs'] as const) { + const rawCatalog = JSON.parse( + readFileSync( + new URL(`../../../locales/${locale}.json`, import.meta.url), + 'utf8' + ) + ) as Record; + assert.deepEqual( + GLOBAL_ERROR_CATALOG[locale], + (rawCatalog.errors as { global: unknown }).global, + `${locale}: GLOBAL_ERROR_CATALOG matches locales/${locale}.json errors.global` + ); + + const historyHtml = renderToStaticMarkup( + React.createElement( + IntlProvider, + { + locale, + messages: pickClientMessages(rawCatalog, 'productDetail'), + timeZone: 'Asia/Ho_Chi_Minh', + }, + React.createElement(PriceHistorySection, { + productName: 'iPhone 16 Pro Max', + history: { + points: [0, 7, 14, 21, 28, 35].map((d, idx) => ({ + id: idx + 1, + product_id: 'offer-1', + merchant_name: 'Apple Flagship Store', + platform: 'shopee', + is_official: true, + price: d === 0 ? 27_190_000 : 27_490_000, + price_original: 34_990_000, + recorded_at: isoDaysAgo(d), + source: 'crawler', + })), + byOffer: { + 'offer-1': { + product_id: 'offer-1', + merchant_name: 'Apple Flagship Store', + platform: 'shopee', + price_current: 27_190_000, + price_original: 34_990_000, + claimed_discount_pct: 22.3, + real_discount_vs_median_pct: 1.1, + historical_min_price: 27_190_000, + historical_max_price: 27_490_000, + historical_median_price: 27_490_000, + observation_count: 6, + verdict: 'genuine_deal', + badge_label: 'Deal', + explanation: 'Deal', + }, + }, + lowestEverPrice: 27_190_000, + lowestEverDate: isoDaysAgo(0), + lowestEverMerchant: 'Apple Flagship Store', + highestEverPrice: 27_490_000, + currentMinPrice: 27_190_000, + fakeDiscountCount: 0, + genuineDealCount: 1, + }, + }) + ) + ); + assert.ok( + historyHtml.includes('data-testid="omnibus-price-audit-card"'), + `${locale}: PriceHistorySection renders omnibus card` + ); + assert.ok( + historyHtml.includes('data-testid="omnibus-cycle-signal"'), + `${locale}: PriceHistorySection renders 90d cycle signal` + ); + + const dealsHtml = renderToStaticMarkup( + React.createElement( + IntlProvider, + { + locale, + messages: pickClientMessages(rawCatalog, 'deals'), + timeZone: 'Asia/Ho_Chi_Minh', + }, + React.createElement(DealFinderWorkspace, { + products: [ + { + id: 'p1', + slug: 'phone-a', + name: 'Phone A', + brand: 'Apple', + model: 'Phone A', + model_key: 'apple_phone_a', + min_price: 24_000_000, + max_price: 28_000_000, + merchant_count: 3, + user_rating_weighted: 4.7, + authentic_review_count: 10, + total_reviews: 10, + status: 'published', + metadata: { category_slug: 'smartphones' }, + } as never, + ], + dealRadar: { + generatedAt: isoDaysAgo(0), + categoryFilter: 'all', + totalClustersAnalyzed: 1, + totalOffersAnalyzed: 3, + totalMerchantsAnalyzed: 3, + genuineDeals: [mockGenuineSig.genuineDeal], + fakeSaleTraps: [mockTrapSig.fakeSaleTrap], + priceSpreadLeaders: [], + }, + }) + ) + ); + assert.ok( + dealsHtml.includes('data-testid="deals-seasonal-campaign-filter"'), + `${locale}: DealFinderWorkspace renders seasonal campaign filter` + ); + + const mockRouter: AppRouterInstance = { + back: () => {}, + forward: () => {}, + refresh: () => {}, + push: () => {}, + replace: () => {}, + prefetch: () => {}, + bfcacheId: 'test', + }; + + const inspectValidHtml = renderToStaticMarkup( + React.createElement( + AppRouterContext.Provider, + { value: mockRouter }, + React.createElement( + IntlProvider, + { + locale, + messages: pickClientMessages(rawCatalog, 'inspect'), + timeZone: 'Asia/Ho_Chi_Minh', + }, + React.createElement(DeepInspectWorkspace, { + initialQuery: 'https://shopee.vn/item-1', + initialInspection: { + query: 'https://shopee.vn/item-1', + matchedType: 'product_listing', + parsedUrl: parseEcommerceUrlOrQuery('https://shopee.vn/item-1'), + masterProduct: { + id: 'mp-1', + slug: 'iphone-16-pro-max-256gb', + name: 'iPhone 16 Pro Max 256GB', + brand: 'Apple', + model: 'iPhone 16 Pro Max', + model_key: 'apple_iphone_16_pro_max_256gb', + min_price: 27_190_000, + max_price: 28_990_000, + merchant_count: 2, + status: 'published', + } as never, + matchedOffer: { + id: 'offer-1', + platform: 'shopee', + title: 'iPhone 16 Pro Max 256GB VN/A', + price_current: 27_190_000, + price_original: 34_990_000, + stock: 5, + rating_star: 4.9, + rating_count: 20, + url: 'https://shopee.vn/item-1', + availability: 'in_stock', + merchant: { + id: 'm-1', + name: 'Apple Flagship Store', + platform: 'shopee', + is_official: true, + rating_star: 4.9, + follower_count: 1000, + location: 'VN', + risk_score: 4, + dosafe_risk_score: 4, + review_risk_score: 4, + review_risk_breakdown: null, + }, + }, + allOffers: [], + discountAnalysis: null, + priceHistory: { + points: [0, 7, 14, 21, 28, 35].map((d, idx) => ({ + id: idx + 1, + product_id: 'offer-1', + merchant_name: 'Apple Flagship Store', + platform: 'shopee', + is_official: true, + price: d === 0 ? 27_190_000 : 27_490_000, + price_original: 34_990_000, + recorded_at: isoDaysAgo(d), + source: 'crawler', + })), + byOffer: {}, + lowestEverPrice: 27_190_000, + lowestEverDate: isoDaysAgo(0), + lowestEverMerchant: 'Apple Flagship Store', + highestEverPrice: 27_490_000, + currentMinPrice: 27_190_000, + fakeDiscountCount: 0, + genuineDealCount: 1, + }, + reviewSummary: null, + merchantProfile: null, + suggestions: [], + }, + }) + ) + ) + ); + assert.ok( + inspectValidHtml.includes('data-testid="inspect-omnibus-audit-card"'), + `${locale}: DeepInspectWorkspace renders Omnibus audit card on valid in-stock listing` + ); + + const inspectBaitHtml = renderToStaticMarkup( + React.createElement( + AppRouterContext.Provider, + { value: mockRouter }, + React.createElement( + IntlProvider, + { + locale, + messages: pickClientMessages(rawCatalog, 'inspect'), + timeZone: 'Asia/Ho_Chi_Minh', + }, + React.createElement(DeepInspectWorkspace, { + initialQuery: 'https://shopee.vn/bait', + initialInspection: { + query: 'https://shopee.vn/bait', + matchedType: 'product_listing', + parsedUrl: parseEcommerceUrlOrQuery('https://shopee.vn/bait'), + masterProduct: { + id: 'mp-1', + slug: 'iphone-16-pro-max-256gb', + name: 'iPhone 16 Pro Max 256GB', + brand: 'Apple', + model: 'iPhone 16 Pro Max', + model_key: 'apple_iphone_16_pro_max_256gb', + min_price: 27_190_000, + max_price: 28_990_000, + merchant_count: 2, + status: 'published', + } as never, + matchedOffer: { + id: 'offer-bait', + platform: 'shopee', + title: 'Ốp lưng iPhone 16', + price_current: 50_000, + price_original: 25_000_000, + stock: 5, + rating_star: 4.9, + rating_count: 20, + url: 'https://shopee.vn/bait', + availability: 'in_stock', + merchant: { + id: 'm-bait', + name: 'Bait Shop', + platform: 'shopee', + is_official: false, + rating_star: 4.0, + follower_count: 10, + location: 'VN', + risk_score: 60, + dosafe_risk_score: 60, + review_risk_score: 60, + review_risk_breakdown: null, + }, + }, + allOffers: [], + discountAnalysis: null, + priceHistory: { + points: [0, 10, 20, 32].map((d, idx) => ({ + id: idx + 1, + product_id: 'offer-1', + merchant_name: 'Shop', + platform: 'shopee', + is_official: true, + price: 27_190_000, + price_original: null, + recorded_at: isoDaysAgo(d), + source: 'crawler', + })), + byOffer: {}, + lowestEverPrice: 27_190_000, + lowestEverDate: isoDaysAgo(0), + lowestEverMerchant: 'Shop', + highestEverPrice: 27_190_000, + currentMinPrice: 27_190_000, + fakeDiscountCount: 0, + genuineDealCount: 0, + }, + reviewSummary: null, + merchantProfile: null, + suggestions: [], + }, + }) + ) + ) + ); + assert.equal( + inspectBaitHtml.includes('data-testid="inspect-omnibus-audit-card"'), + false, + `${locale}: DeepInspectWorkspace suppresses Omnibus audit card on bait listing` + ); + + // Overpriced listing with 0 own history points naast cheaper peer: + // - Never falsely gets green "buy now" (gets Wait signal for 31.99M vs 26.99M) + // - Never falsely accuses 0-day shop of 30d EU Omnibus violation + // - Marks Vietnamese shop name with lang="vi" on en/cs pages (WCAG 3.1.2) + const inspectOverpricedNewShopHtml = renderToStaticMarkup( + React.createElement( + AppRouterContext.Provider, + { value: mockRouter }, + React.createElement( + IntlProvider, + { + locale, + messages: pickClientMessages(rawCatalog, 'inspect'), + timeZone: 'Asia/Ho_Chi_Minh', + }, + React.createElement(DeepInspectWorkspace, { + initialQuery: 'https://shopee.vn/new-shop', + initialInspection: { + query: 'https://shopee.vn/new-shop', + matchedType: 'product_listing', + parsedUrl: parseEcommerceUrlOrQuery('https://shopee.vn/new-shop'), + masterProduct: { + id: 'mp-1', + slug: 'iphone-16-pro-max-256gb', + name: 'iPhone 16 Pro Max 256GB', + brand: 'Apple', + model: 'iPhone 16 Pro Max', + model_key: 'apple_iphone_16_pro_max_256gb', + min_price: 26_990_000, + max_price: 31_990_000, + merchant_count: 2, + status: 'published', + } as never, + matchedOffer: { + id: 'offer-new-expensive', + platform: 'shopee', + title: 'iPhone 16 Pro Max 256GB VN/A', + price_current: 31_990_000, + price_original: 34_990_000, + stock: 3, + rating_star: 4.8, + rating_count: 5, + url: 'https://shopee.vn/new-shop', + availability: 'in_stock', + merchant: { + id: 'm-vn', + name: 'Cửa Hàng Điện Thoại Hà Nội', + platform: 'shopee', + is_official: false, + rating_star: 4.8, + follower_count: 500, + location: 'VN', + risk_score: 12, + dosafe_risk_score: 12, + review_risk_score: 12, + review_risk_breakdown: null, + }, + }, + allOffers: [ + { + id: 'offer-cheap-peer', + platform: 'tiki', + title: 'iPhone 16 Pro Max 256GB', + price_current: 26_990_000, + price_original: null, + stock: 10, + rating_star: 4.9, + rating_count: 40, + url: 'https://tiki.vn/peer', + availability: 'in_stock', + merchant: { + id: 'm-peer', + name: 'Tiki Trading', + platform: 'tiki', + is_official: true, + rating_star: 4.9, + follower_count: 50000, + location: 'VN', + risk_score: 2, + dosafe_risk_score: 2, + review_risk_score: 2, + review_risk_breakdown: null, + }, + }, + { + id: 'offer-new-expensive', + platform: 'shopee', + title: 'iPhone 16 Pro Max 256GB VN/A', + price_current: 31_990_000, + price_original: 34_990_000, + stock: 3, + rating_star: 4.8, + rating_count: 5, + url: 'https://shopee.vn/new-shop', + availability: 'in_stock', + merchant: { + id: 'm-vn', + name: 'Cửa Hàng Điện Thoại Hà Nội', + platform: 'shopee', + is_official: false, + rating_star: 4.8, + follower_count: 500, + location: 'VN', + risk_score: 12, + dosafe_risk_score: 12, + review_risk_score: 12, + review_risk_breakdown: null, + }, + }, + ], + discountAnalysis: null, + priceHistory: { + points: [0, 7, 14, 21, 28, 35].map((d, idx) => ({ + id: idx + 1, + product_id: 'offer-cheap-peer', + merchant_name: 'Tiki Trading', + platform: 'tiki', + is_official: true, + price: 26_990_000 + (d > 0 ? 500_000 : 0), + price_original: null, + recorded_at: isoDaysAgo(d), + source: 'crawler', + })), + byOffer: {}, + lowestEverPrice: 26_990_000, + lowestEverDate: isoDaysAgo(0), + lowestEverMerchant: 'Tiki Trading', + highestEverPrice: 27_490_000, + currentMinPrice: 26_990_000, + fakeDiscountCount: 0, + genuineDealCount: 1, + }, + reviewSummary: null, + merchantProfile: null, + suggestions: [], + }, + }) + ) + ) + ); + const pvDict = (rawCatalog as { priceVerdict: Record }) + .priceVerdict; + assert.ok( + inspectOverpricedNewShopHtml.includes(pvDict.oPend!) && + inspectOverpricedNewShopHtml.includes(pvDict.oNeed!) && + !inspectOverpricedNewShopHtml.includes(pvDict.oOk!), + `${locale}: 0-history matchedOffer shows insufficient history, not competitor 30d floor` + ); + assert.ok( + inspectOverpricedNewShopHtml.includes( + 'data-testid="inspect-omnibus-cycle-signal" class="fw-bold mb-1 text-danger"' + ), + `${locale}: overpriced 31.99M listing renders danger Wait signal, never green Buy-Now` + ); + if (locale !== 'vi') { + const cardStart = inspectOverpricedNewShopHtml.indexOf( + 'data-testid="inspect-omnibus-audit-card"' + ); + const badgeStart = inspectOverpricedNewShopHtml.indexOf( + 'data-testid="inspect-omnibus-window-badge"', + cardStart + ); + const omnibusScopeHeaderHtml = inspectOverpricedNewShopHtml.slice( + cardStart, + badgeStart + ); + assert.ok( + cardStart >= 0 && + badgeStart > cardStart && + omnibusScopeHeaderHtml.includes( + 'Cửa Hàng Điện Thoại Hà Nội' + ), + `${locale}: Vietnamese seller name inside omnibusScopeListing carries lang="vi"` + ); + } + } + + // Expired carry-in offer in market mode (48.5d ago > 18d before 30d boundary) + // never leaks into the 30-day floor via another offer's aggregate timestamp. + const expiredCarryMarket = evaluateOmnibusPriceAudit({ + points: [ + { + product_id: 'offer-expired', + price: 20_000_000, + recorded_at: isoDaysAgo(48.5), + }, + { + product_id: 'offer-active', + price: 30_000_000, + recorded_at: isoDaysAgo(31), + }, + { + product_id: 'offer-active', + price: 30_000_000, + recorded_at: isoDaysAgo(20), + }, + { + product_id: 'offer-active', + price: 30_000_000, + recorded_at: isoDaysAgo(10), + }, + { + product_id: 'offer-active', + price: 28_000_000, + recorded_at: isoDaysAgo(0), + }, + ], + currentPriceVnd: 28_000_000, + claimedOriginalPriceVnd: 30_000_000, + mode: 'market', + referenceTimestampMs: ANCHOR_MS, + }); + assert.equal(expiredCarryMarket.priorFloorPriceVnd, 30_000_000); + assert.equal(expiredCarryMarket.verdict, 'verified_omnibus_reduction'); + + // Carry-in observation outside the 30-day window does not count toward the + // 3-day in-window coverage minimum. + const twoInWindowPlusCarry = evaluateOmnibusPriceAudit({ + points: [ + { product_id: 'o1', price: 25_000_000, recorded_at: isoDaysAgo(32) }, + { product_id: 'o1', price: 26_000_000, recorded_at: isoDaysAgo(15) }, + { product_id: 'o1', price: 25_500_000, recorded_at: isoDaysAgo(0) }, + ], + currentPriceVnd: 25_500_000, + claimedOriginalPriceVnd: 29_000_000, + referenceTimestampMs: ANCHOR_MS, + }); + assert.equal(twoInWindowPlusCarry.isOmnibusCertified, false); + assert.equal(twoInWindowPlusCarry.windowStatus, 'blackout_gap'); + console.warn('✅ Sale state suite passed'); } diff --git a/apps/web/src/lib/omnibus-price-audit.ts b/apps/web/src/lib/omnibus-price-audit.ts new file mode 100644 index 00000000..fba4d677 --- /dev/null +++ b/apps/web/src/lib/omnibus-price-audit.ts @@ -0,0 +1,1270 @@ +/** + * EU Omnibus 30-Day Prior Price-Floor Audit & 90-Day Cycle Buy-vs-Wait Engine + * (Package 8A Feature F1, DOS/Rate#1863). + * + * Inspired by Hlidac shopu (EU Directive 2019/2161 Article 6a) and Keepa/Prisjakt + * 90-day price-cycle percentiles. Pure, deterministic, client-safe TypeScript: + * zero database DDL, zero server-only imports, and strict window honesty. + */ +import { + IMPLAUSIBLY_LOW_RATIO, + MAX_VALID_VND_PRICE, + MINIMUM_EARBUDS_PRICE_FLOOR_VND, + implausiblyLowIndexes, + implausiblyLowOfferIds, + isImplausiblyLowPrice, + isOfferImplausiblyLowAgainstInStock, + normalizeOfferId, + plausibleOffers, +} from '@repo/shared-data/rules'; +import type { RadarSignal } from '@/lib/deal-radar'; +import { formatPlainNumber, formatPriceVnd } from '@/lib/locale-format'; +import { + isOfferUnavailable, + type OfferAvailability, +} from '@/lib/product-market-stats'; + +const DAY_MS = 86_400_000; +const CONTROL_CHAR_RE = /\p{Cc}+/gu; + +/** Full days required before certifying EU Omnibus Article 6a 30-day prior floor. */ +export const OMNIBUS_WINDOW_DAYS = 30; +/** Minimum distinct observed day buckets required to certify a 30-day floor. */ +export const MIN_OMNIBUS_OBSERVATION_DAYS = 3; +/** Maximum allowed gap (in days) inside the 30-day window before withholding certification. */ +export const MAX_OMNIBUS_BLACKOUT_GAP_DAYS = 18; +/** Maximum duration (in days) of a new trailing price change treated as the current sale event. */ +export const MAX_CURRENT_EVENT_TAIL_DAYS = 7; + +/** Reference lookback window for Buy-Now vs Wait percentile analysis. */ +export const CYCLE_90D_WINDOW_DAYS = 90; +/** Minimum distinct observed days required to emit a 90-day percentile call. */ +export const MIN_CYCLE_90D_POINTS = 5; +/** Minimum observed span (in days) required to emit a 90-day percentile call. */ +export const MIN_CYCLE_90D_SPAN_DAYS = 14; +/** <= P15 marks the 90-day floor zone ("Buy now"). */ +export const CYCLE_BUY_NOW_MAX_PERCENTILE = 15; +/** P16..P70 marks stable fair-market pricing; > P70 marks elevated ("Wait for sale"). */ +export const CYCLE_FAIR_MARKET_MAX_PERCENTILE = 70; +/** Minimum relative 90d price spread (1%) required before calling Buy-Now or Wait. */ +export const MIN_CYCLE_90D_RELATIVE_SPREAD = 0.01; + +export type OmnibusWindowStatus = + | 'omnibus_30d_certified' + | 'partial_window' + | 'blackout_gap' + | 'insufficient_history'; + +export type OmnibusAuditVerdict = + | 'fake_strikethrough_above_floor' + | 'exaggerated_strikethrough' + | 'verified_omnibus_reduction' + | 'below_30d_floor' + | 'at_or_above_30d_floor' + | 'unverified_window'; + +export type Cycle90dSignalKind = + 'buy_now_floor' | 'fair_market' | 'above_recent_floor' | 'insufficient_data'; + +export type SeasonalSaleFilterMode = + 'all' | 'genuine_sale_drops' | 'inflated_presale_warnings'; + +export interface OmnibusAuditPointInput { + readonly product_id?: string | null; + readonly price: unknown; + readonly price_original?: unknown; + readonly recorded_at: unknown; + readonly source?: string | null; + readonly availability?: OfferAvailability | null; + readonly implausiblyLow?: boolean | null; +} + +export interface OmnibusReferenceOfferInput { + readonly id?: string | null; + readonly price_current: number; + readonly availability?: OfferAvailability | null; + readonly implausiblyLow?: boolean | null; +} + +export interface EvaluateOmnibusPriceAuditParams { + readonly points: readonly OmnibusAuditPointInput[] | null | undefined; + /** Current selling price of the listing or best verified offer. */ + readonly currentPriceVnd: unknown; + /** Seller-claimed strikethrough original/list price, if any. */ + readonly claimedOriginalPriceVnd?: unknown; + /** + * Verified in-stock non-bait price used for the 90-day Buy-Now vs Wait call. + * Defaults to `currentPriceVnd` unless `currentOfferUnavailable` is true; + * pass `null` explicitly when no verified in-stock offer exists. + */ + readonly currentInStockPriceVnd?: unknown; + /** `'offer'` evaluates a single listing series; `'market'` computes daily floor across offers. */ + readonly mode?: 'offer' | 'market'; + readonly currentOfferUnavailable?: boolean; + readonly currentOfferImplausiblyLow?: boolean; + readonly referenceOffers?: readonly OmnibusReferenceOfferInput[] | null; + readonly unavailableOfferIds?: ReadonlySet | null; + readonly implausibleOfferIds?: ReadonlySet | null; + readonly minValidPriceVnd?: number; + /** Optional deterministic anchor timestamp in ms; defaults to latest valid point timestamp. */ + readonly referenceTimestampMs?: number | null; +} + +export interface Cycle90dEvaluation { + readonly signal: Cycle90dSignalKind; + readonly percentile: number | null; + readonly topPercentileDisplay: number | null; + readonly low90dVnd: number | null; + readonly high90dVnd: number | null; + readonly median90dVnd: number | null; + readonly aboveFloorVnd: number | null; + readonly aboveFloorPct: number | null; + readonly observedPointDays: number; + readonly observedSpanDays90d: number; +} + +export interface OmnibusPriceAuditResult { + readonly currentPriceVnd: number | null; + readonly claimedOriginalPriceVnd: number | null; + readonly claimedDiscountVnd: number | null; + readonly claimedDiscountPct: number | null; + readonly priorFloorPriceVnd: number | null; + readonly observedSpanDays: number; + readonly windowDaysUsed: number; + readonly isOmnibusCertified: boolean; + readonly hasBlackoutGap: boolean; + readonly windowStatus: OmnibusWindowStatus; + readonly verdict: OmnibusAuditVerdict; + readonly deltaVsPriorFloorVnd: number | null; + readonly deltaVsPriorFloorPct: number | null; + readonly claimedVsPriorFloorMarkupVnd: number | null; + readonly claimedVsPriorFloorMarkupPct: number | null; + readonly validObservationCount: number; + readonly cycle90d: Cycle90dEvaluation; +} + +export type OmnibusVerdictMessageKey = + | 'oTitle' + | 'oOk' + | 'oPart' + | 'oGap' + | 'oPend' + | 'oFlr' + | 'oCur' + | 'oClaim' + | 'oNoOrig' + | 'oMarkup' + | 'oAlign' + | 'oDrop' + | 'oFake' + | 'oUp' + | 'oFlat' + | 'oNeed' + | 'oNoteP' + | 'oNoteG' + | 'oCyc' + | 'oBuy' + | 'oFair' + | 'oWait' + | 'oRng' + | 'oCycP' + | 'oCycN'; + +export type OmnibusVerdictTranslator = ( + key: OmnibusVerdictMessageKey, + values?: Record +) => string; + +export interface FormattedOmnibusAuditCopy { + readonly cardTitle: string; + readonly statusBadgeText: string; + readonly statusBadgeTone: 'good' | 'warn' | 'bad' | 'neutral'; + readonly colCurrentTitle: string; + readonly currentPriceText: string; + readonly claimedBadgeText: string | null; + readonly currentSubText: string; + readonly currentSubTone: 'bad' | 'good' | 'neutral'; + readonly colFloorTitle: string; + readonly floorPriceText: string; + readonly floorDeltaText: string; + readonly floorDeltaTone: 'good' | 'bad' | 'neutral'; + readonly floorDisclaimerText: string | null; + readonly colCycleTitle: string; + readonly cycleValueText: string; + readonly cycleValueTone: 'good' | 'bad' | 'neutral'; + readonly cycleSubText: string; +} + +function parseStrictFiniteNumber(raw: unknown): number | null { + if (typeof raw === 'number') { + return Number.isFinite(raw) ? raw : null; + } + if (typeof raw === 'string') { + const cleaned = raw.replace(CONTROL_CHAR_RE, '').trim(); + if (!cleaned || cleaned.length > 32 || /^[+-]?0[xbo]/i.test(cleaned)) { + return null; + } + const num = Number(cleaned); + return Number.isFinite(num) ? num : null; + } + return null; +} + +export function sanitizeOmnibusPriceVnd( + raw: unknown, + minFloorVnd = MINIMUM_EARBUDS_PRICE_FLOOR_VND +): number | null { + const parsed = parseStrictFiniteNumber(raw); + if (parsed == null || parsed <= 0 || parsed > MAX_VALID_VND_PRICE) { + return null; + } + const rounded = Math.round(parsed); + const safeFloor = + Number.isFinite(minFloorVnd) && minFloorVnd > 0 + ? Math.round(minFloorVnd) + : MINIMUM_EARBUDS_PRICE_FLOOR_VND; + if (rounded < safeFloor || rounded > MAX_VALID_VND_PRICE) { + return null; + } + return rounded; +} + +function parseRecordedAtMs(raw: unknown): number | null { + if (typeof raw === 'number') { + return Number.isFinite(raw) && raw > 0 ? Math.round(raw) : null; + } + if (raw instanceof Date) { + const ms = raw.getTime(); + return Number.isFinite(ms) && ms > 0 ? ms : null; + } + if (typeof raw === 'string') { + const cleaned = raw.replace(CONTROL_CHAR_RE, '').trim(); + if (!cleaned || cleaned.length > 64) return null; + const ms = Date.parse(cleaned); + return Number.isFinite(ms) && ms > 0 ? ms : null; + } + return null; +} + +function roundDisplayPct(value: number): number { + if (!Number.isFinite(value) || value === 0) return 0; + const abs = Math.abs(value); + if (abs < 0.1) { + const rounded2 = Math.round(abs * 100) / 100; + const nonZero = Math.max(0.01, rounded2); + return value < 0 ? -nonZero : nonZero; + } + const rounded1 = Math.round(value * 10) / 10; + return Object.is(rounded1, -0) ? 0 : rounded1; +} + +function computeSortedMedian(sortedAsc: readonly number[]): number | null { + if (sortedAsc.length === 0) return null; + const mid = Math.floor(sortedAsc.length / 2); + if (sortedAsc.length % 2 === 1) { + return sortedAsc[mid] ?? null; + } + return Math.round(((sortedAsc[mid - 1] ?? 0) + (sortedAsc[mid] ?? 0)) / 2); +} + +interface CleanHistoryPoint { + readonly offerKey: string; + readonly priceVnd: number; + readonly recordedMs: number; +} + +interface SeriesPoint { + readonly priceVnd: number; + readonly recordedMs: number; +} + +function buildOfferExclusionSets(params: { + readonly referenceOffers?: readonly OmnibusReferenceOfferInput[] | null; + readonly unavailableOfferIds?: ReadonlySet | null; + readonly implausibleOfferIds?: ReadonlySet | null; + readonly minFloorVnd: number; +}): { + excludedIds: Set; + inStockPlausibleOffers: { id: string; price_current: number }[]; +} { + const excludedIds = new Set(); + const markExcluded = (raw: string | null | undefined) => { + if (!raw) return; + const trimmed = raw.trim(); + if (trimmed) excludedIds.add(trimmed); + const clean = normalizeOfferId(trimmed); + if (clean) excludedIds.add(clean); + }; + for (const set of [params.unavailableOfferIds, params.implausibleOfferIds]) { + if (!set) continue; + for (const id of set) markExcluded(id); + } + + const safeRefOffers = Array.isArray(params.referenceOffers) + ? params.referenceOffers.filter((o): o is OmnibusReferenceOfferInput => + Boolean(o && typeof o === 'object' && !Array.isArray(o)) + ) + : []; + + const inStockSized: { id: string; price_current: number }[] = []; + const pricedAll: { rawId: string; id: string; price_current: number }[] = []; + for (const off of safeRefOffers) { + const rawId = typeof off.id === 'string' ? off.id.trim() : ''; + const id = normalizeOfferId(rawId) || rawId; + const price = sanitizeOmnibusPriceVnd( + off.price_current, + params.minFloorVnd + ); + if (price != null) pricedAll.push({ rawId, id, price_current: price }); + if ( + (rawId && excludedIds.has(rawId)) || + (id && excludedIds.has(id)) || + isOfferUnavailable(off) || + off.implausiblyLow === true || + price == null + ) { + markExcluded(rawId); + continue; + } + inStockSized.push({ id, price_current: price }); + } + + const baitIdsFromInStock = implausiblyLowOfferIds(inStockSized); + for (const bId of baitIdsFromInStock) excludedIds.add(bId); + if (inStockSized.length > 0) { + for (const off of pricedAll) { + if ( + isOfferImplausiblyLowAgainstInStock( + off, + inStockSized, + baitIdsFromInStock + ) + ) { + markExcluded(off.rawId); + } + } + } + + const inStockPlausibleOffers = plausibleOffers(inStockSized).sort( + (a, b) => a.price_current - b.price_current + ); + return { excludedIds, inStockPlausibleOffers }; +} + +/** + * Builds an ascending time series of verified prices: + * - In `'offer'` mode, collapses identical timestamps to the lowest valid price. + * - In `'market'` mode, computes the step-function market floor across active + * plausible offers at each observation timestamp (carrying each offer forward + * up to `MAX_OMNIBUS_BLACKOUT_GAP_DAYS` so staggered store crawls never create + * artificial spikes). + */ +function buildEffectiveSeries( + points: readonly CleanHistoryPoint[], + mode: 'offer' | 'market' +): { series: SeriesPoint[]; nonBaitPoints: CleanHistoryPoint[] } { + if (points.length === 0) return { series: [], nonBaitPoints: [] }; + const sorted = [...points].sort( + (a, b) => a.recordedMs - b.recordedMs || a.priceVnd - b.priceVnd + ); + + // When multiple offers are present without explicit referenceOffers, run + // cross-offer outlier detection on each offer's latest observed price so a + // bait listing inside raw points cannot set the 30d or 90d floor. + const latestByOffer = new Map(); + for (const pt of sorted) { + latestByOffer.set(pt.offerKey, pt.priceVnd); + } + const offerEntries = Array.from(latestByOffer.entries()); + const autoBaitKeys = new Set(); + if (offerEntries.length >= 3) { + const flagged = implausiblyLowIndexes(offerEntries.map(([, p]) => p)); + for (const idx of flagged) { + const key = offerEntries[idx]?.[0]; + if (key) autoBaitKeys.add(key); + } + } + + const filtered = + autoBaitKeys.size > 0 + ? sorted.filter((pt) => !autoBaitKeys.has(pt.offerKey)) + : sorted; + if (filtered.length === 0) return { series: [], nonBaitPoints: [] }; + + if (mode === 'offer' || latestByOffer.size <= 1) { + const out: SeriesPoint[] = []; + for (const pt of filtered) { + const prev = out[out.length - 1]; + if (prev && prev.recordedMs === pt.recordedMs) { + if (pt.priceVnd < prev.priceVnd) { + out[out.length - 1] = { + recordedMs: pt.recordedMs, + priceVnd: pt.priceVnd, + }; + } + } else { + out.push({ recordedMs: pt.recordedMs, priceVnd: pt.priceVnd }); + } + } + return { series: out, nonBaitPoints: filtered }; + } + + const carryLimitMs = MAX_OMNIBUS_BLACKOUT_GAP_DAYS * DAY_MS; + const activeOffers = new Map< + string, + { priceVnd: number; recordedMs: number } + >(); + const out: SeriesPoint[] = []; + + let i = 0; + while (i < filtered.length) { + const tMs = filtered[i]!.recordedMs; + while (i < filtered.length && filtered[i]!.recordedMs === tMs) { + const pt = filtered[i]!; + const existing = activeOffers.get(pt.offerKey); + if ( + !existing || + existing.recordedMs < tMs || + pt.priceVnd < existing.priceVnd + ) { + activeOffers.set(pt.offerKey, { + priceVnd: pt.priceVnd, + recordedMs: tMs, + }); + } + i++; + } + let minActive = Number.POSITIVE_INFINITY; + for (const [key, state] of activeOffers.entries()) { + if (tMs - state.recordedMs > carryLimitMs) { + activeOffers.delete(key); + continue; + } + if (state.priceVnd < minActive) { + minActive = state.priceVnd; + } + } + if (Number.isFinite(minActive)) { + out.push({ recordedMs: tMs, priceVnd: minActive }); + } + } + return { series: out, nonBaitPoints: filtered }; +} + +const EMPTY_CYCLE_90D: Cycle90dEvaluation = { + signal: 'insufficient_data', + percentile: null, + topPercentileDisplay: null, + low90dVnd: null, + high90dVnd: null, + median90dVnd: null, + aboveFloorVnd: null, + aboveFloorPct: null, + observedPointDays: 0, + observedSpanDays90d: 0, +}; + +function evaluate90dCycleFromSeries(params: { + readonly series: readonly SeriesPoint[]; + readonly anchorMs: number; + readonly currentInStockPriceVnd: number | null; +}): Cycle90dEvaluation { + const { series, anchorMs, currentInStockPriceVnd } = params; + const cutoff90dMs = anchorMs - CYCLE_90D_WINDOW_DAYS * DAY_MS; + const in90d = series.filter( + (pt) => pt.recordedMs >= cutoff90dMs && pt.recordedMs <= anchorMs + ); + if (in90d.length === 0) return EMPTY_CYCLE_90D; + + const earliest90dMs = in90d[0]!.recordedMs; + const latest90dMs = in90d[in90d.length - 1]!.recordedMs; + const observedSpanDays90d = Math.max( + 0, + Math.floor((latest90dMs - earliest90dMs) / DAY_MS) + ); + + // Bucket into 24-hour day slots anchored at `anchorMs` so burst crawls on a + // single day never overweight one day in the 90-day empirical distribution. + const dailyMinByBucket = new Map(); + for (const pt of in90d) { + const dayBucket = Math.max( + 0, + Math.floor((anchorMs - pt.recordedMs) / DAY_MS) + ); + const prev = dailyMinByBucket.get(dayBucket); + if (prev == null || pt.priceVnd < prev) { + dailyMinByBucket.set(dayBucket, pt.priceVnd); + } + } + + const observedPointDays = dailyMinByBucket.size; + const sortedDailyPrices = Array.from(dailyMinByBucket.values()).sort( + (a, b) => a - b + ); + const rawLow90d = sortedDailyPrices[0] ?? null; + const rawHigh90d = sortedDailyPrices[sortedDailyPrices.length - 1] ?? null; + const low90dVnd = + rawLow90d != null && currentInStockPriceVnd != null + ? Math.min(rawLow90d, currentInStockPriceVnd) + : rawLow90d; + const high90dVnd = + rawHigh90d != null && currentInStockPriceVnd != null + ? Math.max(rawHigh90d, currentInStockPriceVnd) + : rawHigh90d; + const median90dVnd = computeSortedMedian(sortedDailyPrices); + + if ( + currentInStockPriceVnd == null || + observedPointDays < MIN_CYCLE_90D_POINTS || + observedSpanDays90d < MIN_CYCLE_90D_SPAN_DAYS || + low90dVnd == null || + high90dVnd == null + ) { + return { + signal: 'insufficient_data', + percentile: null, + topPercentileDisplay: null, + low90dVnd, + high90dVnd, + median90dVnd, + aboveFloorVnd: null, + aboveFloorPct: null, + observedPointDays, + observedSpanDays90d, + }; + } + + let belowCount = 0; + let equalCount = 0; + for (const p of sortedDailyPrices) { + if (p < currentInStockPriceVnd) belowCount++; + else if (p === currentInStockPriceVnd) equalCount++; + } + + const rawPercentile = + ((belowCount + 0.5 * equalCount) / sortedDailyPrices.length) * 100; + const percentile = Math.min(100, Math.max(0, Math.round(rawPercentile))); + const topPercentileDisplay = Math.max(1, percentile); + const aboveFloorVnd = Math.max(0, currentInStockPriceVnd - low90dVnd); + const aboveFloorPct = + low90dVnd > 0 && aboveFloorVnd > 0 + ? roundDisplayPct((aboveFloorVnd / low90dVnd) * 100) + : 0; + const relativeSpread = + low90dVnd > 0 ? (high90dVnd - low90dVnd) / low90dVnd : 0; + + let signal: Cycle90dSignalKind; + if (relativeSpread < MIN_CYCLE_90D_RELATIVE_SPREAD) { + signal = 'fair_market'; + } else if (rawPercentile <= CYCLE_BUY_NOW_MAX_PERCENTILE) { + signal = 'buy_now_floor'; + } else if ( + rawPercentile <= CYCLE_FAIR_MARKET_MAX_PERCENTILE || + aboveFloorPct < 1 + ) { + signal = 'fair_market'; + } else { + signal = 'above_recent_floor'; + } + + return { + signal, + percentile, + topPercentileDisplay, + low90dVnd, + high90dVnd, + median90dVnd, + aboveFloorVnd, + aboveFloorPct, + observedPointDays, + observedSpanDays90d, + }; +} + +function extractCleanHistoryPoints(params: { + readonly points: readonly OmnibusAuditPointInput[] | null | undefined; + readonly excludedIds: ReadonlySet; + readonly inStockPlausibleOffers: readonly { + id: string; + price_current: number; + }[]; + readonly minFloorVnd: number; + readonly explicitAnchorMs: number | null; +}): CleanHistoryPoint[] { + const rawPoints = Array.isArray(params.points) ? params.points : []; + const peerMedianVnd = + params.inStockPlausibleOffers.length >= 2 + ? params.inStockPlausibleOffers[ + Math.floor((params.inStockPlausibleOffers.length - 1) / 2) + ]!.price_current + : null; + const cleanPoints: CleanHistoryPoint[] = []; + + for (const pt of rawPoints) { + if (!pt || typeof pt !== 'object' || Array.isArray(pt)) continue; + if (pt.source === 'live_listing') continue; + if (isOfferUnavailable(pt) || pt.implausiblyLow === true) continue; + + const rawOfferId = + typeof pt.product_id === 'string' ? pt.product_id.trim() : ''; + const canonOfferId = normalizeOfferId(rawOfferId); + if ( + (canonOfferId && params.excludedIds.has(canonOfferId)) || + (rawOfferId && params.excludedIds.has(rawOfferId)) + ) { + continue; + } + + const priceVnd = sanitizeOmnibusPriceVnd(pt.price, params.minFloorVnd); + if (priceVnd == null) continue; + if ( + peerMedianVnd != null && + priceVnd < peerMedianVnd * IMPLAUSIBLY_LOW_RATIO + ) { + continue; + } + + const recordedMs = parseRecordedAtMs(pt.recorded_at); + if (recordedMs == null) continue; + if ( + params.explicitAnchorMs != null && + recordedMs > params.explicitAnchorMs + ) { + continue; + } + + cleanPoints.push({ + offerKey: canonOfferId || rawOfferId || '__default__', + priceVnd, + recordedMs, + }); + } + return cleanPoints; +} + +/** + * Resolves the latest eligible observation timestamp across verified, non-bait, + * available crawler points so callers share the exact same anchor rules as + * `evaluateOmnibusPriceAudit`. + */ +export function resolveOmnibusReferenceAnchorMs(params: { + readonly points: readonly OmnibusAuditPointInput[] | null | undefined; + readonly referenceOffers?: readonly OmnibusReferenceOfferInput[] | null; + readonly unavailableOfferIds?: ReadonlySet | null; + readonly implausibleOfferIds?: ReadonlySet | null; + readonly minValidPriceVnd?: number | null; +}): number | null { + const minFloorVnd = + typeof params.minValidPriceVnd === 'number' && + Number.isFinite(params.minValidPriceVnd) && + params.minValidPriceVnd > 0 + ? Math.round(params.minValidPriceVnd) + : MINIMUM_EARBUDS_PRICE_FLOOR_VND; + const { excludedIds, inStockPlausibleOffers } = buildOfferExclusionSets({ + referenceOffers: params.referenceOffers, + unavailableOfferIds: params.unavailableOfferIds, + implausibleOfferIds: params.implausibleOfferIds, + minFloorVnd, + }); + const cleanPoints = extractCleanHistoryPoints({ + points: params.points, + excludedIds, + inStockPlausibleOffers, + minFloorVnd, + explicitAnchorMs: null, + }); + const { series } = buildEffectiveSeries(cleanPoints, 'market'); + return series.length > 0 ? series[series.length - 1]!.recordedMs : null; +} +export function evaluateOmnibusPriceAudit( + params: EvaluateOmnibusPriceAuditParams +): OmnibusPriceAuditResult { + const safeParams = + params && typeof params === 'object' + ? params + : ({ + points: [], + currentPriceVnd: null, + } as EvaluateOmnibusPriceAuditParams); + + const minFloorVnd = + typeof safeParams.minValidPriceVnd === 'number' && + Number.isFinite(safeParams.minValidPriceVnd) && + safeParams.minValidPriceVnd > 0 + ? Math.round(safeParams.minValidPriceVnd) + : MINIMUM_EARBUDS_PRICE_FLOOR_VND; + + const { excludedIds, inStockPlausibleOffers } = buildOfferExclusionSets({ + referenceOffers: safeParams.referenceOffers, + unavailableOfferIds: safeParams.unavailableOfferIds, + implausibleOfferIds: safeParams.implausibleOfferIds, + minFloorVnd, + }); + + const rawCurrent = sanitizeOmnibusPriceVnd( + safeParams.currentPriceVnd, + minFloorVnd + ); + const currentIsBaitAgainstPeers = + rawCurrent != null && + inStockPlausibleOffers.length >= 2 && + isImplausiblyLowPrice(rawCurrent, inStockPlausibleOffers); + + const currentPriceVnd = + safeParams.currentOfferUnavailable === true || + safeParams.currentOfferImplausiblyLow === true || + currentIsBaitAgainstPeers + ? null + : rawCurrent; + + const rawClaimedOrig = sanitizeOmnibusPriceVnd( + safeParams.claimedOriginalPriceVnd, + minFloorVnd + ); + const claimedOriginalPriceVnd = + currentPriceVnd != null && + rawClaimedOrig != null && + rawClaimedOrig > currentPriceVnd + ? rawClaimedOrig + : null; + + const claimedDiscountVnd = + currentPriceVnd != null && claimedOriginalPriceVnd != null + ? claimedOriginalPriceVnd - currentPriceVnd + : null; + const claimedDiscountPct = + claimedDiscountVnd != null && claimedOriginalPriceVnd != null + ? roundDisplayPct((claimedDiscountVnd / claimedOriginalPriceVnd) * 100) + : null; + + const resolvedInStockPrice = (() => { + if (safeParams.currentInStockPriceVnd !== undefined) { + if (safeParams.currentInStockPriceVnd === null) return null; + const candidate = sanitizeOmnibusPriceVnd( + safeParams.currentInStockPriceVnd, + minFloorVnd + ); + if ( + candidate != null && + inStockPlausibleOffers.length >= 2 && + isImplausiblyLowPrice(candidate, inStockPlausibleOffers) + ) { + return null; + } + return candidate; + } + return currentPriceVnd; + })(); + + const explicitAnchorMs = + safeParams.referenceTimestampMs != null && + Number.isFinite(safeParams.referenceTimestampMs) && + safeParams.referenceTimestampMs > 0 + ? Math.round(safeParams.referenceTimestampMs) + : null; + + const cleanPoints = extractCleanHistoryPoints({ + points: safeParams.points, + excludedIds, + inStockPlausibleOffers, + minFloorVnd, + explicitAnchorMs, + }); + + const mode = safeParams.mode === 'market' ? 'market' : 'offer'; + const { series, nonBaitPoints } = buildEffectiveSeries(cleanPoints, mode); + + const unverified = ( + observedSpanDays: number, + validObservationCount: number, + cycle90d: Cycle90dEvaluation + ): OmnibusPriceAuditResult => ({ + currentPriceVnd, + claimedOriginalPriceVnd, + claimedDiscountVnd, + claimedDiscountPct, + priorFloorPriceVnd: null, + observedSpanDays, + windowDaysUsed: 0, + isOmnibusCertified: false, + hasBlackoutGap: false, + windowStatus: 'insufficient_history', + verdict: 'unverified_window', + deltaVsPriorFloorVnd: null, + deltaVsPriorFloorPct: null, + claimedVsPriorFloorMarkupVnd: null, + claimedVsPriorFloorMarkupPct: null, + validObservationCount, + cycle90d, + }); + + if (series.length === 0) { + return unverified(0, 0, EMPTY_CYCLE_90D); + } + + const seriesLatestMs = series[series.length - 1]!.recordedMs; + const anchorMs = explicitAnchorMs ?? seriesLatestMs; + const earliestMs = series[0]!.recordedMs; + const seriesSpanMs = Math.max(0, seriesLatestMs - earliestMs); + const anchorSpanMs = Math.max(0, anchorMs - earliestMs); + const observedSpanDays = + series.length >= 2 ? Math.floor(seriesSpanMs / DAY_MS) : 0; + + const cycle90d = evaluate90dCycleFromSeries({ + series, + anchorMs, + currentInStockPriceVnd: resolvedInStockPrice, + }); + + // Require multi-day actual observations (>= 1 full day between real points + // and >= 2 timestamps) before reporting any prior floor at all. + if (series.length < 2 || seriesSpanMs < DAY_MS || currentPriceVnd == null) { + return unverified(observedSpanDays, series.length, cycle90d); + } + + const windowStartMs = anchorMs - OMNIBUS_WINDOW_DAYS * DAY_MS; + const maxGapMs = MAX_OMNIBUS_BLACKOUT_GAP_DAYS * DAY_MS; + const spansFull30d = + seriesSpanMs >= OMNIBUS_WINDOW_DAYS * DAY_MS && + anchorSpanMs >= OMNIBUS_WINDOW_DAYS * DAY_MS; + + let carryInPoint: SeriesPoint | null = null; + const inWindowPoints: SeriesPoint[] = []; + for (const pt of series) { + if (pt.recordedMs <= windowStartMs) { + if (mode === 'offer') carryInPoint = pt; + } else if (pt.recordedMs <= anchorMs) { + inWindowPoints.push(pt); + } + } + + // In `'market'` mode, compute carry-in at `windowStartMs` strictly from offers + // whose OWN latest observation at `<= windowStartMs` has not expired (`<= maxGapMs`), + // so an offer that expired before the 30-day window began never leaks in via + // another offer's aggregate timestamp. + if (mode === 'market' && spansFull30d) { + const boundaryOffers = new Map< + string, + { priceVnd: number; recordedMs: number } + >(); + for (const pt of nonBaitPoints) { + if (pt.recordedMs > windowStartMs) break; + const prev = boundaryOffers.get(pt.offerKey); + if ( + !prev || + prev.recordedMs < pt.recordedMs || + pt.priceVnd < prev.priceVnd + ) { + boundaryOffers.set(pt.offerKey, { + priceVnd: pt.priceVnd, + recordedMs: pt.recordedMs, + }); + } + } + let minBoundaryVnd = Number.POSITIVE_INFINITY; + let latestBoundaryMs = 0; + for (const state of boundaryOffers.values()) { + if (windowStartMs - state.recordedMs > maxGapMs) continue; + if (state.priceVnd < minBoundaryVnd) minBoundaryVnd = state.priceVnd; + if (state.recordedMs > latestBoundaryMs) { + latestBoundaryMs = state.recordedMs; + } + } + if (Number.isFinite(minBoundaryVnd) && latestBoundaryMs > 0) { + carryInPoint = { priceVnd: minBoundaryVnd, recordedMs: latestBoundaryMs }; + } + } + + let hasBlackoutGap = false; + if (spansFull30d) { + const checkTimes: number[] = []; + if (carryInPoint) { + checkTimes.push(carryInPoint.recordedMs); + } else { + checkTimes.push(windowStartMs); + } + for (const pt of inWindowPoints) { + checkTimes.push(pt.recordedMs); + } + checkTimes.push(anchorMs); + + for (let i = 1; i < checkTimes.length; i++) { + if (checkTimes[i]! - checkTimes[i - 1]! > maxGapMs) { + hasBlackoutGap = true; + break; + } + } + } + + const windowCandidates: SeriesPoint[] = spansFull30d + ? [ + ...(carryInPoint && windowStartMs - carryInPoint.recordedMs <= maxGapMs + ? [carryInPoint] + : []), + ...inWindowPoints, + ] + : [...series]; + + const distinctWindowDays = new Set( + inWindowPoints.map((pt) => Math.floor((anchorMs - pt.recordedMs) / DAY_MS)) + ).size; + + // Separate the current price event tail from prior observations when the price + // changed within the recent campaign window (`<= 7` days), so a genuine sale + // starting today compares against the prior floor rather than against itself. + const hasPriceVariationInWindow = windowCandidates.some( + (pt) => pt.priceVnd !== currentPriceVnd + ); + const tailCutoffMs = hasPriceVariationInWindow + ? anchorMs - MAX_CURRENT_EVENT_TAIL_DAYS * DAY_MS + : anchorMs - 12 * 3_600_000; + + let trimEnd = windowCandidates.length; + while (trimEnd > 1) { + const tail = windowCandidates[trimEnd - 1]!; + if (tail.priceVnd === currentPriceVnd && tail.recordedMs > tailCutoffMs) { + trimEnd--; + } else { + break; + } + } + const priorCandidates = windowCandidates.slice(0, trimEnd); + + let priorFloorPriceVnd: number | null = null; + for (const pt of priorCandidates) { + if (priorFloorPriceVnd == null || pt.priceVnd < priorFloorPriceVnd) { + priorFloorPriceVnd = pt.priceVnd; + } + } + + const isOmnibusCertified = + spansFull30d && + !hasBlackoutGap && + distinctWindowDays >= MIN_OMNIBUS_OBSERVATION_DAYS && + priorFloorPriceVnd != null; + + const windowStatus: OmnibusWindowStatus = + priorFloorPriceVnd == null + ? 'insufficient_history' + : isOmnibusCertified + ? 'omnibus_30d_certified' + : spansFull30d && + (hasBlackoutGap || + distinctWindowDays < MIN_OMNIBUS_OBSERVATION_DAYS) + ? 'blackout_gap' + : 'partial_window'; + + const windowDaysUsed = + priorFloorPriceVnd == null || windowStatus === 'blackout_gap' + ? 0 + : isOmnibusCertified + ? OMNIBUS_WINDOW_DAYS + : Math.min(OMNIBUS_WINDOW_DAYS - 1, Math.max(1, observedSpanDays)); + + const deltaVsPriorFloorVnd = + priorFloorPriceVnd != null ? currentPriceVnd - priorFloorPriceVnd : null; + const deltaVsPriorFloorPct = + deltaVsPriorFloorVnd != null && priorFloorPriceVnd != null + ? roundDisplayPct((deltaVsPriorFloorVnd / priorFloorPriceVnd) * 100) + : null; + + const claimedVsPriorFloorMarkupVnd = + claimedOriginalPriceVnd != null && priorFloorPriceVnd != null + ? claimedOriginalPriceVnd - priorFloorPriceVnd + : null; + const claimedVsPriorFloorMarkupPct = + claimedVsPriorFloorMarkupVnd != null && priorFloorPriceVnd != null + ? roundDisplayPct( + (claimedVsPriorFloorMarkupVnd / priorFloorPriceVnd) * 100 + ) + : null; + + let verdict: OmnibusAuditVerdict = 'unverified_window'; + if (isOmnibusCertified && priorFloorPriceVnd != null) { + if (claimedOriginalPriceVnd != null) { + if ( + claimedOriginalPriceVnd > priorFloorPriceVnd && + currentPriceVnd >= priorFloorPriceVnd + ) { + verdict = 'fake_strikethrough_above_floor'; + } else if ( + claimedOriginalPriceVnd > Math.round(priorFloorPriceVnd * 1.02) && + currentPriceVnd < priorFloorPriceVnd + ) { + verdict = 'exaggerated_strikethrough'; + } else if (currentPriceVnd < priorFloorPriceVnd) { + verdict = 'verified_omnibus_reduction'; + } else { + verdict = 'at_or_above_30d_floor'; + } + } else if (currentPriceVnd < priorFloorPriceVnd) { + verdict = 'below_30d_floor'; + } else { + verdict = 'at_or_above_30d_floor'; + } + } + + return { + currentPriceVnd, + claimedOriginalPriceVnd, + claimedDiscountVnd, + claimedDiscountPct, + priorFloorPriceVnd, + observedSpanDays, + windowDaysUsed, + isOmnibusCertified, + hasBlackoutGap, + windowStatus, + verdict, + deltaVsPriorFloorVnd, + deltaVsPriorFloorPct, + claimedVsPriorFloorMarkupVnd, + claimedVsPriorFloorMarkupPct, + validObservationCount: series.length, + cycle90d, + }; +} + +/** + * Formats an `OmnibusPriceAuditResult` into locale-ready strings and semantic + * WCAG contrast tones (`good` / `warn` / `bad` / `neutral`) for `vi`, `en`, `cs`. + */ +export function formatOmnibusAuditCopy( + audit: OmnibusPriceAuditResult, + t: OmnibusVerdictTranslator, + locale?: string | null +): FormattedOmnibusAuditCopy { + const { + windowStatus: ws, + verdict: vd, + currentPriceVnd: curVnd, + claimedOriginalPriceVnd: origVnd, + claimedDiscountPct: claimPct, + priorFloorPriceVnd: flrVnd, + windowDaysUsed: days, + isOmnibusCertified: cert, + deltaVsPriorFloorVnd: dVnd, + deltaVsPriorFloorPct: dPct, + claimedVsPriorFloorMarkupVnd: mkVnd, + claimedVsPriorFloorMarkupPct: mkPct, + cycle90d: c, + } = audit; + const priceOrDash = (vnd: number | null) => + vnd != null && vnd > 0 ? formatPriceVnd(vnd, locale) : '-'; + const fmtVnd = (vnd: number) => formatPriceVnd(vnd, locale); + const fmtNum = (num: number) => formatPlainNumber(num, locale); + + const isFake = vd === 'fake_strikethrough_above_floor'; + const isExag = vd === 'exaggerated_strikethrough'; + + const statusBadgeText = + ws === 'omnibus_30d_certified' + ? t('oOk') + : ws === 'partial_window' + ? t('oPart', { days }) + : ws === 'blackout_gap' + ? t('oGap') + : t('oPend'); + const statusBadgeTone: 'good' | 'warn' | 'bad' | 'neutral' = + ws === 'omnibus_30d_certified' + ? isFake + ? 'bad' + : 'good' + : ws === 'partial_window' || ws === 'blackout_gap' + ? 'warn' + : 'neutral'; + + const claimedBadgeText = + origVnd != null && claimPct != null + ? t('oClaim', { pct: fmtNum(claimPct), original: fmtVnd(origVnd) }) + : null; + + let currentSubText: string; + let currentSubTone: 'bad' | 'good' | 'neutral' = 'neutral'; + if (origVnd == null) { + currentSubText = t('oNoOrig'); + } else if (flrVnd == null) { + currentSubText = t('oNeed'); + } else if ( + (isFake || isExag || origVnd > Math.round(flrVnd * 1.02)) && + mkVnd != null && + mkVnd > 0 && + mkPct != null + ) { + currentSubText = t('oMarkup', { + markup: fmtVnd(mkVnd), + pct: fmtNum(mkPct), + }); + currentSubTone = isFake || isExag ? 'bad' : 'neutral'; + } else { + currentSubText = t('oAlign'); + currentSubTone = cert && origVnd <= flrVnd ? 'good' : 'neutral'; + } + + const colFloorTitle = + ws === 'omnibus_30d_certified' + ? t('oOk') + : ws === 'partial_window' + ? t('oPart', { days }) + : t('oFlr'); + + let floorDeltaText: string; + let floorDeltaTone: 'good' | 'bad' | 'neutral' = 'neutral'; + if (flrVnd == null || dVnd == null || dPct == null) { + floorDeltaText = t('oNeed'); + } else if (dVnd < 0) { + floorDeltaText = t('oDrop', { + pct: fmtNum(Math.abs(dPct)), + amount: fmtVnd(Math.abs(dVnd)), + }); + floorDeltaTone = 'good'; + } else if (dVnd > 0) { + floorDeltaText = t(isFake ? 'oFake' : 'oUp', { + pct: fmtNum(dPct), + amount: fmtVnd(dVnd), + }); + floorDeltaTone = 'bad'; + } else if (isFake) { + floorDeltaText = t('oFake', { pct: fmtNum(0), amount: fmtVnd(0) }); + floorDeltaTone = 'bad'; + } else { + floorDeltaText = t('oFlat'); + } + + const floorDisclaimerText = + ws === 'partial_window' + ? t('oNoteP', { days }) + : ws === 'blackout_gap' + ? t('oNoteG') + : null; + + let cycleValueText: string; + let cycleValueTone: 'good' | 'bad' | 'neutral' = 'neutral'; + const rngSub = + c.low90dVnd != null && c.high90dVnd != null + ? t('oRng', { low: fmtVnd(c.low90dVnd), high: fmtVnd(c.high90dVnd) }) + : null; + let cycleSubText: string; + + if ( + c.signal === 'buy_now_floor' && + c.topPercentileDisplay != null && + rngSub != null + ) { + cycleValueText = t('oBuy', { pct: fmtNum(c.topPercentileDisplay) }); + cycleValueTone = 'good'; + cycleSubText = rngSub; + } else if ( + c.signal === 'fair_market' && + c.percentile != null && + rngSub != null + ) { + cycleValueText = t('oFair', { pct: fmtNum(c.percentile) }); + cycleSubText = rngSub; + } else if ( + c.signal === 'above_recent_floor' && + c.aboveFloorVnd != null && + rngSub != null + ) { + cycleValueText = t('oWait', { gap: fmtVnd(c.aboveFloorVnd) }); + cycleValueTone = 'bad'; + cycleSubText = rngSub; + } else { + cycleValueText = t('oCycP'); + cycleSubText = t('oCycN', { + points: c.observedPointDays, + days: c.observedSpanDays90d, + }); + } + + return { + cardTitle: t('oTitle'), + statusBadgeText, + statusBadgeTone, + colCurrentTitle: t('oCur'), + currentPriceText: priceOrDash(curVnd), + claimedBadgeText, + currentSubText, + currentSubTone, + colFloorTitle, + floorPriceText: priceOrDash(flrVnd), + floorDeltaText, + floorDeltaTone, + floorDisclaimerText, + colCycleTitle: t('oCyc'), + cycleValueText, + cycleValueTone, + cycleSubText, + }; +} + +const validPosVnd = (v: unknown): number | null => { + const n = parseStrictFiniteNumber(v); + if (n == null) return null; + const r = Math.round(n); + return r > 0 && r <= MAX_VALID_VND_PRICE ? r : null; +}; + +/** + * Seasonal sale campaign filter predicate for `/deals` (`DealFinderWorkspace`). + */ +export function matchesSeasonalSaleFilter( + signal: RadarSignal | null | undefined, + mode: SeasonalSaleFilterMode +): boolean { + if (mode === 'all') return true; + if (!signal || typeof signal !== 'object') return false; + if (mode === 'genuine_sale_drops') { + const g = signal.genuineDeal; + return Boolean( + g && + typeof g === 'object' && + typeof signal.savingsPct === 'number' && + Number.isFinite(signal.savingsPct) && + signal.savingsPct > 0 && + validPosVnd(g.priceCurrent) != null && + validPosVnd(g.savingsVsMedianVnd) != null + ); + } + if (mode === 'inflated_presale_warnings') { + const trap = signal.fakeSaleTrap; + const cur = + trap && typeof trap === 'object' ? validPosVnd(trap.priceCurrent) : null; + const orig = + trap && typeof trap === 'object' ? validPosVnd(trap.priceOriginal) : null; + return Boolean( + typeof signal.fakeMarkupPct === 'number' && + Number.isFinite(signal.fakeMarkupPct) && + signal.fakeMarkupPct > 0 && + cur != null && + orig != null && + orig > cur + ); + } + return true; +} + +export function countSeasonalSaleCampaignDeals( + deals: readonly T[], + getSignal: (slug: string) => RadarSignal | null | undefined +): { + genuineSaleCount: number; + inflatedWarningCount: number; +} { + if (!Array.isArray(deals)) { + return { genuineSaleCount: 0, inflatedWarningCount: 0 }; + } + let genuineSaleCount = 0; + let inflatedWarningCount = 0; + for (const d of deals) { + if (!d || typeof d.slug !== 'string') continue; + const sig = getSignal(d.slug); + if (matchesSeasonalSaleFilter(sig, 'genuine_sale_drops')) { + genuineSaleCount++; + } + if (matchesSeasonalSaleFilter(sig, 'inflated_presale_warnings')) { + inflatedWarningCount++; + } + } + return { genuineSaleCount, inflatedWarningCount }; +} diff --git a/apps/web/src/lib/rate-i18n.ts b/apps/web/src/lib/rate-i18n.ts index 1d4a749a..bfc0b405 100644 --- a/apps/web/src/lib/rate-i18n.ts +++ b/apps/web/src/lib/rate-i18n.ts @@ -1,6 +1,6 @@ -import csMessages from '../../locales/cs.json'; -import enMessages from '../../locales/en.json'; -import viMessages from '../../locales/vi.json'; +import type csMessages from '../../locales/cs.json'; +import type enMessages from '../../locales/en.json'; +import type viMessages from '../../locales/vi.json'; export type SupportedRateLocale = 'vi' | 'en' | 'cs'; export type RateLocale = SupportedRateLocale; @@ -24,102 +24,14 @@ export function normalizeRateLocale( } // All UI copy lives in the next-intl catalogs (locales/*.json), the single -// source of truth for every locale. These compile-time bindings fail the build -// if any locale catalog is missing a key present in vi.json. -type RateCopyStrings = typeof viMessages.rate; -const _enRateCheck: RateCopyStrings = enMessages.rate; -const _csRateCheck: RateCopyStrings = csMessages.rate; -void _enRateCheck; -void _csRateCheck; - -type ErrorsCopyStrings = typeof viMessages.errors; -const _enErrorsCheck: ErrorsCopyStrings = enMessages.errors; -const _csErrorsCheck: ErrorsCopyStrings = csMessages.errors; -void _enErrorsCheck; -void _csErrorsCheck; - -type CompareCopyStrings = typeof viMessages.compare; -const _enCompareCheck: CompareCopyStrings = enMessages.compare; -const _csCompareCheck: CompareCopyStrings = csMessages.compare; -void _enCompareCheck; -void _csCompareCheck; - -type LeaderboardCopyStrings = typeof viMessages.leaderboard; -const _enLeaderboardCheck: LeaderboardCopyStrings = enMessages.leaderboard; -const _csLeaderboardCheck: LeaderboardCopyStrings = csMessages.leaderboard; -void _enLeaderboardCheck; -void _csLeaderboardCheck; - -type ReviewsCopyStrings = typeof viMessages.reviews; -const _enReviewsCheck: ReviewsCopyStrings = enMessages.reviews; -const _csReviewsCheck: ReviewsCopyStrings = csMessages.reviews; -void _enReviewsCheck; -void _csReviewsCheck; - -type WatchlistCopyStrings = typeof viMessages.watchlist; -const _enWatchlistCheck: WatchlistCopyStrings = enMessages.watchlist; -const _csWatchlistCheck: WatchlistCopyStrings = csMessages.watchlist; -void _enWatchlistCheck; -void _csWatchlistCheck; - -type DealsCopyStrings = typeof viMessages.deals; -const _enDealsCheck: DealsCopyStrings = enMessages.deals; -const _csDealsCheck: DealsCopyStrings = csMessages.deals; -void _enDealsCheck; -void _csDealsCheck; - -type InspectCopyStrings = typeof viMessages.inspect; -const _enInspectCheck: InspectCopyStrings = enMessages.inspect; -const _csInspectCheck: InspectCopyStrings = csMessages.inspect; -void _enInspectCheck; -void _csInspectCheck; - -type MerchantsCopyStrings = typeof viMessages.merchants; -const _enMerchantsCheck: MerchantsCopyStrings = enMessages.merchants; -const _csMerchantsCheck: MerchantsCopyStrings = csMessages.merchants; -void _enMerchantsCheck; -void _csMerchantsCheck; - -type ProductDetailCopyStrings = typeof viMessages.productDetail; -const _enProductDetailCheck: ProductDetailCopyStrings = - enMessages.productDetail; -const _csProductDetailCheck: ProductDetailCopyStrings = - csMessages.productDetail; -void _enProductDetailCheck; -void _csProductDetailCheck; - -type HomePageCopyStrings = typeof viMessages.homePage; -const _enHomePageCheck: HomePageCopyStrings = enMessages.homePage; -const _csHomePageCheck: HomePageCopyStrings = csMessages.homePage; -void _enHomePageCheck; -void _csHomePageCheck; - -type DevelopersCopyStrings = typeof viMessages.developers; -const _enDevelopersCheck: DevelopersCopyStrings = enMessages.developers; -const _csDevelopersCheck: DevelopersCopyStrings = csMessages.developers; -void _enDevelopersCheck; -void _csDevelopersCheck; - -type StaticPagesCopyStrings = typeof viMessages.staticPages; -const _enStaticPagesCheck: StaticPagesCopyStrings = enMessages.staticPages; -const _csStaticPagesCheck: StaticPagesCopyStrings = csMessages.staticPages; -void _enStaticPagesCheck; -void _csStaticPagesCheck; - -type CatalogCopyStrings = typeof viMessages.catalog; -const _enCatalogCheck: CatalogCopyStrings = enMessages.catalog; -const _csCatalogCheck: CatalogCopyStrings = csMessages.catalog; -void _enCatalogCheck; -void _csCatalogCheck; - -type HeroSearchCopyStrings = typeof viMessages.heroSearch; -const _enHeroSearchCheck: HeroSearchCopyStrings = enMessages.heroSearch; -const _csHeroSearchCheck: HeroSearchCopyStrings = csMessages.heroSearch; -void _enHeroSearchCheck; -void _csHeroSearchCheck; - -type AuthPortalCopyStrings = typeof viMessages.authPortal; -const _enAuthPortalCheck: AuthPortalCopyStrings = enMessages.authPortal; -const _csAuthPortalCheck: AuthPortalCopyStrings = csMessages.authPortal; -void _enAuthPortalCheck; -void _csAuthPortalCheck; +// source of truth for every locale. Pure type-level constraints fail `tsc` +// whenever any locale catalog misses or adds a key relative to `vi.json`, +// while emitting zero runtime JSON into client JavaScript bundles (#1863). +type AssertAssignable<_Target, _Source extends _Target> = true; + +export type AssertCatalogParity = [ + AssertAssignable, + AssertAssignable, + AssertAssignable, + AssertAssignable, +]; From 5e2bc210fe5408cbf182abfb94f5176cb303b7eb Mon Sep 17 00:00:00 2001 From: JOY <5027251+JOY@users.noreply.github.com> Date: Mon, 23 Nov 2026 01:07:10 +0700 Subject: [PATCH 6/6] fix(web): propagate offer availability into Omnibus price audit (#1872) * fix(web): propagate offer availability into Omnibus price audit Add optional availability on OfferDiscountAnalysis in rate-domain and populate it in getMasterProductPriceHistory, include availability in price-history cache keys, forward offers into PriceHistorySection from ProductDetailView and ItemLazySizePanel, and cover sold-out normal_price exclusion when offers is omitted (Refs #1871). * fix(web): harden reference offer availability and cache key hashing Preserve explicit unavailability on blank-ID reference offers, filter malformed offers entries before fallback, check plausible in-stock offers for allKnownOffersUnavailable, and hash all offers in getCachedMasterProductPriceHistory (Refs #1871). --- .../app/[locale]/smartphones/[slug]/page.tsx | 3 + .../price-history/PriceHistorySection.tsx | 200 ++++++-- .../product/item/ItemLazySizePanel.tsx | 1 + .../lib/__tests__/offer-plausibility.test.ts | 10 + apps/web/src/lib/__tests__/sale-state.test.ts | 442 +++++++++++++++++- apps/web/src/lib/omnibus-price-audit.ts | 9 +- apps/web/src/lib/rate-api.ts | 4 + apps/web/src/lib/rate-domain.ts | 1 + apps/web/src/server/rate/index.ts | 45 +- apps/web/src/server/rate/item-page.ts | 4 +- 10 files changed, 665 insertions(+), 54 deletions(-) diff --git a/apps/web/src/app/[locale]/smartphones/[slug]/page.tsx b/apps/web/src/app/[locale]/smartphones/[slug]/page.tsx index 8121bd88..91f444bd 100644 --- a/apps/web/src/app/[locale]/smartphones/[slug]/page.tsx +++ b/apps/web/src/app/[locale]/smartphones/[slug]/page.tsx @@ -761,6 +761,7 @@ export async function ProductDetailView({ // renders them for its own master, an Item page once per size (#1154). const renderPriceHistory = (v: { product: { name: string }; + offers: typeof offers; priceHistory: typeof priceHistory; minPrice: number; radarSignal: typeof radarSignal; @@ -773,6 +774,7 @@ export async function ProductDetailView({ currentMinPrice: v.minPrice > 0 ? v.minPrice : null, }} radarSignal={v.radarSignal} + offers={v.offers} /> ); const renderOffersBody = (v: { @@ -1631,6 +1633,7 @@ export async function ProductDetailView({ ) : renderPriceHistory({ product, + offers, priceHistory, minPrice: currentMinPrice, radarSignal, diff --git a/apps/web/src/components/price-history/PriceHistorySection.tsx b/apps/web/src/components/price-history/PriceHistorySection.tsx index 2fbae3ca..66561270 100644 --- a/apps/web/src/components/price-history/PriceHistorySection.tsx +++ b/apps/web/src/components/price-history/PriceHistorySection.tsx @@ -19,6 +19,7 @@ import { evaluateOmnibusPriceAudit, formatOmnibusAuditCopy, resolveOmnibusReferenceAnchorMs, + sanitizeOmnibusPriceVnd, type OmnibusPriceAuditResult, type OmnibusReferenceOfferInput, type OmnibusVerdictTranslator, @@ -26,15 +27,17 @@ import { import { minimumListingPriceVnd, normalizeOfferId, + plausibleOffers, } from '@repo/shared-data/rules'; import { isOfferUnavailable, - type OfferAvailability, + toOfferAvailability, } from '@/lib/product-market-stats'; import { MAX_VALID_VND_PRICE, type DiscountVerdictType, type MasterProductPriceHistorySummary, + type OfferAvailability, type OfferDiscountAnalysis, type PriceHistoryPoint, } from '@/lib/rate-domain'; @@ -679,34 +682,112 @@ export default function PriceHistorySection({ return Math.round(raw); }, [history.currentMinPrice]); + const safeOffersInput = useMemo( + () => + Array.isArray(offers) + ? offers.filter((off): off is OmnibusReferenceOfferInput => + Boolean(off && typeof off === 'object' && !Array.isArray(off)) + ) + : [], + [offers] + ); + // Identify unavailable (sold-out / discontinued) offers from explicit `offers`, - // optional `availability` on `offerAnalyses`, prices strictly below the - // verified in-stock minimum (DOS/Rate#1141), or `rate-api`'s unavailable - // suppression signature (`normal_price` despite qualifying for `genuine_deal`). + // explicit `availability` on `offerAnalyses`, or fallback heuristics when + // availability is unknown (prices strictly below the verified in-stock minimum, + // DOS/Rate#1141, or `rate-api`'s unavailable `normal_price` suppression). const unavailableOfferIds = useMemo>(() => { const ids = new Set(); const addId = (rawId: string | null | undefined) => { - if (!rawId) return; + if (typeof rawId !== 'string') return; + const trimmed = rawId.trim(); + if (!trimmed) return; ids.add(rawId); - const canon = normalizeOfferId(rawId); + ids.add(trimmed); + const canon = normalizeOfferId(trimmed); if (canon) ids.add(canon); }; - if (Array.isArray(offers)) { - for (const off of offers) { - if (off && isOfferUnavailable(off)) { - addId(off.id); + const setAvailInMap = ( + map: Map, + rawId: string | null | undefined, + avail: OfferAvailability + ) => { + if (typeof rawId !== 'string') return; + const trimmed = rawId.trim(); + if (!trimmed) return; + const canon = normalizeOfferId(trimmed); + for (const key of [rawId, trimmed, canon]) { + if (!key) continue; + const prev = map.get(key); + if (!prev || isOfferUnavailable({ availability: avail })) { + map.set(key, avail); } } + }; + + const explicitAvailFromAnalyses = new Map(); + for (const oa of offerAnalyses) { + const avail = toOfferAvailability(oa.availability); + if (avail) { + setAvailInMap(explicitAvailFromAnalyses, oa.product_id, avail); + } + } + + const explicitAvailFromOffers = new Map(); + for (const off of safeOffersInput) { + const rawId = + typeof off.id === 'string' && off.id.trim() + ? off.id + : typeof off.product_id === 'string' && off.product_id.trim() + ? off.product_id + : null; + const avail = toOfferAvailability(off.availability); + if (avail) { + setAvailInMap(explicitAvailFromOffers, rawId, avail); + if (isOfferUnavailable({ availability: avail })) { + addId(rawId); + } + continue; + } + if (!rawId) continue; + const trimmed = rawId.trim(); + const canon = normalizeOfferId(trimmed); + const oaAvail = + explicitAvailFromAnalyses.get(rawId) ?? + explicitAvailFromAnalyses.get(trimmed) ?? + (canon ? explicitAvailFromAnalyses.get(canon) : undefined); + if (oaAvail) { + if (isOfferUnavailable({ availability: oaAvail })) { + addId(rawId); + } + continue; + } + const p = Number(off.price_current); + if ( + safeCurrentMinPrice != null && + Number.isFinite(p) && + p > 0 && + Math.round(p) < safeCurrentMinPrice + ) { + addId(rawId); + } } for (const oa of offerAnalyses) { - const maybeAvail = (oa as { availability?: OfferAvailability | null }) - .availability; - if (maybeAvail && isOfferUnavailable({ availability: maybeAvail })) { - addId(oa.product_id); + const canonOaId = normalizeOfferId(oa.product_id); + const explicitAvail = + explicitAvailFromOffers.get(oa.product_id) ?? + explicitAvailFromOffers.get(oa.product_id.trim()) ?? + (canonOaId ? explicitAvailFromOffers.get(canonOaId) : undefined) ?? + toOfferAvailability(oa.availability); + if (explicitAvail) { + if (isOfferUnavailable({ availability: explicitAvail })) { + addId(oa.product_id); + } continue; } + const p = Number(oa.price_current); if ( safeCurrentMinPrice != null && @@ -741,28 +822,79 @@ export default function PriceHistorySection({ } } return ids; - }, [offerAnalyses, offers, safeCurrentMinPrice]); + }, [offerAnalyses, safeCurrentMinPrice, safeOffersInput]); const isUnavailId = useCallback( (id: string) => unavailableOfferIds.has(id) || + unavailableOfferIds.has(id.trim()) || unavailableOfferIds.has(normalizeOfferId(id)), [unavailableOfferIds] ); - const effectiveReferenceOffers = useMemo( - () => - Array.isArray(offers) && offers.length > 0 - ? [...offers] - : offerAnalyses.map((oa) => ({ - id: oa.product_id, - price_current: oa.price_current, - availability: isUnavailId(oa.product_id) - ? ('out_of_stock' as const) - : ('in_stock' as const), - })), - [isUnavailId, offerAnalyses, offers] - ); + const effectiveReferenceOffers = useMemo(() => { + if (safeOffersInput.length > 0) { + return safeOffersInput.map((off) => { + const rawId = + typeof off.id === 'string' && off.id.trim() + ? off.id + : typeof off.product_id === 'string' && off.product_id.trim() + ? off.product_id + : undefined; + const explicit = toOfferAvailability(off.availability); + const explicitUnavailable = + explicit != null && isOfferUnavailable({ availability: explicit }); + const unavailable = + explicitUnavailable || Boolean(rawId && isUnavailId(rawId)); + return { + id: rawId, + price_current: off.price_current, + availability: unavailable + ? explicitUnavailable + ? explicit + : ('out_of_stock' as const) + : ('in_stock' as const), + implausiblyLow: off.implausiblyLow, + }; + }); + } + return offerAnalyses.map((oa) => { + const explicit = toOfferAvailability(oa.availability); + const explicitUnavailable = + explicit != null && isOfferUnavailable({ availability: explicit }); + const unavailable = explicitUnavailable || isUnavailId(oa.product_id); + return { + id: oa.product_id, + price_current: oa.price_current, + availability: unavailable + ? explicitUnavailable + ? explicit + : ('out_of_stock' as const) + : ('in_stock' as const), + }; + }); + }, [isUnavailId, offerAnalyses, safeOffersInput]); + + const allKnownOffersUnavailable = useMemo(() => { + if (effectiveReferenceOffers.length === 0) return false; + const inStockSized: { id: string; price_current: number }[] = []; + effectiveReferenceOffers.forEach((off, idx) => { + if (isOfferUnavailable(off) || off.implausiblyLow === true) return; + const price = sanitizeOmnibusPriceVnd( + off.price_current, + minValidPriceVnd + ); + if (price == null) return; + inStockSized.push({ + id: + typeof off.id === 'string' && off.id.trim() + ? off.id.trim() + : `__idx_${idx}`, + price_current: price, + }); + }); + return plausibleOffers(inStockSized).length === 0; + }, [effectiveReferenceOffers, minValidPriceVnd]); // Historical anchor uses the exact same evidence-eligibility rules as the // Omnibus evaluator so rows below `minValidPriceVnd`, `live_listing` rows, @@ -881,12 +1013,18 @@ export default function PriceHistorySection({ return evaluateOmnibusPriceAudit({ ...omnibusSharedOpts, points: validPoints, - currentPriceVnd: safeCurrentMinPrice, - claimedOriginalPriceVnd: bestClaimedOrig, - currentInStockPriceVnd: safeCurrentMinPrice, + currentPriceVnd: allKnownOffersUnavailable ? null : safeCurrentMinPrice, + claimedOriginalPriceVnd: allKnownOffersUnavailable + ? null + : bestClaimedOrig, + currentInStockPriceVnd: allKnownOffersUnavailable + ? null + : safeCurrentMinPrice, + currentOfferUnavailable: allKnownOffersUnavailable, mode: 'market', }); }, [ + allKnownOffersUnavailable, isUnavailId, offerAnalyses, omnibusByOffer, diff --git a/apps/web/src/components/product/item/ItemLazySizePanel.tsx b/apps/web/src/components/product/item/ItemLazySizePanel.tsx index 46d96424..464384de 100644 --- a/apps/web/src/components/product/item/ItemLazySizePanel.tsx +++ b/apps/web/src/components/product/item/ItemLazySizePanel.tsx @@ -196,6 +196,7 @@ function renderSize( currentMinPrice: data.stats.minPrice > 0 ? data.stats.minPrice : null, }} radarSignal={data.radarSignal} + offers={data.offers} /> ); } diff --git a/apps/web/src/lib/__tests__/offer-plausibility.test.ts b/apps/web/src/lib/__tests__/offer-plausibility.test.ts index 309f4ef6..693de5a9 100644 --- a/apps/web/src/lib/__tests__/offer-plausibility.test.ts +++ b/apps/web/src/lib/__tests__/offer-plausibility.test.ts @@ -235,8 +235,18 @@ async function main() { history.byOffer['sold-out-cheap-real']?.verdict, 'normal_price' ); + assert.equal( + history.byOffer['sold-out-cheap-real']?.availability, + 'out_of_stock' + ); + assert.equal( + history.byOffer['sold-out-high']?.availability, + 'discontinued' + ); assert.equal(history.byOffer['in-stock-3']?.verdict, 'normal_price'); + assert.equal(history.byOffer['in-stock-3']?.availability, 'in_stock'); assert.equal(history.byOffer['in-stock-1']?.verdict, 'genuine_deal'); + assert.equal(history.byOffer['in-stock-1']?.availability, 'in_stock'); assert.equal(history.genuineDealCount, 1); // Zero in-stock offers: safe fallback drops sold-out 500k bait among sold-out peers. diff --git a/apps/web/src/lib/__tests__/sale-state.test.ts b/apps/web/src/lib/__tests__/sale-state.test.ts index edc17eb6..5e92eb7d 100644 --- a/apps/web/src/lib/__tests__/sale-state.test.ts +++ b/apps/web/src/lib/__tests__/sale-state.test.ts @@ -16,7 +16,12 @@ import { matchesSeasonalSaleFilter, } from '../omnibus-price-audit'; import { pickClientMessages } from '../client-messages'; -import { parseEcommerceUrlOrQuery } from '../rate-domain'; +import { + parseEcommerceUrlOrQuery, + type OfferAvailability, + type OfferDiscountAnalysis, +} from '../rate-domain'; +import { formatPriceVnd } from '../locale-format'; import { AppRouterContext, type AppRouterInstance, @@ -26,7 +31,7 @@ import DealFinderWorkspace from '../../components/deals/DealFinderWorkspace'; import DeepInspectWorkspace from '../../components/inspect/DeepInspectWorkspace'; import { GLOBAL_ERROR_CATALOG } from '../../app/global-error'; -function main() { +async function main() { console.warn('🧪 Sale state suite (DOS/Rate#1188)'); // An in-stock price wins over everything else. @@ -984,7 +989,438 @@ function main() { assert.equal(twoInWindowPlusCarry.isOmnibusCertified, false); assert.equal(twoInWindowPlusCarry.windowStatus, 'blackout_gap'); + // ========================================================================= + // 7. Explicit OfferAvailability on OfferDiscountAnalysis & PriceHistorySection + // when `offers` is omitted or forwarded (DOS/Rate#1871) + // ========================================================================= + const supaUrlEnvKey = ['NEXT_PUBLIC_SUPABASE', 'URL'].join('_'); + const supaAnonEnvKey = ['NEXT_PUBLIC_SUPABASE', 'ANON', 'KEY'].join('_'); + process.env[supaUrlEnvKey] = + process.env[supaUrlEnvKey] || 'https://stub.supabase.test'; + process.env[supaAnonEnvKey] = + process.env[supaAnonEnvKey] || 'stub-public-token'; + + const { getMasterProductPriceHistory } = await import('../rate-api'); + const rawHistoryRows1871 = [ + ...[35, 28, 21, 14, 7].map((d, idx) => ({ + id: 100 + idx, + product_id: 'offer-in-stock-1871', + price: 28_500_000, + price_original: 29_000_000, + recorded_at: isoDaysAgo(d), + source: 'crawler', + })), + { + id: 106, + product_id: 'offer-in-stock-1871', + price: 27_000_000, + price_original: 29_000_000, + recorded_at: isoDaysAgo(0), + source: 'crawler', + }, + // Sold-out normal_price offer priced ABOVE currentMinPrice (27.8M > 27.0M) + // with an old 21.5M dip that must never pollute the 30d floor or 90d low. + ...[35, 28, 21, 14, 7].map((d, idx) => ({ + id: 200 + idx, + product_id: 'offer-soldout-above-min', + price: d === 21 ? 21_500_000 : 27_800_000, + price_original: null, + recorded_at: isoDaysAgo(d), + source: 'crawler', + })), + // Discontinued normal_price offer priced EQUAL to currentMinPrice (27.0M) + // with an old 20.0M dip that must also be excluded when `offers` is omitted. + ...[35, 28, 14].map((d, idx) => ({ + id: 300 + idx, + product_id: 'offer-discontinued-at-min', + price: d === 28 ? 20_000_000 : 27_000_000, + price_original: null, + recorded_at: isoDaysAgo(d), + source: 'crawler', + })), + ]; + + const mkOffer1871 = ( + id: string, + merchantName: string, + priceCurrent: number, + priceOriginal: number | null, + availability: OfferAvailability | null + ) => ({ + id, + platform: 'shopee', + title: `iPhone 16 Pro Max ${id}`, + price_current: priceCurrent, + price_original: priceOriginal, + stock: availability === 'in_stock' ? 8 : 0, + rating_star: 4.9, + rating_count: 30, + url: `https://shopee.vn/${id}`, + availability, + merchant: { + id: `m-${id}`, + name: merchantName, + platform: 'shopee', + is_official: true, + rating_star: 4.9, + follower_count: 1000, + location: 'VN', + risk_score: 4, + dosafe_risk_score: 4, + review_risk_score: 4, + review_risk_breakdown: null, + }, + }); + + const offers1871 = [ + mkOffer1871( + 'offer-in-stock-1871', + 'Official Store In Stock', + 27_000_000, + 29_000_000, + 'in_stock' + ), + mkOffer1871( + 'offer-soldout-above-min', + 'Sold Out Store Above Min', + 27_800_000, + null, + 'out_of_stock' + ), + mkOffer1871( + 'offer-discontinued-at-min', + 'Discontinued Store At Min', + 27_000_000, + null, + 'discontinued' + ), + mkOffer1871( + 'offer-unknown-avail', + 'Unknown Availability Store', + 28_900_000, + null, + null + ), + ]; + + const origFetch1871 = globalThis.fetch; + let history1871; + try { + globalThis.fetch = (async (input: RequestInfo | URL) => { + const url = new URL( + typeof input === 'string' + ? input + : input instanceof URL + ? input.toString() + : input.url + ); + const limit = Number(url.searchParams.get('limit') ?? 1000); + const order = url.searchParams.get('order') ?? ''; + let rows = [...rawHistoryRows1871]; + if (limit === 1 && order.startsWith('price.asc')) { + rows.sort((a, b) => a.price - b.price); + rows = rows.slice(0, 1); + } else if (limit === 1 && order.startsWith('price.desc')) { + rows.sort((a, b) => b.price - a.price); + rows = rows.slice(0, 1); + } else { + rows.sort( + (a, b) => Date.parse(b.recorded_at) - Date.parse(a.recorded_at) + ); + } + return new Response(JSON.stringify(rows), { + status: 200, + headers: { 'content-type': 'application/json' }, + }); + }) as typeof fetch; + + history1871 = await getMasterProductPriceHistory('master-1871', offers1871); + } finally { + globalThis.fetch = origFetch1871; + } + + const inStockAnalysis1871: OfferDiscountAnalysis | undefined = + history1871.byOffer['offer-in-stock-1871']; + const soldOutAnalysis1871: OfferDiscountAnalysis | undefined = + history1871.byOffer['offer-soldout-above-min']; + const discontinuedAnalysis1871: OfferDiscountAnalysis | undefined = + history1871.byOffer['offer-discontinued-at-min']; + const unknownAvailAnalysis1871: OfferDiscountAnalysis | undefined = + history1871.byOffer['offer-unknown-avail']; + + assert.equal(history1871.currentMinPrice, 27_000_000); + assert.equal(inStockAnalysis1871?.availability, 'in_stock'); + assert.equal(soldOutAnalysis1871?.availability, 'out_of_stock'); + assert.equal(soldOutAnalysis1871?.verdict, 'normal_price'); + assert.ok((soldOutAnalysis1871?.price_current ?? 0) > 27_000_000); + assert.equal(discontinuedAnalysis1871?.availability, 'discontinued'); + assert.equal(discontinuedAnalysis1871?.verdict, 'normal_price'); + assert.equal(discontinuedAnalysis1871?.price_current, 27_000_000); + assert.equal(unknownAvailAnalysis1871?.availability, undefined); + + // Direct evaluator check with OfferDiscountAnalysis[] (product_id + availability) + const directByOfferAudit1871 = evaluateOmnibusPriceAudit({ + points: history1871.points, + currentPriceVnd: history1871.currentMinPrice, + claimedOriginalPriceVnd: 29_000_000, + mode: 'market', + referenceOffers: Object.values(history1871.byOffer), + referenceTimestampMs: ANCHOR_MS, + }); + assert.equal(directByOfferAudit1871.priorFloorPriceVnd, 28_500_000); + assert.equal(directByOfferAudit1871.verdict, 'verified_omnibus_reduction'); + assert.equal(directByOfferAudit1871.cycle90d.low90dVnd, 27_000_000); + assert.equal(directByOfferAudit1871.cycle90d.high90dVnd, 28_500_000); + assert.equal(directByOfferAudit1871.cycle90d.signal, 'buy_now_floor'); + + // SSR PriceHistorySection WITHOUT `offers` prop: sold-out/discontinued + // normal_price offers priced >= currentMinPrice are excluded from Omnibus + // prior-floor and 90-day cycle inputs via OfferDiscountAnalysis.availability. + for (const locale of ['vi', 'en', 'cs'] as const) { + const rawCatalog = JSON.parse( + readFileSync( + new URL(`../../../locales/${locale}.json`, import.meta.url), + 'utf8' + ) + ) as Record; + const omittedOffersHtml = renderToStaticMarkup( + React.createElement( + IntlProvider, + { + locale, + messages: pickClientMessages(rawCatalog, 'productDetail'), + timeZone: 'Asia/Ho_Chi_Minh', + }, + React.createElement(PriceHistorySection, { + productName: 'iPhone 16 Pro Max', + history: history1871, + }) + ) + ); + const cardIdx = omittedOffersHtml.indexOf( + 'data-testid="omnibus-price-audit-card"' + ); + const cardEndIdx = omittedOffersHtml.indexOf('role="group"', cardIdx); + const omnibusCardHtml = omittedOffersHtml.slice(cardIdx, cardEndIdx); + assert.ok( + cardIdx >= 0 && cardEndIdx > cardIdx, + `${locale}: PriceHistorySection renders omnibus card when offers is omitted` + ); + assert.ok( + omnibusCardHtml.includes(formatPriceVnd(28_500_000, locale)), + `${locale}: Omnibus 30d prior floor uses in-stock 28.5M floor (${formatPriceVnd(28_500_000, locale)})` + ); + assert.equal( + omnibusCardHtml.includes(formatPriceVnd(21_500_000, locale)), + false, + `${locale}: Sold-out normal_price offer above currentMinPrice must not leak 21.5M into Omnibus card` + ); + assert.equal( + omnibusCardHtml.includes(formatPriceVnd(20_000_000, locale)), + false, + `${locale}: Discontinued normal_price offer at currentMinPrice must not leak 20.0M into Omnibus card` + ); + assert.ok( + omnibusCardHtml.includes( + 'data-testid="omnibus-cycle-signal" class="fw-bold mb-1 text-success"' + ), + `${locale}: 90d cycle renders green buy_now_floor instead of Wait polluted by sold-out history` + ); + + // Explicitly in-stock offer priced slightly below a stale stored minPrice + // stays eligible when `offers` is forwarded. + const forwardedOffersHtml = renderToStaticMarkup( + React.createElement( + IntlProvider, + { + locale, + messages: pickClientMessages(rawCatalog, 'productDetail'), + timeZone: 'Asia/Ho_Chi_Minh', + }, + React.createElement(PriceHistorySection, { + productName: 'iPhone 16 Pro Max', + history: { + ...history1871, + currentMinPrice: 27_500_000, + }, + offers: offers1871, + }) + ) + ); + const fwdCardIdx = forwardedOffersHtml.indexOf( + 'data-testid="omnibus-price-audit-card"' + ); + const fwdCardEndIdx = forwardedOffersHtml.indexOf( + 'role="group"', + fwdCardIdx + ); + const fwdCardHtml = forwardedOffersHtml.slice(fwdCardIdx, fwdCardEndIdx); + assert.ok( + fwdCardHtml.includes(formatPriceVnd(28_500_000, locale)), + `${locale}: Forwarded offers keeps explicitly in_stock 27.0M offer history even when stored minPrice is 27.5M` + ); + + // All real offers sold out (including missing-ID sold-out entry) alongside + // an in-stock sub-floor accessory/bait listing suppresses phantom Omnibus card + // even when cached currentMinPrice is still non-null. + const allSoldOutPlusBaitHtml = renderToStaticMarkup( + React.createElement( + IntlProvider, + { + locale, + messages: pickClientMessages(rawCatalog, 'productDetail'), + timeZone: 'Asia/Ho_Chi_Minh', + }, + React.createElement(PriceHistorySection, { + productName: 'iPhone 16 Pro Max', + history: history1871, + offers: [ + { + id: '', + product_id: ' ', + price_current: 28_000_000, + availability: 'out_of_stock', + }, + { + id: 'offer-in-stock-1871', + price_current: 27_000_000, + availability: 'discontinued', + }, + { + id: 'offer-subfloor-bait', + price_current: 500_000, + availability: 'in_stock', + }, + ], + }) + ) + ); + assert.equal( + allSoldOutPlusBaitHtml.includes('data-testid="omnibus-price-audit-card"'), + false, + `${locale}: Suppresses Omnibus card when only sold-out offers and sub-floor bait remain` + ); + } + + // Malformed non-empty `offers` array falls back cleanly to `byOffer` analyses, + // and `offers` entries with `availability: null` absent from `byOffer` but + // priced strictly below `currentMinPrice` are excluded from Omnibus floor. + { + const rawViCatalog = JSON.parse( + readFileSync(new URL('../../../locales/vi.json', import.meta.url), 'utf8') + ) as Record; + const malformedOffersHtml = renderToStaticMarkup( + React.createElement( + IntlProvider, + { + locale: 'vi', + messages: pickClientMessages(rawViCatalog, 'productDetail'), + timeZone: 'Asia/Ho_Chi_Minh', + }, + React.createElement(PriceHistorySection, { + productName: 'iPhone 16 Pro Max', + history: history1871, + offers: [null as never], + }) + ) + ); + const malCardStart = malformedOffersHtml.indexOf( + 'data-testid="omnibus-price-audit-card"' + ); + const malCardStop = malformedOffersHtml.indexOf( + 'role="group"', + malCardStart + ); + const malOmnibusCardHtml = malformedOffersHtml.slice( + malCardStart, + malCardStop + ); + assert.ok( + malCardStart >= 0 && + malOmnibusCardHtml.includes(formatPriceVnd(28_500_000, 'vi')) + ); + assert.equal( + malOmnibusCardHtml.includes(formatPriceVnd(21_500_000, 'vi')), + false + ); + + const unknownExtraOfferHtml = renderToStaticMarkup( + React.createElement( + IntlProvider, + { + locale: 'vi', + messages: pickClientMessages(rawViCatalog, 'productDetail'), + timeZone: 'Asia/Ho_Chi_Minh', + }, + React.createElement(PriceHistorySection, { + productName: 'iPhone 16 Pro Max', + history: { + ...history1871, + points: [ + ...history1871.points, + ...[35, 21, 7].map((d, idx) => ({ + id: 900 + idx, + product_id: 'offer-untracked-below-min', + merchant_name: 'Untracked Shop', + platform: 'shopee', + is_official: false, + price: 22_000_000, + price_original: null, + recorded_at: isoDaysAgo(d), + source: 'crawler', + })), + ], + }, + offers: [ + ...offers1871, + { + id: 'offer-untracked-below-min', + price_current: 22_000_000, + availability: null, + }, + ], + }) + ) + ); + const cardStart = unknownExtraOfferHtml.indexOf( + 'data-testid="omnibus-price-audit-card"' + ); + const cardStop = unknownExtraOfferHtml.indexOf('role="group"', cardStart); + assert.equal( + unknownExtraOfferHtml + .slice(cardStart, cardStop) + .includes(formatPriceVnd(22_000_000, 'vi')), + false + ); + } + + // Verify product detail route and ItemLazySizePanel forward `offers` to PriceHistorySection. + const pdvRouteSrc = readFileSync( + new URL('../../app/[locale]/smartphones/[slug]/page.tsx', import.meta.url), + 'utf8' + ); + const lazySizePanelSrc = readFileSync( + new URL( + '../../components/product/item/ItemLazySizePanel.tsx', + import.meta.url + ), + 'utf8' + ); + assert.match( + pdvRouteSrc, + / { + console.error(err); + process.exit(1); +}); diff --git a/apps/web/src/lib/omnibus-price-audit.ts b/apps/web/src/lib/omnibus-price-audit.ts index fba4d677..a636873a 100644 --- a/apps/web/src/lib/omnibus-price-audit.ts +++ b/apps/web/src/lib/omnibus-price-audit.ts @@ -81,6 +81,7 @@ export interface OmnibusAuditPointInput { export interface OmnibusReferenceOfferInput { readonly id?: string | null; + readonly product_id?: string | null; readonly price_current: number; readonly availability?: OfferAvailability | null; readonly implausiblyLow?: boolean | null; @@ -309,7 +310,13 @@ function buildOfferExclusionSets(params: { const inStockSized: { id: string; price_current: number }[] = []; const pricedAll: { rawId: string; id: string; price_current: number }[] = []; for (const off of safeRefOffers) { - const rawId = typeof off.id === 'string' ? off.id.trim() : ''; + const rawIdCandidate = + typeof off.id === 'string' && off.id.trim() + ? off.id + : typeof off.product_id === 'string' + ? off.product_id + : ''; + const rawId = rawIdCandidate.trim(); const id = normalizeOfferId(rawId) || rawId; const price = sanitizeOmnibusPriceVnd( off.price_current, diff --git a/apps/web/src/lib/rate-api.ts b/apps/web/src/lib/rate-api.ts index d45f871b..d392bddb 100644 --- a/apps/web/src/lib/rate-api.ts +++ b/apps/web/src/lib/rate-api.ts @@ -49,6 +49,7 @@ import { type OfferAvailability, toOfferAvailability, } from './product-market-stats'; +export type { OfferAvailability } from './product-market-stats'; export { computeWilsonLowerBound, evaluateReviewTrustAssessment, @@ -2162,6 +2163,7 @@ export interface OfferDiscountAnalysis { verdict: DiscountVerdictType; badge_label: string; explanation: string; + availability?: OfferAvailability; } export interface MasterProductPriceHistorySummary { @@ -2490,6 +2492,7 @@ export async function getMasterProductPriceHistory( let badgeLabel = 'Giá ổn định'; let explanation = `Giá bán hiện tại (${priceCurrent.toLocaleString('vi-VN')} ₫) khớp với mức trung vị lịch sử (${histMedian.toLocaleString('vi-VN')} ₫).`; + const offerAvailability = toOfferAvailability(off.availability); const offerUnavailable = isOfferUnavailable(off); if (priceOriginal && claimedDiscountPct >= 5) { // Case 1: Shop claims >= 8% discount, but current price is at or above historical median @@ -2545,6 +2548,7 @@ export async function getMasterProductPriceHistory( verdict, badge_label: badgeLabel, explanation, + ...(offerAvailability ? { availability: offerAvailability } : {}), }; } diff --git a/apps/web/src/lib/rate-domain.ts b/apps/web/src/lib/rate-domain.ts index a2cdb5fe..56ba31b2 100644 --- a/apps/web/src/lib/rate-domain.ts +++ b/apps/web/src/lib/rate-domain.ts @@ -49,6 +49,7 @@ export type { MerchantProfileDetail, MerchantRiskBreakdown, MerchantSummary, + OfferAvailability, OfferDiscountAnalysis, ParsedEcommerceUrl, PriceHistoryPoint, diff --git a/apps/web/src/server/rate/index.ts b/apps/web/src/server/rate/index.ts index c1430040..7b538350 100644 --- a/apps/web/src/server/rate/index.ts +++ b/apps/web/src/server/rate/index.ts @@ -460,24 +460,33 @@ export const getCachedMasterProductPriceHistory = cache( ? existingOffers.filter((o) => Boolean(o && typeof o === 'object')) : undefined; const offersKey = safeOffers - ? `offers:${safeOffers.length}:${safeOffers - .slice(0, 20) - .map((o) => { - const safeCur = - typeof o.price_current === 'number' && - Number.isFinite(o.price_current) && - o.price_current > 0 - ? Math.round(o.price_current) - : 0; - const safeOrig = - typeof o.price_original === 'number' && - Number.isFinite(o.price_original) && - o.price_original > 0 - ? Math.round(o.price_original) - : ''; - return `${sanitizeCachedEntityId(o.id)}:${safeCur}:${safeOrig}`; - }) - .join('|')}` + ? `offers:${safeOffers.length}:${createHash('sha256') + .update( + safeOffers + .map((o) => { + const safeCur = + typeof o.price_current === 'number' && + Number.isFinite(o.price_current) && + o.price_current > 0 + ? Math.round(o.price_current) + : 0; + const safeOrig = + typeof o.price_original === 'number' && + Number.isFinite(o.price_original) && + o.price_original > 0 + ? Math.round(o.price_original) + : ''; + const safeAvail = + o.availability === 'in_stock' || + o.availability === 'out_of_stock' || + o.availability === 'discontinued' + ? o.availability + : ''; + return `${sanitizeCachedEntityId(o.id)}:${safeCur}:${safeOrig}:${safeAvail}`; + }) + .join('|') + ) + .digest('hex')}` : 'offers:auto'; return withRateDataCache( async (id: string) => { diff --git a/apps/web/src/server/rate/item-page.ts b/apps/web/src/server/rate/item-page.ts index 4b7b696f..94c29e91 100644 --- a/apps/web/src/server/rate/item-page.ts +++ b/apps/web/src/server/rate/item-page.ts @@ -20,6 +20,7 @@ import type { RadarSignal } from '@/lib/deal-radar'; import { isOfferUnavailable, productMarketStats, + toOfferAvailability, } from '@/lib/product-market-stats'; import type { ProductSpecifications } from '@repo/shared-data'; import type { ItemSizePanelData } from '@/lib/item-size-panel'; @@ -109,7 +110,8 @@ const _getCachedUnknownByOffer = cache( .update( offers .map( - (o) => `${o.id}:${o.price_current}:${o.price_original ?? ''}` + (o) => + `${o.id}:${o.price_current}:${o.price_original ?? ''}:${toOfferAvailability(o.availability) ?? ''}` ) .join('|') )