diff --git a/.gitignore b/.gitignore index 3a4873ad..f61b0edf 100644 --- a/.gitignore +++ b/.gitignore @@ -66,6 +66,8 @@ packages/*/.env .cursor/ memory-bank/ mcp.json +!apps/web/src/app/.well-known/mcp.json/ +!apps/web/src/app/.well-known/mcp.json/** .cache .strapi-updater.json 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). +

+
+ + + + diff --git a/apps/web/locales/cs.json b/apps/web/locales/cs.json index ea5b02d3..70a26c0f 100644 --- a/apps/web/locales/cs.json +++ b/apps/web/locales/cs.json @@ -352,7 +352,44 @@ "trayRemoveAria": "Odebrat {name}", "quickToggleShortAdd": "Porovnat", "quickToggleShortSelected": "Přidáno", - "quickToggleShortLimit": "Max. 4" + "quickToggleShortLimit": "Max. 4", + "preset_default": "Vyvážený výchozí", + "preset_gaming": "Hraní her a výdrž", + "preset_camera": "Fotoaparát a vlog", + "preset_endurance": "Výdrž a odolnost", + "preset_value": "Nejlepší cena / výkon", + "preset_media": "Filmy a zábava", + "preset_study_work": "Studium a poznámky", + "preset_office": "Kancelář a mobilita", + "preset_creator": "Programování a grafika", + "preset_fitness": "Sport a zdraví", + "preset_smart_daily": "Chytré funkce a nošení", + "preset_audiophile": "Audiofilský poslech", + "preset_commute_anc": "Cestování a ANC", + "preset_calls_work": "Schůzky a hovory", + "weightCrit_performance": "Výkon", + "weightCrit_camera": "Fotoaparát", + "weightCrit_battery": "Baterie a nabíjení", + "weightCrit_display": "Displej", + "weightCrit_design": "Design a zpracování", + "weightCrit_value": "Poměr cena / výkon", + "weightCrit_sound": "Kvalita zvuku", + "weightCrit_software": "Software a příslušenství", + "weightCrit_keyboard": "Klávesnice a touchpad", + "weightCrit_thermals": "Chlazení a hlučnost", + "weightCrit_health": "Sledování zdraví", + "weightCrit_apps": "Aplikace a konektivita", + "weightCrit_anc": "Potlačení hluku", + "weightCrit_comfort": "Pohodlí při nošení", + "weightCrit_calls": "Mikrofon a hovory", + "resetWeightsBtn": "Obnovit výchozí", + "normalizedWeightsPrefix": "Normalizované váhy (100 %):", + "officialRateScoreLabel": "Oficiální skóre Rate.vn", + "yourCustomScoreLabel": "Vaše vlastní skóre", + "officialScoreKeepNote": "Oficiální skóre Rate.vn zůstává beze změny vedle vašeho vlastního skóre.", + "customWinnerSummary": "Podle {preset}: vede {winner} ({score}/5, náskok +{delta})", + "customWinnerSingle": "Podle {preset}: vede {winner} ({score}/5)", + "customWinnerTie": "Podle {preset}: vedoucí modely mají shodné skóre ({score}/5)" }, "leaderboard": { "criteriaSourceExpert": "Hodnocení kritérií od recenzentů nebo expertů", @@ -450,7 +487,42 @@ "categoryTabsAria": "Vyberte kategorii", "shortCamera": "Foto", "shortAnc": "ANC", - "expertScoreShort": "Expert {score}/10" + "expertScoreShort": "Expert {score}/10", + "preset_default": "Vyvážený výchozí", + "preset_gaming": "Hraní her a výdrž", + "preset_camera": "Fotoaparát a vlog", + "preset_endurance": "Výdrž a odolnost", + "preset_value": "Nejlepší cena / výkon", + "preset_media": "Filmy a zábava", + "preset_study_work": "Studium a poznámky", + "preset_office": "Kancelář a mobilita", + "preset_creator": "Programování a grafika", + "preset_fitness": "Sport a zdraví", + "preset_smart_daily": "Chytré funkce a nošení", + "preset_audiophile": "Audiofilský poslech", + "preset_commute_anc": "Cestování a ANC", + "preset_calls_work": "Schůzky a hovory", + "weightCrit_performance": "Výkon", + "weightCrit_camera": "Fotoaparát", + "weightCrit_battery": "Baterie a nabíjení", + "weightCrit_display": "Displej", + "weightCrit_design": "Design a zpracování", + "weightCrit_value": "Poměr cena / výkon", + "weightCrit_sound": "Kvalita zvuku", + "weightCrit_software": "Software a příslušenství", + "weightCrit_keyboard": "Klávesnice a touchpad", + "weightCrit_thermals": "Chlazení a hlučnost", + "weightCrit_health": "Sledování zdraví", + "weightCrit_apps": "Aplikace a konektivita", + "weightCrit_anc": "Potlačení hluku", + "weightCrit_comfort": "Pohodlí při nošení", + "weightCrit_calls": "Mikrofon a hovory", + "customWeightsBtn": "Vlastní váhy", + "resetWeightsBtn": "Obnovit výchozí", + "normalizedWeightsPrefix": "Normalizované váhy (100 %):", + "officialRateScoreLabel": "Oficiální skóre Rate.vn", + "yourCustomScoreLabel": "Vaše vlastní skóre", + "officialScoreKeepNote": "Oficiální skóre Rate.vn zůstává na každém řádku beze změny." }, "reviews": { "reviewsShowMore": "Zobrazit {count, plural, one {# další recenzi} few {# další recenze} other {# dalších recenzí}}", @@ -822,7 +894,16 @@ "radarBadgeSpread": "📊 +{pct} % rozdíl mezi e-shopy", "radarNoGenuine": "V této kategorii nejsou žádné nabídky pod tržním mediánem.", "radarNoTraps": "V této kategorii nebyly zjištěny žádné navýšené původní ceny.", - "showMoreDeals": "Zobrazit další nabídky ({count, plural, one {zbývá #} few {zbývají #} other {zbývá #}})" + "showMoreDeals": "Zobrazit další nabídky ({count, plural, one {zbývá #} few {zbývají #} other {zbývá #}})", + "campaignFilterLabel": "Filtr cenových signálů:", + "campaignAll": "Všechna zařízení", + "campaignGenuineDrops": "Ověřeně pod mediánem ({count})", + "campaignInflatedTraps": "Varování: navýšené přeškrtnuté ceny ({count})", + "campaignEmptyGenuine": "Žádné zařízení s ověřenou cenou pod tržním mediánem neodpovídá zvoleným filtrům.", + "campaignEmptyTraps": "Ve zvolených filtrech nebyly zjištěny žádné uměle navýšené přeškrtnuté ceny.", + "campaignResetBtn": "Zobrazit všechna zařízení", + "campaignCardTrapNote": "Varování na {platform}: přeškrtnutá cena {claimed} (+{pct} % nad mediánem) - nakupte v nejlevnějším ověřeném obchodě", + "campaignCardGenuineNote": "Pod mediánem na {platform}: úspora {savings} (-{pct} % oproti mediánu obchodů)" }, "inspect": { "metaTitle": "Kontrola odkazu na produkt a falešných slev | Rate.vn", @@ -903,7 +984,9 @@ "errInspectFailed": "Tento odkaz se nepodařilo zkontrolovat.", "errNetwork": "Chyba sítě, zkuste to znovu.", "loading": "Načítání...", - "reviewRiskNoData": "nedostatek dat" + "reviewRiskNoData": "nedostatek dat", + "omnibusScopeListing": "Kontrola vybrané nabídky: {merchant} ({platform})", + "omnibusScopeProduct": "Kontrola nejnižší ověřené ceny skladem napříč obchody" }, "merchants": { "dirMetaTitle": "Důvěryhodnost prodejců | Rate.vn", @@ -1221,6 +1304,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", @@ -1545,6 +1630,33 @@ "connectivity": "Komunikace a konektivita", "battery": "Baterie a nabíjení", "misc": "Senzory, SAR a předpisy" + }, + "btnMcpDocs": "MCP a /llms.txt pro AI agenty", + "authPublicMcp": "Veřejné pouze pro čtení (limit na IP)", + "cacheNoStoreMcp": "no-store (čtení přes withRateDataCache)", + "ep20Params": "Tělo JSON-RPC 2.0: initialize, ping, tools/list, tools/call (<= 16 KB)", + "ep20Summary": "Bezstavový MCP server přes HTTP s 5 čtecími nástroji napříč 22 obchody ve Vietnamu a povinnou citací rate.vn.", + "ep21Params": "Bez parametrů", + "ep21Summary": "Popisovač automatického zjištění MCP serveru (verze protokolu 2025-06-18, adresa HTTP, limity požadavků a seznam nástrojů).", + "ep22Params": "Bez parametrů", + "ep22Summary": "Stručný přehled v Markdownu (/llms.txt) pro AI asistenty a čtečky webu o 22 obchodech, 5 kategoriích, 6osém modelu důvěry recenzí a nástrojích MCP.", + "mcpBadge": "Protokol MCP (2025-06-18)", + "mcpTitle": "MCP server Rate.vn a /llms.txt pro AI agenty", + "mcpSubtitle": "Připojte AI asistenty, IDE agenty, ChatGPT nebo DOSClaw přímo k ověřeným cenám z 22 obchodů ve Vietnamu a 6osému hodnocení důvěry recenzí bez API klíče.", + "mcpBtnLlmsTxt": "Otevřít /llms.txt", + "mcpBtnWellKnown": "Zobrazit /.well-known/mcp.json", + "mcpGuardNote": "Bezpečnostní limity pouze pro čtení: JSON-RPC 2.0 přes POST /api/mcp, tělo <= 16 KB, max. 10 položek na volání, klouzavý limit podle IP (60 požadavků/min, 30 kontrol URL/min) a povinné pole canonical_citation_url s časovým razítkem observed_at u každé položky.", + "mcpToolsHeading": "5 čtecích nástrojů MCP", + "mcpReadOnlyBadge": "Pouze čtení", + "mcpConfigHeading": "Rychlé připojení (.mcp.json / .cursor/mcp.json / claude_desktop_config.json / DOSClaw)", + "mcpClientConfigLabel": ".mcp.json / .cursor/mcp.json / claude_desktop_config.json / DOSClaw", + "mcpCurlConfigLabel": "JSON-RPC 2.0 přes HTTP (POST /api/mcp)", + "mcpTools": { + "search_verified_catalog": "Hledání v 5 technologických kategoriích s filtry značky a ceny ve VND (max. 10 položek, bez vyprodaných a návnadových nabídek).", + "get_22_store_offers_and_price_truth": "Vrátí ověřené nabídky skladem z 22 obchodů, historické minimum a medián, bayesovské skóre, 6osou důvěru recenzí a příznaky falešných slev.", + "compare_devices_by_use_case": "Porovná 2 až 4 modely stejné kategorie v 10 skupinách parametrů, minimálních cenách a 5 kritériích s volitelnými vlastními vahami.", + "audit_listing_url": "Prověří URL nabídky z 22 podporovaných obchodů, spáruje katalogový model a vrátí 5stupňový verdikt ceny i riziko prodejce.", + "get_genuine_deals": "Vypíše ověřené nabídky pod mediánem a cenová minima napříč obchody (limit <= 10) s filtry kategorie, platformy a rozpočtu." } }, "staticPages": { @@ -2072,7 +2184,32 @@ "explainSuspicious": "Inzerovaná sleva (-{claimed} %) je výrazně vyšší než skutečná sleva (-{real} %) podle historie cen ({median}).", "explainGenuine": "Aktuální cena je o {pct} % nižší než historický medián ({median}).", "explainHistoricLow": "Nejnižší zaznamenaná cena ({current}, maximum {max}).", - "explainNormal": "Aktuální cena ({current}) odpovídá historickému mediánu ({median})." + "explainNormal": "Aktuální cena ({current}) odpovídá historickému mediánu ({median}).", + "oTitle": "Kontrola 30d minima (EU) a 90d cyklus", + "oOk": "30denní minimum EU", + "oPart": "Sledované minimum ({days} d)", + "oGap": "Výpadek v 30d záznamu", + "oPend": "Sběr historie (pod 30 dní)", + "oFlr": "Zaznamenané minimum", + "oCur": "Prodejní a přeškrtnutá cena", + "oClaim": "-{pct} % z {original}", + "oNoOrig": "Bez přeškrtnuté ceny", + "oMarkup": "Přeškrtnutá o {markup} (+{pct} %) nad minimem", + "oAlign": "Nepřesahuje předchozí minimum", + "oDrop": "Reálný pokles: -{pct} % (-{amount})", + "oFake": "Falešná sleva: +{amount} (+{pct} %) vs 30d min", + "oUp": "Nad minimem: +{pct} % (+{amount})", + "oFlat": "Shodné s minimem (0 %)", + "oNeed": "Málo dnů měření", + "oNoteP": "{days}/30 d: 30d EU nepotvrzeno", + "oNoteG": "Výpadek v 30d okně: EU nevydáno", + "oCyc": "90d cyklus (koupit, či počkat)", + "oBuy": "90d minimum (nejnižších {pct} %) - koupit", + "oFair": "Běžné pásmo ({pct} % 90d cyklu)", + "oWait": "O {gap} nad 90d minimem - počkat", + "oRng": "Rozpětí 90 d: {low} - {high}", + "oCycP": "Sběr 90d cyklu", + "oCycN": "{points}/5 dnů za {days} d (min. 14 d)" }, "analyzerCopy": { "reasonAuthentic": "Podrobná, platná recenze od skutečného uživatele.", diff --git a/apps/web/locales/en.json b/apps/web/locales/en.json index 4fb58a61..11e9250a 100644 --- a/apps/web/locales/en.json +++ b/apps/web/locales/en.json @@ -352,7 +352,44 @@ "trayRemoveAria": "Remove {name}", "quickToggleShortAdd": "Compare", "quickToggleShortSelected": "Added", - "quickToggleShortLimit": "Max 4" + "quickToggleShortLimit": "Max 4", + "preset_default": "Balanced default", + "preset_gaming": "Gaming & battery", + "preset_camera": "Camera & creator", + "preset_endurance": "Endurance & durability", + "preset_value": "Value-first", + "preset_media": "Media & entertainment", + "preset_study_work": "Study & productivity", + "preset_office": "Office & portability", + "preset_creator": "Coding & creator", + "preset_fitness": "Fitness & health", + "preset_smart_daily": "Smart apps & daily wear", + "preset_audiophile": "Audiophile sound", + "preset_commute_anc": "ANC & commute", + "preset_calls_work": "Meetings & calls", + "weightCrit_performance": "Performance", + "weightCrit_camera": "Camera", + "weightCrit_battery": "Battery and charging", + "weightCrit_display": "Display", + "weightCrit_design": "Design and build", + "weightCrit_value": "Value for money", + "weightCrit_sound": "Sound quality", + "weightCrit_software": "Software and accessories", + "weightCrit_keyboard": "Keyboard and touchpad", + "weightCrit_thermals": "Thermals and noise", + "weightCrit_health": "Health tracking", + "weightCrit_apps": "Apps and connectivity", + "weightCrit_anc": "Noise cancelling", + "weightCrit_comfort": "Comfort", + "weightCrit_calls": "Microphone and calls", + "resetWeightsBtn": "Reset to default", + "normalizedWeightsPrefix": "Normalized weights (100%):", + "officialRateScoreLabel": "Rate.vn score", + "yourCustomScoreLabel": "Your custom score", + "officialScoreKeepNote": "The official Rate.vn score stays unchanged beside your custom score.", + "customWinnerSummary": "Under {preset}: {winner} leads ({score}/5, +{delta} ahead)", + "customWinnerSingle": "Under {preset}: {winner} leads ({score}/5)", + "customWinnerTie": "Under {preset}: leading models are tied ({score}/5)" }, "leaderboard": { "criteriaSourceExpert": "Criterion scores from reviewers or experts", @@ -450,7 +487,42 @@ "categoryTabsAria": "Choose a category", "shortCamera": "Camera", "shortAnc": "ANC", - "expertScoreShort": "Expert {score}/10" + "expertScoreShort": "Expert {score}/10", + "preset_default": "Balanced default", + "preset_gaming": "Gaming & battery", + "preset_camera": "Camera & creator", + "preset_endurance": "Endurance & durability", + "preset_value": "Value-first", + "preset_media": "Media & entertainment", + "preset_study_work": "Study & productivity", + "preset_office": "Office & portability", + "preset_creator": "Coding & creator", + "preset_fitness": "Fitness & health", + "preset_smart_daily": "Smart apps & daily wear", + "preset_audiophile": "Audiophile sound", + "preset_commute_anc": "ANC & commute", + "preset_calls_work": "Meetings & calls", + "weightCrit_performance": "Performance", + "weightCrit_camera": "Camera", + "weightCrit_battery": "Battery and charging", + "weightCrit_display": "Display", + "weightCrit_design": "Design and build", + "weightCrit_value": "Value for money", + "weightCrit_sound": "Sound quality", + "weightCrit_software": "Software and accessories", + "weightCrit_keyboard": "Keyboard and touchpad", + "weightCrit_thermals": "Thermals and noise", + "weightCrit_health": "Health tracking", + "weightCrit_apps": "Apps and connectivity", + "weightCrit_anc": "Noise cancelling", + "weightCrit_comfort": "Comfort", + "weightCrit_calls": "Microphone and calls", + "customWeightsBtn": "Custom weights", + "resetWeightsBtn": "Reset to default", + "normalizedWeightsPrefix": "Normalized weights (100%):", + "officialRateScoreLabel": "Rate.vn score", + "yourCustomScoreLabel": "Your custom score", + "officialScoreKeepNote": "The official Rate.vn score stays unchanged on every product row." }, "reviews": { "reviewsShowMore": "Show {count, plural, one {# more review} other {# more reviews}}", @@ -822,7 +894,16 @@ "radarBadgeSpread": "📊 +{pct}% cross-platform spread", "radarNoGenuine": "No offers below the market median in this category.", "radarNoTraps": "No inflated list prices detected in this category.", - "showMoreDeals": "Show more deals ({count} left)" + "showMoreDeals": "Show more deals ({count} left)", + "campaignFilterLabel": "Price signal filter:", + "campaignAll": "All devices", + "campaignGenuineDrops": "Verified below median ({count})", + "campaignInflatedTraps": "Inflated list-price alerts ({count})", + "campaignEmptyGenuine": "No devices with verified below-median selling prices match your current filters.", + "campaignEmptyTraps": "No inflated strikethrough list-price alerts match your current filters.", + "campaignResetBtn": "Show all devices", + "campaignCardTrapNote": "Alert on {platform}: claimed list price {claimed} (+{pct}% vs median) - compare stores for the lowest verified price", + "campaignCardGenuineNote": "Below median on {platform}: save {savings} (-{pct}% vs cross-store median)" }, "inspect": { "metaTitle": "Check a product link and fake discounts | Rate.vn", @@ -903,7 +984,9 @@ "errInspectFailed": "Could not check this link.", "errNetwork": "Network error, please try again.", "loading": "Loading...", - "reviewRiskNoData": "not enough data" + "reviewRiskNoData": "not enough data", + "omnibusScopeListing": "Checking matched listing: {merchant} ({platform})", + "omnibusScopeProduct": "Checking lowest verified in-stock price across tracked stores" }, "merchants": { "dirMetaTitle": "Seller trust directory | Rate.vn", @@ -1221,6 +1304,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", @@ -1545,6 +1630,33 @@ "connectivity": "Comms & connectivity", "battery": "Battery & charging", "misc": "Sensors, SAR & regulatory" + }, + "btnMcpDocs": "MCP & /llms.txt for AI agents", + "authPublicMcp": "Public read-only (per-IP rate limit)", + "cacheNoStoreMcp": "no-store (withRateDataCache BFF)", + "ep20Params": "Body JSON-RPC 2.0: initialize, ping, tools/list, tools/call (<= 16 KB)", + "ep20Summary": "Stateless streamable HTTP MCP server exposing 5 read-only tools across 22 stores in Vietnam with mandatory rate.vn citations.", + "ep21Params": "No parameters", + "ep21Summary": "Self-hosted MCP server discovery descriptor (protocol version 2025-06-18, streamable HTTP endpoint, rate limits and tool list).", + "ep22Params": "No parameters", + "ep22Summary": "Concise Markdown context guide (/llms.txt) for AI assistants and web readers covering 22 retail platforms, 5 categories, 6-axis review trust and MCP tools.", + "mcpBadge": "MCP protocol (2025-06-18)", + "mcpTitle": "Rate.vn MCP server & /llms.txt for AI agents", + "mcpSubtitle": "Connect AI assistants, IDE agents, ChatGPT or DOSClaw directly to verified 22-store prices in Vietnam and 6-axis review trust with zero API keys.", + "mcpBtnLlmsTxt": "Open /llms.txt", + "mcpBtnWellKnown": "View /.well-known/mcp.json", + "mcpGuardNote": "Read-only guardrails: JSON-RPC 2.0 over POST /api/mcp, body <= 16 KB, max 10 items per call, per-IP sliding-window rate limit (60 req/min, 30 URL audits/min), and mandatory canonical_citation_url + observed_at provenance on every item.", + "mcpToolsHeading": "5 read-only MCP tools", + "mcpReadOnlyBadge": "Read-only", + "mcpConfigHeading": "Quick connect (.mcp.json / .cursor/mcp.json / claude_desktop_config.json / DOSClaw)", + "mcpClientConfigLabel": ".mcp.json / .cursor/mcp.json / claude_desktop_config.json / DOSClaw", + "mcpCurlConfigLabel": "JSON-RPC 2.0 over HTTP (POST /api/mcp)", + "mcpTools": { + "search_verified_catalog": "Search across 5 tech categories with brand and VND price bounds (max 10 items, bait and sold-out listings excluded).", + "get_22_store_offers_and_price_truth": "Fetch verified in-stock offers across 22 stores, historical floor/median prices, Bayesian rating, 6-axis review trust and fake-sale flags.", + "compare_devices_by_use_case": "Compare 2 to 4 same-category slugs side-by-side across 10 spec groups, floor prices and 5 criteria with optional custom weights.", + "audit_listing_url": "Inspect a marketplace listing URL across the 22 supported platforms for catalog match, 5-level price verdict and seller risk scores.", + "get_genuine_deals": "List verified below-median and multi-store floor deals (limit <= 10) with optional category, platform and budget filters." } }, "staticPages": { @@ -2072,7 +2184,32 @@ "explainSuspicious": "The advertised discount (-{claimed}%) is well above the real discount (-{real}%) against the price history ({median}).", "explainGenuine": "The current price is {pct}% below the historical median ({median}).", "explainHistoricLow": "At the lowest price recorded ({current}, against a high of {max}).", - "explainNormal": "The current price ({current}) matches the historical median ({median})." + "explainNormal": "The current price ({current}) matches the historical median ({median}).", + "oTitle": "30-day EU floor check and 90-day cycle", + "oOk": "30-day EU prior floor", + "oPart": "{days}-day observed floor", + "oGap": "Gapped log (30d incomplete)", + "oPend": "Collecting history (under 30d)", + "oFlr": "Observed prior floor", + "oCur": "Selling vs list price", + "oClaim": "-{pct}% from {original}", + "oNoOrig": "No strikethrough price", + "oMarkup": "List price +{markup} (+{pct}%) above floor", + "oAlign": "List price within prior floor", + "oDrop": "Real drop: -{pct}% (-{amount})", + "oFake": "Fake sale: +{amount} (+{pct}%) vs 30d floor", + "oUp": "Above floor: +{pct}% (+{amount})", + "oFlat": "Matches prior floor (0%)", + "oNeed": "Need multi-day history", + "oNoteP": "{days}/30d observed: EU 30d uncertified", + "oNoteG": "Gap in 30d window: EU status withheld", + "oCyc": "90-day cycle (buy or wait)", + "oBuy": "90d floor (lowest {pct}%) - buy now", + "oFair": "Fair range ({pct}% of 90d cycle)", + "oWait": "Above 90d low by +{gap} - wait", + "oRng": "90d range: {low} - {high}", + "oCycP": "Collecting 90-day cycle", + "oCycN": "{points}/5 days across {days}d (14d min)" }, "analyzerCopy": { "reasonAuthentic": "Detailed, valid review from a real user.", diff --git a/apps/web/locales/vi.json b/apps/web/locales/vi.json index 72f4ea0e..80ae55d8 100644 --- a/apps/web/locales/vi.json +++ b/apps/web/locales/vi.json @@ -352,7 +352,44 @@ "trayRemoveAria": "Xóa {name}", "quickToggleShortAdd": "So sánh", "quickToggleShortSelected": "Đã chọn", - "quickToggleShortLimit": "Tối đa 4" + "quickToggleShortLimit": "Tối đa 4", + "preset_default": "Cân bằng mặc định", + "preset_gaming": "Cày game & pin trâu", + "preset_camera": "Nhiếp ảnh & quay vlog", + "preset_endurance": "Bền bỉ & thực dụng", + "preset_value": "Đáng tiền nhất (P/P)", + "preset_media": "Xem phim & giải trí", + "preset_study_work": "Học tập & ghi chú", + "preset_office": "Văn phòng & di động", + "preset_creator": "Lập trình & đồ họa nặng", + "preset_fitness": "Thể thao & sức khỏe", + "preset_smart_daily": "Đeo hằng ngày & tiện ích", + "preset_audiophile": "Nghe nhạc chuyên sâu", + "preset_commute_anc": "Đi làm & chống ồn ANC", + "preset_calls_work": "Họp online & đàm thoại", + "weightCrit_performance": "Hiệu năng", + "weightCrit_camera": "Camera", + "weightCrit_battery": "Pin và sạc", + "weightCrit_display": "Màn hình", + "weightCrit_design": "Thiết kế và độ bền", + "weightCrit_value": "Đáng tiền", + "weightCrit_sound": "Chất âm", + "weightCrit_software": "Phần mềm và phụ kiện", + "weightCrit_keyboard": "Bàn phím và touchpad", + "weightCrit_thermals": "Tản nhiệt và độ ồn", + "weightCrit_health": "Theo dõi sức khỏe", + "weightCrit_apps": "Ứng dụng và kết nối", + "weightCrit_anc": "Chống ồn", + "weightCrit_comfort": "Đeo thoải mái", + "weightCrit_calls": "Mic và gọi", + "resetWeightsBtn": "Đặt lại mặc định", + "normalizedWeightsPrefix": "Trọng số chuẩn hóa (100%):", + "officialRateScoreLabel": "Điểm chuẩn Rate.vn", + "yourCustomScoreLabel": "Điểm theo trọng số bạn chọn", + "officialScoreKeepNote": "Điểm chuẩn Rate.vn luôn giữ nguyên bên cạnh điểm theo trọng số bạn chọn.", + "customWinnerSummary": "Theo {preset}: {winner} dẫn đầu ({score}/5, hơn +{delta})", + "customWinnerSingle": "Theo {preset}: {winner} dẫn đầu ({score}/5)", + "customWinnerTie": "Theo {preset}: các mẫu dẫn đầu ngang điểm ({score}/5)" }, "leaderboard": { "criteriaSourceExpert": "Điểm tiêu chí từ người review hoặc chuyên gia", @@ -450,7 +487,42 @@ "categoryTabsAria": "Chọn ngành hàng", "shortCamera": "Camera", "shortAnc": "Chống ồn", - "expertScoreShort": "Chuyên gia {score}/10" + "expertScoreShort": "Chuyên gia {score}/10", + "preset_default": "Cân bằng mặc định", + "preset_gaming": "Cày game & pin trâu", + "preset_camera": "Nhiếp ảnh & quay vlog", + "preset_endurance": "Bền bỉ & thực dụng", + "preset_value": "Đáng tiền nhất (P/P)", + "preset_media": "Xem phim & giải trí", + "preset_study_work": "Học tập & ghi chú", + "preset_office": "Văn phòng & di động", + "preset_creator": "Lập trình & đồ họa nặng", + "preset_fitness": "Thể thao & sức khỏe", + "preset_smart_daily": "Đeo hằng ngày & tiện ích", + "preset_audiophile": "Nghe nhạc chuyên sâu", + "preset_commute_anc": "Đi làm & chống ồn ANC", + "preset_calls_work": "Họp online & đàm thoại", + "weightCrit_performance": "Hiệu năng", + "weightCrit_camera": "Camera", + "weightCrit_battery": "Pin và sạc", + "weightCrit_display": "Màn hình", + "weightCrit_design": "Thiết kế và độ bền", + "weightCrit_value": "Đáng tiền", + "weightCrit_sound": "Chất âm", + "weightCrit_software": "Phần mềm và phụ kiện", + "weightCrit_keyboard": "Bàn phím và touchpad", + "weightCrit_thermals": "Tản nhiệt và độ ồn", + "weightCrit_health": "Theo dõi sức khỏe", + "weightCrit_apps": "Ứng dụng và kết nối", + "weightCrit_anc": "Chống ồn", + "weightCrit_comfort": "Đeo thoải mái", + "weightCrit_calls": "Mic và gọi", + "customWeightsBtn": "Tùy chỉnh trọng số", + "resetWeightsBtn": "Đặt lại mặc định", + "normalizedWeightsPrefix": "Trọng số chuẩn hóa (100%):", + "officialRateScoreLabel": "Điểm chuẩn Rate.vn", + "yourCustomScoreLabel": "Điểm theo trọng số bạn chọn", + "officialScoreKeepNote": "Điểm chuẩn Rate.vn luôn giữ nguyên ở từng dòng sản phẩm." }, "reviews": { "reviewsShowMore": "Xem thêm {count} đánh giá", @@ -822,7 +894,16 @@ "radarBadgeSpread": "📊 Lệch giá +{pct}% đa sàn", "radarNoGenuine": "Chưa có nơi bán nào có giá thấp hơn trung vị thị trường trong danh mục này.", "radarNoTraps": "Chưa phát hiện giá gốc bị nâng khống trong danh mục này.", - "showMoreDeals": "Xem thêm deal (còn {count})" + "showMoreDeals": "Xem thêm deal (còn {count})", + "campaignFilterLabel": "Lọc tín hiệu giá:", + "campaignAll": "Tất cả thiết bị", + "campaignGenuineDrops": "Giá bán dưới trung vị ({count})", + "campaignInflatedTraps": "Cảnh báo kê cao giá gốc ({count})", + "campaignEmptyGenuine": "Chưa có thiết bị nào có giá bán xác thực thấp hơn trung vị thị trường trong bộ lọc hiện tại.", + "campaignEmptyTraps": "Không phát hiện tin bán treo giá gạch ngang cao bất thường trong bộ lọc hiện tại.", + "campaignResetBtn": "Xem lại tất cả thiết bị", + "campaignCardTrapNote": "Cảnh báo trên {platform}: kê giá gạch ngang {claimed} (+{pct}% so trung vị) - hãy đối chiếu để mua ở nơi bán thấp nhất", + "campaignCardGenuineNote": "Giá tốt tại {platform}: tiết kiệm {savings} (-{pct}% so trung vị các sàn)" }, "inspect": { "metaTitle": "Kiểm tra link sản phẩm và giảm giá ảo | Rate.vn", @@ -903,7 +984,9 @@ "errInspectFailed": "Không kiểm tra được link này.", "errNetwork": "Lỗi mạng, vui lòng thử lại.", "loading": "Đang tải...", - "reviewRiskNoData": "chưa đủ dữ liệu" + "reviewRiskNoData": "chưa đủ dữ liệu", + "omnibusScopeListing": "Đối chiếu trực tiếp tin bán: {merchant} ({platform})", + "omnibusScopeProduct": "Đối chiếu mức giá thấp nhất đang còn hàng của mẫu máy này" }, "merchants": { "dirMetaTitle": "Độ tin cậy gian hàng trên các sàn | Rate.vn", @@ -1221,6 +1304,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ố", @@ -1545,6 +1630,33 @@ "connectivity": "Kết nối", "battery": "Pin và sạc", "misc": "Cảm biến, SAR và quy chuẩn" + }, + "btnMcpDocs": "MCP & /llms.txt cho AI agent", + "authPublicMcp": "Công khai chỉ đọc (giới hạn theo IP)", + "cacheNoStoreMcp": "no-store (đọc qua withRateDataCache)", + "ep20Params": "Body JSON-RPC 2.0: initialize, ping, tools/list, tools/call (<= 16 KB)", + "ep20Summary": "Máy chủ MCP qua HTTP không trạng thái, cung cấp 5 công cụ chỉ đọc trên 22 sàn tại Việt Nam kèm trích dẫn nguồn rate.vn.", + "ep21Params": "Không có tham số", + "ep21Summary": "Tệp mô tả tự động nhận diện máy chủ MCP (phiên bản giao thức 2025-06-18, địa chỉ HTTP, giới hạn tần suất và danh sách công cụ).", + "ep22Params": "Không có tham số", + "ep22Summary": "Tài liệu ngữ cảnh Markdown gọn nhẹ (/llms.txt) cho trợ lý AI và trình đọc web về 22 sàn bán lẻ, 5 ngành hàng, mô hình tin cậy đánh giá 6 trục và bộ công cụ MCP.", + "mcpBadge": "Giao thức MCP (2025-06-18)", + "mcpTitle": "Máy chủ MCP của Rate.vn & /llms.txt cho AI agent", + "mcpSubtitle": "Kết nối trực tiếp trợ lý AI, trình sửa mã IDE, ChatGPT hoặc DOSClaw với giá thật từ 22 sàn tại Việt Nam và mô hình lọc đánh giá 6 trục mà không cần khóa API.", + "mcpBtnLlmsTxt": "Mở /llms.txt", + "mcpBtnWellKnown": "Xem /.well-known/mcp.json", + "mcpGuardNote": "Chốt an toàn chỉ đọc: JSON-RPC 2.0 qua POST /api/mcp, kích thước body <= 16 KB, tối đa 10 kết quả mỗi lần gọi, giới hạn tần suất theo IP (60 yêu cầu/phút, 30 lần kiểm tra URL/phút), bắt buộc đính kèm canonical_citation_url và mốc thời gian observed_at trên mọi mục trả về.", + "mcpToolsHeading": "5 công cụ MCP chỉ đọc", + "mcpReadOnlyBadge": "Chỉ đọc", + "mcpConfigHeading": "Cấu hình kết nối nhanh (.mcp.json / .cursor/mcp.json / claude_desktop_config.json / DOSClaw)", + "mcpClientConfigLabel": ".mcp.json / .cursor/mcp.json / claude_desktop_config.json / DOSClaw", + "mcpCurlConfigLabel": "JSON-RPC 2.0 qua HTTP (POST /api/mcp)", + "mcpTools": { + "search_verified_catalog": "Tìm kiếm trên 5 ngành hàng công nghệ theo hãng và khoảng giá VNĐ (tối đa 10 mục, đã loại tin hết hàng và giá mồi).", + "get_22_store_offers_and_price_truth": "Lấy danh sách nơi bán còn hàng trên 22 sàn, giá đáy và trung vị lịch sử, điểm Bayes, độ tin cậy đánh giá 6 trục và cờ giảm giá ảo.", + "compare_devices_by_use_case": "So sánh trực tiếp 2 đến 4 mẫu máy cùng ngành hàng trên 10 nhóm thông số, giá đáy đa sàn và 5 tiêu chí kèm trọng số tùy chỉnh.", + "audit_listing_url": "Kiểm tra đường dẫn tin bán trên 22 sàn được hỗ trợ để ghép mẫu máy chuẩn, chấm kết luận giá 5 mức và điểm rủi ro người bán.", + "get_genuine_deals": "Liệt kê các deal dưới giá trung vị và chạm đáy đa sàn đã kiểm chứng (tối đa 10 mục), lọc theo ngành hàng, sàn và ngân sách." } }, "staticPages": { @@ -2072,7 +2184,32 @@ "explainSuspicious": "Mức giảm công bố (-{claimed}%) cao hơn đáng kể so với mức giảm thực tế (-{real}%) khi đối chiếu lịch sử giá ({median}).", "explainGenuine": "Giá hiện tại thấp hơn {pct}% so với mức trung vị lịch sử ({median}).", "explainHistoricLow": "Đang ở vùng giá thấp nhất ghi nhận được ({current} so với đỉnh {max}).", - "explainNormal": "Giá bán hiện tại ({current}) khớp với mức trung vị lịch sử ({median})." + "explainNormal": "Giá bán hiện tại ({current}) khớp với mức trung vị lịch sử ({median}).", + "oTitle": "Đối chiếu đáy giá 30 ngày (EU) và chu kỳ 90 ngày", + "oOk": "Đáy 30 ngày chuẩn EU", + "oPart": "Đáy quan sát {days} ngày", + "oGap": "Ngắt quãng (chưa đủ 30 ngày)", + "oPend": "Đang tích lũy (dưới 30 ngày)", + "oFlr": "Đáy quan sát trước đó", + "oCur": "Giá bán và giá gạch ngang", + "oClaim": "-{pct}% từ {original}", + "oNoOrig": "Không treo giá gạch ngang", + "oMarkup": "Giá gốc cao hơn đáy +{markup} (+{pct}%)", + "oAlign": "Giá gốc không vượt đáy trước đó", + "oDrop": "Giảm thật: -{pct}% (-{amount})", + "oFake": "Giảm ảo: so với đáy 30d +{amount} (+{pct}%)", + "oUp": "Cao hơn đáy: +{pct}% (+{amount})", + "oFlat": "Bằng đáy trước đó (0%)", + "oNeed": "Chưa đủ ngày đo trước đó", + "oNoteP": "Mới có {days}/30 ngày: chưa chứng nhận EU", + "oNoteG": "Ngắt quãng 30 ngày: chưa kết luận EU", + "oCyc": "Chu kỳ 90 ngày (mua hay chờ)", + "oBuy": "Đáy 90d (nhóm {pct}% thấp nhất) - mua ngay", + "oFair": "Giá hợp lý (mức {pct}% chu kỳ 90d)", + "oWait": "Cao hơn đáy 90d +{gap} - chờ giảm", + "oRng": "Biên độ 90d: {low} - {high}", + "oCycP": "Đang tích lũy chu kỳ 90d", + "oCycN": "{points}/5 ngày đo trong {days}d (cần 14d)" }, "analyzerCopy": { "reasonAuthentic": "Đánh giá chi tiết, hợp lệ từ người dùng thực tế.", diff --git a/apps/web/package.json b/apps/web/package.json index 830346b2..27165a49 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -8,7 +8,7 @@ "lint": "eslint . --max-warnings 0", "preview": "next build && next start", "start": "next start", - "test": "pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/server/rate/__tests__/core-rate-architecture.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/server/rate/__tests__/item-model.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/server/rate/__tests__/item-directory.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/server/rate/__tests__/compare-selection.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/app/api/v1/rate/__tests__/write-paths.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/app/api/v1/rate/__tests__/spec-scope.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/app/api/v1/rate/__tests__/versus-parity.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/app/api/v1/rate/__tests__/item-fields.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/logger.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/review-display.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/review-form-v2.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/review-value-display.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/concurrency.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/merchant-profile-reads.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/merchant-review-risk.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/item-directory.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/home-deals-item-grouping.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/watchlist-sizes.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/item-compare.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/product-variant-links.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/compare-params.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/catalog-listing.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/discount-verdict-copy.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/product-detail-copy.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/product-competitors.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/analyzer-copy.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/sold-count.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/content-lang.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/image-url.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/client-messages.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/seo.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/offer-plausibility.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/product-market-stats.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/sitemap-lastmod.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/leaderboard-badge-copy.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/leaderboard-criteria.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/trust-depth-v2.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/rating-score.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/rating-display.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/focus-trap.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/display-truth.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/spec-template.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/product-spec-rows.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/sale-state.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/csp.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/proxy.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/device-images.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/render-timing.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/model-match.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/developers-copy.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/plural-copy.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/locale-format.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/paged-reads.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/server-timing.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/hero-products.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/components/elementary/__tests__/locale-switcher-a11y.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/components/compare/__tests__/quick-toggle-a11y.test.ts", + "test": "pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/server/rate/__tests__/core-rate-architecture.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/server/rate/__tests__/mcp.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/server/rate/__tests__/item-model.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/server/rate/__tests__/item-directory.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/server/rate/__tests__/compare-selection.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/app/api/v1/rate/__tests__/write-paths.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/app/api/v1/rate/__tests__/spec-scope.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/app/api/v1/rate/__tests__/versus-parity.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/app/api/v1/rate/__tests__/item-fields.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/logger.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/review-display.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/review-form-v2.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/review-value-display.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/concurrency.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/merchant-profile-reads.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/merchant-review-risk.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/item-directory.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/home-deals-item-grouping.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/watchlist-sizes.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/item-compare.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/product-variant-links.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/compare-params.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/catalog-listing.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/discount-verdict-copy.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/product-detail-copy.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/product-competitors.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/analyzer-copy.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/sold-count.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/content-lang.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/image-url.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/client-messages.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/seo.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/offer-plausibility.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/product-market-stats.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/sitemap-lastmod.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/leaderboard-badge-copy.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/leaderboard-criteria.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/trust-depth-v2.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/rating-score.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/rating-display.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/focus-trap.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/display-truth.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/spec-template.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/product-spec-rows.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/sale-state.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/csp.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/proxy.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/device-images.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/render-timing.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/model-match.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/developers-copy.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/plural-copy.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/locale-format.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/paged-reads.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/server-timing.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/lib/__tests__/hero-products.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/components/elementary/__tests__/locale-switcher-a11y.test.ts && pnpm --filter @repo/crawlers exec tsx --tsconfig ../web/tsconfig.test.json ../web/src/components/compare/__tests__/quick-toggle-a11y.test.ts", "typecheck": "tsc --noEmit" }, "browserslist": [ diff --git a/apps/web/src/app/.well-known/mcp.json/route.ts b/apps/web/src/app/.well-known/mcp.json/route.ts new file mode 100644 index 00000000..2169d75a --- /dev/null +++ b/apps/web/src/app/.well-known/mcp.json/route.ts @@ -0,0 +1,17 @@ +import { NextResponse } from 'next/server'; +import { + MCP_DISCOVERY_CORS_HEADERS, + buildRateWellKnownMcpDescriptor, +} from '@/server/rate/mcp'; + +export const dynamic = 'force-static'; + +export async function GET() { + return NextResponse.json(buildRateWellKnownMcpDescriptor(), { + status: 200, + headers: { + ...MCP_DISCOVERY_CORS_HEADERS, + 'Cache-Control': 'public, s-maxage=3600, stale-while-revalidate=86400', + }, + }); +} 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]/developers/page.tsx b/apps/web/src/app/[locale]/developers/page.tsx index 1b8827e4..1a8e2f7c 100644 --- a/apps/web/src/app/[locale]/developers/page.tsx +++ b/apps/web/src/app/[locale]/developers/page.tsx @@ -94,6 +94,51 @@ const TEN_FIELD_GROUPS = [ }, ] as const; +const MCP_TOOL_KEYS = [ + 'search_verified_catalog', + 'get_22_store_offers_and_price_truth', + 'compare_devices_by_use_case', + 'audit_listing_url', + 'get_genuine_deals', +] as const; + +const MCP_CLIENT_CONFIG_SNIPPET = [ + '// .mcp.json / .cursor/mcp.json / DOSClaw (native HTTP)', + JSON.stringify( + { + mcpServers: { + 'rate-vn': { + type: 'streamable-http', + url: 'https://rate.vn/api/mcp', + }, + }, + }, + null, + 2 + ), + '', + '// claude_desktop_config.json (stdio bridge)', + JSON.stringify( + { + mcpServers: { + 'rate-vn': { + command: 'npx', + args: ['-y', 'mcp-remote', 'https://rate.vn/api/mcp'], + }, + }, + }, + null, + 2 + ), +].join('\n'); + +const MCP_JSON_RPC_CURL_SNIPPET = [ + "curl -sS -X POST 'https://rate.vn/api/mcp' \\", + " -H 'Content-Type: application/json' \\", + " -H 'Accept: application/json, text/event-stream' \\", + ' --data-raw \'{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"get_genuine_deals","arguments":{"category":"smartphones","limit":3}}}\'', +].join('\n'); + export default async function DevelopersPage({ params, }: { @@ -244,6 +289,30 @@ export default async function DevelopersPage({ queryParams: t('ep12Params'), summary: t('ep12Summary'), }, + { + method: 'POST', + path: '/api/mcp', + auth: t('authPublicMcp'), + cache: t('cacheNoStoreMcp'), + queryParams: t('ep20Params'), + summary: t('ep20Summary'), + }, + { + method: 'GET', + path: '/.well-known/mcp.json', + auth: t('authPublic'), + cache: 's-maxage=3600, stale-while-revalidate=86400', + queryParams: t('ep21Params'), + summary: t('ep21Summary'), + }, + { + method: 'GET', + path: '/llms.txt', + auth: t('authPublic'), + cache: 's-maxage=3600, stale-while-revalidate=86400', + queryParams: t('ep22Params'), + summary: t('ep22Summary'), + }, { method: 'POST', path: '/api/v1/rate/reviews', @@ -292,6 +361,12 @@ export default async function DevelopersPage({ > {t('btnPlayground')} + + {t('btnMcpDocs')} + + {/* Rate Shopping MCP Server & /llms.txt Section */} +
+
+
+
+ + {t('mcpBadge')} + +

{t('mcpTitle')}

+

{t('mcpSubtitle')}

+

{t('mcpGuardNote')}

+
+
+
+ + {t('mcpBtnLlmsTxt')} + + + {t('mcpBtnWellKnown')} + +
+
+
+ +
+
+

+ {t('mcpToolsHeading')} +

+
+ {MCP_TOOL_KEYS.map((toolKey) => ( +
+
+ + {toolKey} + + + {t('mcpReadOnlyBadge')} + +
+
+ {t(`mcpTools.${toolKey}`)} +
+
+ ))} +
+
+ +
+

+ {t('mcpConfigHeading')} +

+
+
+
+ {t('mcpClientConfigLabel')} +
+
+                      {MCP_CLIENT_CONFIG_SNIPPET}
+                    
+
+
+
+ {t('mcpCurlConfigLabel')} +
+
+                      {MCP_JSON_RPC_CURL_SNIPPET}
+                    
+
+
+
+
+
+
+ {/* Endpoint Reference Table */}
diff --git a/apps/web/src/app/[locale]/smartphones/[slug]/page.tsx b/apps/web/src/app/[locale]/smartphones/[slug]/page.tsx index 10fd014d..91f444bd 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, }: { @@ -760,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; @@ -772,6 +774,7 @@ export async function ProductDetailView({ currentMinPrice: v.minPrice > 0 ? v.minPrice : null, }} radarSignal={v.radarSignal} + offers={v.offers} /> ); const renderOffersBody = (v: { @@ -881,6 +884,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/app/global-error.tsx b/apps/web/src/app/global-error.tsx index 7b871817..9d025986 100644 --- a/apps/web/src/app/global-error.tsx +++ b/apps/web/src/app/global-error.tsx @@ -1,18 +1,34 @@ 'use client'; -import csMessages from '../../locales/cs.json'; -import enMessages from '../../locales/en.json'; -import viMessages from '../../locales/vi.json'; +import type viMessages from '../../locales/vi.json'; import { PAGE_META_CSP } from '@/lib/csp'; import { normalizeRateLocale, type SupportedRateLocale } from '@/lib/rate-i18n'; -const GLOBAL_ERROR_CATALOG: Record< +export const GLOBAL_ERROR_CATALOG: Record< SupportedRateLocale, typeof viMessages.errors.global > = { - vi: viMessages.errors.global, - en: enMessages.errors.global, - cs: csMessages.errors.global, + vi: { + title: 'Đã xảy ra lỗi không xác định', + tryAgain: 'Thử lại', + invalidContent: 'Không thể hiển thị nội dung này', + somethingWentWrong: 'Đã xảy ra sự cố ngoài ý muốn', + goHome: 'Về trang chủ Rate.vn', + }, + en: { + title: 'An unknown error occurred', + tryAgain: 'Try again', + invalidContent: 'This content could not be displayed', + somethingWentWrong: 'Something went wrong', + goHome: 'Rate.vn home', + }, + cs: { + title: 'Nastala neznámá chyba', + tryAgain: 'Zkusit znovu', + invalidContent: 'Tenhle obsah se nepodařilo načíst', + somethingWentWrong: 'Něco se pokazilo', + goHome: 'Domů na Rate.vn', + }, }; function detectBrowserLocale(): SupportedRateLocale { diff --git a/apps/web/src/app/llms.txt/route.ts b/apps/web/src/app/llms.txt/route.ts new file mode 100644 index 00000000..6f4749e4 --- /dev/null +++ b/apps/web/src/app/llms.txt/route.ts @@ -0,0 +1,18 @@ +import { NextResponse } from 'next/server'; +import { + MCP_DISCOVERY_CORS_HEADERS, + buildRateLlmsTxt, +} from '@/server/rate/mcp'; + +export const dynamic = 'force-static'; + +export async function GET() { + return new NextResponse(buildRateLlmsTxt(), { + status: 200, + headers: { + ...MCP_DISCOVERY_CORS_HEADERS, + 'Content-Type': 'text/plain; charset=utf-8', + 'Cache-Control': 'public, s-maxage=3600, stale-while-revalidate=86400', + }, + }); +} diff --git a/apps/web/src/app/robots.ts b/apps/web/src/app/robots.ts index 56c9b75c..c6af4a46 100644 --- a/apps/web/src/app/robots.ts +++ b/apps/web/src/app/robots.ts @@ -1,24 +1,24 @@ -import { env } from "@/env.mjs" +import { env } from '@/env.mjs'; -import type { MetadataRoute } from "next" +import type { MetadataRoute } from 'next'; -import { isProduction } from "@/lib/general-helpers" +import { isProduction } from '@/lib/general-helpers'; -const baseUrl = env.APP_PUBLIC_URL +const baseUrl = env.APP_PUBLIC_URL; export default function robots(): MetadataRoute.Robots { return isProduction() ? { rules: { - userAgent: "*", - allow: "/", + userAgent: '*', + allow: ['/', '/llms.txt', '/.well-known/mcp.json', '/api/mcp'], }, - sitemap: new URL("sitemap.xml", baseUrl).toString(), + sitemap: new URL('sitemap.xml', baseUrl).toString(), } : { rules: { - userAgent: "*", - disallow: "/", + userAgent: '*', + disallow: '/', }, - } + }; } diff --git a/apps/web/src/components/compare/CompareWorkspace.tsx b/apps/web/src/components/compare/CompareWorkspace.tsx index 92b9cf08..36995470 100644 --- a/apps/web/src/components/compare/CompareWorkspace.tsx +++ b/apps/web/src/components/compare/CompareWorkspace.tsx @@ -1,12 +1,14 @@ 'use client'; import React, { + Suspense, useCallback, useEffect, useMemo, useRef, useState, } from 'react'; +import { useSearchParams } from 'next/navigation'; import { useTranslations } from 'next-intl'; import type { IconType } from 'react-icons'; import { @@ -35,8 +37,28 @@ import { getCategorySpecTemplate, specFieldApplies, type CategorySpecTemplate, + type RatingCriterionKey, type SpecGroupKey, + type UseCasePresetId, } from '@repo/shared-data/rules'; +import { + availableCategoryUseCasePresets, + computeCustomWeightedScore5, + defaultCategoryWeights, + extractCategoryCriteriaScores, + isDefaultCategoryWeights, + mergeUseCaseQueryIntoSearch, + normalizeCategoryWeights, + parseUseCaseWeightsFromParams, + resolveCategoryPreset, + resolveLocalizedPresetName, + sanitizeSliderWeight, + scoredCategoryCriteriaForProducts, + type ActiveWeightMode, + type CategoryCriterionWeights, + type CustomWeightedScoreResult, +} from '@/lib/use-case-weights'; +import UseCaseWeightBar from './UseCaseWeightBar'; import { type CanonicalCategorySlug, MAX_VALID_VND_PRICE, @@ -110,6 +132,7 @@ import { displayedScore5, formatRatingValue, formatScoreFixed, + roundScore, } from '@/lib/rating-display'; interface CompareWorkspaceProps { @@ -125,6 +148,9 @@ interface CompareWorkspaceProps { * first and the second summary is left out (DOS/Rate#1473). */ layout?: 'compare' | 'versus'; + initialWeightMode?: ActiveWeightMode; + initialCategoryWeights?: CategoryCriterionWeights; + initialShowWeightSliders?: boolean; } type CompareTranslator = ReturnType>; @@ -1847,6 +1873,31 @@ export function filterSpecGroupsForCategory( .filter((group) => group.rows.length > 0); } +function CompareUrlWeightsSync({ + 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'); + const categorySlugRef = useRef(categorySlug); + useEffect(() => { + categorySlugRef.current = categorySlug; + }, [categorySlug]); + useEffect( + () => onSync(categorySlugRef.current, rawPreset, rawWeights), + [rawPreset, rawWeights, onSync] + ); + return null; +} + export default function CompareWorkspace({ initialProducts, catalogCandidates, @@ -1855,6 +1906,9 @@ export default function CompareWorkspace({ locale = 'vi', itemSlugBySlug, layout = 'compare', + initialWeightMode = 'default', + initialCategoryWeights, + initialShowWeightSliders = false, }: CompareWorkspaceProps) { const t = useTranslations('compare'); const router = useRouter(); @@ -1894,6 +1948,29 @@ export default function CompareWorkspace({ const [showDiffOnly, setShowDiffOnly] = useState(false); const [highlightWinners, setHighlightWinners] = useState(true); const [copiedLink, setCopiedLink] = useState(false); + const [weightMode, setWeightMode] = + useState(initialWeightMode); + const [categoryWeights, setCategoryWeights] = + useState(() => { + const cat = + initialProducts.length > 0 + ? getMasterProductCategorySlug(initialProducts[0]!) + : initialCategory; + if (initialCategoryWeights) { + return normalizeCategoryWeights(cat, initialCategoryWeights) + .sliderWeights; + } + if (initialWeightMode !== 'default' && initialWeightMode !== 'custom') { + return normalizeCategoryWeights( + cat, + resolveCategoryPreset(cat, initialWeightMode).weights + ).sliderWeights; + } + return defaultCategoryWeights(cat); + }); + const [showWeightSliders, setShowWeightSliders] = useState( + initialShowWeightSliders + ); const radarIndex = useDealRadarIndex(); // Every row, verdict and export reads the category's view of a product, // like the product page (DOS/Rate#1166). @@ -1902,6 +1979,168 @@ export default function CompareWorkspace({ storedProducts.map((p) => applyCategorySpecTemplate(activeCategory, p)), [storedProducts, activeCategory] ); + const scoredCompareCriteria = useMemo( + () => + scoredCategoryCriteriaForProducts( + activeCategory, + products.map((p) => ({ product: p })) + ), + [activeCategory, products] + ); + const availableComparePresets = useMemo( + () => + availableCategoryUseCasePresets(activeCategory, scoredCompareCriteria), + [activeCategory, scoredCompareCriteria] + ); + const canWeighCompare = + layout === 'compare' && + products.length >= 2 && + availableComparePresets.length > 0; + + const replaceCompareWeightQuery = useCallback( + ( + cat: CanonicalCategorySlug, + nextMode: ActiveWeightMode, + nextWeights: CategoryCriterionWeights, + available: readonly RatingCriterionKey[] + ) => { + if (typeof window === 'undefined' || layout !== 'compare') return; + const merged = + available.length > 0 + ? mergeUseCaseQueryIntoSearch( + window.location.search, + cat, + nextMode, + nextWeights, + available + ) + : mergeUseCaseQueryIntoSearch( + window.location.search, + cat, + 'default', + defaultCategoryWeights(cat), + [] + ); + window.history.replaceState( + null, + '', + `${window.location.pathname}${merged}` + ); + }, + [layout] + ); + + const handleCompareUrlWeightsSync = 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); + }, + [] + ); + + useEffect(() => { + if (layout !== 'compare') return; + if (!canWeighCompare) { + if (weightMode !== 'default' || showWeightSliders) { + const defaults = defaultCategoryWeights(activeCategory); + setWeightMode('default'); + setShowWeightSliders(false); + setCategoryWeights(defaults); + replaceCompareWeightQuery(activeCategory, 'default', defaults, []); + } + return; + } + if ( + weightMode !== 'default' && + (isDefaultCategoryWeights( + activeCategory, + weightMode, + categoryWeights, + scoredCompareCriteria + ) || + (weightMode !== 'custom' && + !availableComparePresets.some((p) => p.id === weightMode))) + ) { + const defaults = defaultCategoryWeights(activeCategory); + setWeightMode('default'); + setCategoryWeights(defaults); + replaceCompareWeightQuery( + activeCategory, + 'default', + defaults, + scoredCompareCriteria + ); + } + }, [ + layout, + canWeighCompare, + weightMode, + categoryWeights, + showWeightSliders, + activeCategory, + availableComparePresets, + scoredCompareCriteria, + replaceCompareWeightQuery, + ]); + + const handleSelectComparePreset = (presetId: UseCasePresetId) => { + const preset = resolveCategoryPreset(activeCategory, presetId); + const norm = normalizeCategoryWeights( + activeCategory, + preset.weights, + scoredCompareCriteria + ); + setWeightMode(preset.id); + setCategoryWeights(norm.sliderWeights); + replaceCompareWeightQuery( + activeCategory, + preset.id, + norm.sliderWeights, + scoredCompareCriteria + ); + }; + + const handleUpdateCompareWeight = (key: RatingCriterionKey, val: number) => { + const candidate: CategoryCriterionWeights = { + ...categoryWeights, + [key]: sanitizeSliderWeight(val, categoryWeights[key] ?? 0), + }; + const normalized = normalizeCategoryWeights( + activeCategory, + candidate, + scoredCompareCriteria + ); + const collapsesToDefault = + normalized.wasAllZeroReset || + isDefaultCategoryWeights( + activeCategory, + 'custom', + normalized.sliderWeights, + scoredCompareCriteria + ); + const nextMode: ActiveWeightMode = collapsesToDefault + ? 'default' + : 'custom'; + const nextWeights = collapsesToDefault + ? defaultCategoryWeights(activeCategory) + : normalized.sliderWeights; + setWeightMode(nextMode); + setCategoryWeights(nextWeights); + replaceCompareWeightQuery( + activeCategory, + nextMode, + nextWeights, + scoredCompareCriteria + ); + }; + + const handleResetCompareWeights = () => { + handleSelectComparePreset('default'); + }; // RATE_ITEM_MODEL on (the page passed a map): products the client added, // restored from the tray, or surfaced in Popular 1v1 Battles are read as // Items too, so 1v1 and product links name Canonical Items without a 308 @@ -2204,7 +2443,26 @@ export default function CompareWorkspace({ if (restored) { setActiveCategory(restored.activeCategory); setProducts(restored.products); - router.replace(`/compare?slugs=${restored.slugsCsv}`, { + let restoredQuery = `?slugs=${restored.slugsCsv}`; + if ( + typeof window !== 'undefined' && + layout === 'compare' && + restored.products.length >= 2 + ) { + const parsedRestored = parseUseCaseWeightsFromParams( + restored.activeCategory, + window.location.search + ); + setWeightMode(parsedRestored.mode); + setCategoryWeights(parsedRestored.weights); + restoredQuery = mergeUseCaseQueryIntoSearch( + restoredQuery, + restored.activeCategory, + parsedRestored.mode, + parsedRestored.weights + ); + } + router.replace(`/compare${restoredQuery}`, { scroll: false, }); return; @@ -2214,7 +2472,7 @@ export default function CompareWorkspace({ // Otherwise only show the page's defaults or a shared ?slugs= list: the // tray changes on the visitor's own edits (syncSelection), never on load, // so it does not follow them site-wide or lose what they saved (#714). - }, [hasExplicitSlugs, catalogCandidates, itemSlugBySlug, router]); + }, [hasExplicitSlugs, catalogCandidates, itemSlugBySlug, layout, router]); // Sync URL and localStorage tray whenever compared products change (always locked to 1 category) const syncSelection = ( @@ -2244,10 +2502,24 @@ export default function CompareWorkspace({ })) ); const slugsCsv = sameCategoryProducts.map((p) => p.slug).join(','); - const nextUrl = slugsCsv - ? `/compare?slugs=${slugsCsv}` - : `/compare?category=${targetCat}`; - router.replace(nextUrl, { scroll: false }); + const baseQuery = slugsCsv + ? `?slugs=${slugsCsv}` + : `?category=${targetCat}`; + let finalQuery = baseQuery; + if (targetCat !== activeCategory || sameCategoryProducts.length < 2) { + const nextDefaults = defaultCategoryWeights(targetCat); + setWeightMode('default'); + setCategoryWeights(nextDefaults); + setShowWeightSliders(false); + } else if (layout === 'compare') { + finalQuery = mergeUseCaseQueryIntoSearch( + baseQuery, + targetCat, + weightMode, + categoryWeights + ); + } + router.replace(`/compare${finalQuery}`, { scroll: false }); }; const handleSwitchCategoryTab = (nextCat: CanonicalCategorySlug) => { @@ -2716,6 +2988,83 @@ export default function CompareWorkspace({ activeReplaceIndex, }); + const hasActiveCompareWeights = + canWeighCompare && + !isDefaultCategoryWeights( + activeCategory, + weightMode, + categoryWeights, + scoredCompareCriteria + ); + + const customCompareScoresById = useMemo(() => { + const map = new Map(); + if (!hasActiveCompareWeights) return map; + for (const p of products) { + const critScores = extractCategoryCriteriaScores(p, activeCategory); + const res = computeCustomWeightedScore5( + activeCategory, + critScores, + categoryWeights, + { + onlyCriteria: scoredCompareCriteria, + officialScore5: getEffectiveRating(p), + product: p, + } + ); + map.set(p.id, res); + } + return map; + }, [ + hasActiveCompareWeights, + products, + activeCategory, + categoryWeights, + scoredCompareCriteria, + ]); + + const customCompareWinner = useMemo(() => { + if (!hasActiveCompareWeights) return null; + const scoredItems = products + .map((p) => ({ + product: p, + score5: customCompareScoresById.get(p.id)?.customScore5 ?? null, + })) + .filter( + (entry): entry is { product: MasterProduct; score5: number } => + entry.score5 !== null + ) + .sort((a, b) => b.score5 - a.score5); + if (scoredItems.length === 0) return null; + const top = scoredItems[0]!; + const runnerUp = scoredItems[1] ?? null; + const delta5 = runnerUp + ? roundScore(Math.max(0, top.score5 - runnerUp.score5), 2) + : null; + const isTie = runnerUp !== null && top.score5 === runnerUp.score5; + const winnerIds = new Set( + scoredItems + .filter((entry) => entry.score5 === top.score5) + .map((entry) => entry.product.id) + ); + return { + leadProduct: top.product, + leadScore5: top.score5, + delta5, + isTie, + scoredCount: scoredItems.length, + winnerIds, + }; + }, [hasActiveCompareWeights, products, customCompareScoresById]); + + const activeComparePresetTitle = resolveLocalizedPresetName( + activeCategory, + weightMode, + locale, + undefined, + t('customWeightsActive') + ); + const controlsBlock = ( <> {/* 5-Category Lock Switcher Bar */} @@ -3160,6 +3509,88 @@ export default function CompareWorkspace({
)} + + {/* 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/deals/DealFinderWorkspace.tsx b/apps/web/src/components/deals/DealFinderWorkspace.tsx index 1f94c4fe..17f64511 100644 --- a/apps/web/src/components/deals/DealFinderWorkspace.tsx +++ b/apps/web/src/components/deals/DealFinderWorkspace.tsx @@ -35,6 +35,11 @@ import { } from '@/lib/deal-radar'; import RadarBadge from '@/components/radar/RadarBadge'; import { useDealRadarIndex } from '@/components/radar/use-deal-radar'; +import { + countSeasonalSaleCampaignDeals, + matchesSeasonalSaleFilter, + type SeasonalSaleFilterMode, +} from '@/lib/omnibus-price-audit'; import { escapeCsvCell } from '@/lib/csv-safe'; import { formatDecimal, @@ -569,10 +574,13 @@ export default function DealFinderWorkspace({ const locale = useLocale(); const categoryLabelId = useId(); const personaLabelId = useId(); + const campaignLabelId = useId(); const [categoryFilter, setCategoryFilter] = useState< CanonicalCategorySlug | 'all' >(initialCategory); const [chosenPersona, setPersona] = useState('value_hunter'); + const [campaignFilter, setCampaignFilter] = + useState('all'); const [maxBudgetVnd, setMaxBudgetVnd] = useState(65_000_000); const [searchQuery, setSearchQuery] = useState(''); const [copiedMarkdown, setCopiedMarkdown] = useState(false); @@ -588,7 +596,7 @@ export default function DealFinderWorkspace({ ? chosenPersona : 'default'; // Paging restarts whenever a filter changes the ranking. - const filterKey = `${categoryFilter}|${persona}|${maxBudgetVnd}|${searchQuery}`; + const filterKey = `${categoryFilter}|${persona}|${campaignFilter}|${maxBudgetVnd}|${searchQuery}`; const [paging, setPaging] = useState({ key: filterKey, count: DEALS_PAGE_SIZE, @@ -611,7 +619,7 @@ export default function DealFinderWorkspace({ .querySelectorAll('#rate-ranked-deals > div') [index]?.querySelector('a[href]') ?.focus(); - }, [visibleCount]); + }, [visibleCount, filterKey]); const categoryOptions: Array<{ slug: CanonicalCategorySlug | 'all'; @@ -739,7 +747,7 @@ export default function DealFinderWorkspace({ URL.revokeObjectURL(url); }; - const rankedDeals = useMemo( + const baseRankedDeals = useMemo( () => rankProductsForDealFinder(products, { categoryFilter, @@ -750,6 +758,29 @@ export default function DealFinderWorkspace({ [products, categoryFilter, persona, maxBudgetVnd, searchQuery] ); + const seasonalCampaignCounts = useMemo( + () => + countSeasonalSaleCampaignDeals(baseRankedDeals, (slug) => + getRadarSignal(radarIndex, slug) + ), + [baseRankedDeals, radarIndex] + ); + + const rankedDeals = useMemo(() => { + if (campaignFilter === 'all') return baseRankedDeals; + return baseRankedDeals + .filter((d) => + matchesSeasonalSaleFilter( + getRadarSignal(radarIndex, d.slug), + campaignFilter + ) + ) + .map((d, idx) => ({ + ...d, + rank: idx + 1, + })); + }, [baseRankedDeals, campaignFilter, radarIndex]); + const handleCopyDealsMarkdown = async () => { if (typeof window === 'undefined' || rankedDeals.length === 0) return; try { @@ -951,6 +982,56 @@ export default function DealFinderWorkspace({
)} + {/* 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/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} +
{ + 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) => ( <> +
+ {/* 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 +1774,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/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__/compare-params.test.ts b/apps/web/src/lib/__tests__/compare-params.test.ts index 6315f23b..0462f1f8 100644 --- a/apps/web/src/lib/__tests__/compare-params.test.ts +++ b/apps/web/src/lib/__tests__/compare-params.test.ts @@ -1,5 +1,33 @@ import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { + RATING_DEVICE_CATEGORIES, + getRatingCriteria, + getRatingUseCasePresets, +} from '@repo/shared-data/rules'; import { compareCategoryParam } from '../compare-params'; +import { weightedCriteriaScore5 } from '../leaderboard-engine'; +import { + availableCategoryUseCasePresets, + computeCustomWeightedScore5, + defaultCategoryWeights, + extractCategoryCriteriaScores, + formatNormalizedWeightSummary, + isDefaultCategoryWeights, + mergeUseCaseQueryIntoSearch, + normalizeCategoryWeights, + parseUseCaseWeightsFromParams, + parseWeightsParam, + resolveCategoryPreset, + sanitizeSliderWeight, + scoredCategoryCriteriaForProducts, + serializeWeightsParam, + sharedCategoryCriteriaForPair, + toLegacyCriteriaWeights, + toLegacyVersusPersona, +} from '../use-case-weights'; // Compare links written with ?cat= open on their category (DOS/Rate#1303). assert.equal(compareCategoryParam({ cat: 'earbuds' }), 'earbuds'); @@ -12,4 +40,563 @@ assert.equal( assert.equal(compareCategoryParam({ cat: ['tablets', 'x'] }), 'tablets'); assert.equal(compareCategoryParam({}), undefined); assert.equal(compareCategoryParam({ category: '', cat: 'earbuds' }), 'earbuds'); -console.log('✅ compare params'); + +// ============================================================================ +// RTINGS-Style Category Use-Case Presets & Custom Weight Math (DOS/Rate#1864) +// ============================================================================ +{ + const testDir = path.dirname(fileURLToPath(import.meta.url)); + const webSrcDir = path.resolve(testDir, '../..'); + + // 1. Pure client-safe boundary & zero em/en-dash guard + for (const relPath of [ + 'lib/use-case-weights.ts', + 'components/compare/UseCaseWeightBar.tsx', + ]) { + const src = fs.readFileSync(path.join(webSrcDir, relPath), 'utf8'); + assert.doesNotMatch( + src, + /\bfrom\s+['"][^'"]*server\/rate/, + `${relPath} must stay client-safe with zero @/server/rate imports` + ); + assert.doesNotMatch( + src, + /[\u2013\u2014]|—|–/, + `${relPath} must contain zero em-dashes or en-dashes` + ); + } + + // 2. Category preset coverage & sum=100 across all 5 categories + for (const cat of RATING_DEVICE_CATEGORIES) { + const defaults = defaultCategoryWeights(cat); + const defaultSum = Object.values(defaults).reduce( + (acc, v) => 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__/developers-copy.test.ts b/apps/web/src/lib/__tests__/developers-copy.test.ts index 2d27c741..fc0fae7a 100644 --- a/apps/web/src/lib/__tests__/developers-copy.test.ts +++ b/apps/web/src/lib/__tests__/developers-copy.test.ts @@ -129,6 +129,143 @@ for (const locale of ['vi', 'cs']) { console.warn(' ✅ /developers table and group titles are localized (#1372)'); +// --------------------------------------------------------------------------- +// DOS/Rate#1866: Rate Shopping MCP Server (/api/mcp), /.well-known/mcp.json & +// /llms.txt documentation parity across vi, en, cs (zero em-dash / en-dash). +// --------------------------------------------------------------------------- +const mcpToolKeys = [ + 'search_verified_catalog', + 'get_22_store_offers_and_price_truth', + 'compare_devices_by_use_case', + 'audit_listing_url', + 'get_genuine_deals', +] as const; + +const mcpFlatKeys = [ + 'btnMcpDocs', + 'authPublicMcp', + 'cacheNoStoreMcp', + 'ep20Params', + 'ep20Summary', + 'ep21Params', + 'ep21Summary', + 'ep22Params', + 'ep22Summary', + 'mcpBadge', + 'mcpTitle', + 'mcpSubtitle', + 'mcpBtnLlmsTxt', + 'mcpBtnWellKnown', + 'mcpGuardNote', + 'mcpToolsHeading', + 'mcpReadOnlyBadge', + 'mcpConfigHeading', + 'mcpClientConfigLabel', + 'mcpCurlConfigLabel', +] as const; + +const enDevTopKeys = Object.keys(messages.en!).sort(); +for (const locale of ['vi', 'en', 'cs'] as const) { + const dev = messages[locale]!; + assert.deepEqual( + Object.keys(dev).sort(), + enDevTopKeys, + `${locale}.developers top-level key parity` + ); + for (const k of mcpFlatKeys) { + const val = dev[k]; + assert.ok( + typeof val === 'string' && val.trim().length > 0, + `${locale}.developers.${k} must be a non-empty string` + ); + assert.equal( + /[\u2013\u2014]/.test(val), + false, + `${locale}.developers.${k} must contain zero em-dashes or en-dashes` + ); + } + const mcpTools = dev.mcpTools as Record; + assert.ok( + mcpTools && typeof mcpTools === 'object', + `${locale}.developers.mcpTools must exist` + ); + assert.deepEqual( + Object.keys(mcpTools).sort(), + [...mcpToolKeys].sort(), + `${locale}.developers.mcpTools key parity` + ); + for (const toolKey of mcpToolKeys) { + const desc = mcpTools[toolKey]; + assert.ok( + typeof desc === 'string' && desc.trim().length > 0, + `${locale}.developers.mcpTools.${toolKey} must be non-empty` + ); + assert.equal( + /[\u2013\u2014]/.test(desc), + false, + `${locale}.developers.mcpTools.${toolKey} must contain zero em-dashes or en-dashes` + ); + } +} + +for (const locale of ['vi', 'cs'] as const) { + const dev = messages[locale]!; + for (const proseKey of [ + 'authPublicMcp', + 'ep20Summary', + 'ep21Summary', + 'ep22Summary', + 'mcpTitle', + 'mcpSubtitle', + 'mcpGuardNote', + 'mcpReadOnlyBadge', + ] as const) { + assert.notEqual( + dev[proseKey], + messages.en![proseKey], + `${locale}.developers.${proseKey} must be localized` + ); + } + for (const toolKey of mcpToolKeys) { + assert.notEqual( + (dev.mcpTools as Record)[toolKey], + (messages.en!.mcpTools as Record)[toolKey], + `${locale}.developers.mcpTools.${toolKey} must be localized` + ); + } +} + +assert.equal( + /[\u2013\u2014]/.test(page), + false, + 'developers/page.tsx must contain zero em-dashes or en-dashes' +); +for (const expectedPageToken of [ + "'/api/mcp'", + "'/.well-known/mcp.json'", + "'/llms.txt'", + 't(`mcpTools.${toolKey}`)', + 'https://rate.vn/api/mcp', + 'mcp-remote', + 'Accept: application/json, text/event-stream', + 'btn-outline-dark', + ...mcpToolKeys.map((k) => `'${k}'`), +]) { + assert.ok( + page.includes(expectedPageToken), + `developers/page.tsx must include ${expectedPageToken}` + ); +} +assert.equal( + page.includes('btn-outline-secondary'), + false, + 'developers/page.tsx must not use low-contrast dark-mode btn-outline-secondary' +); + +console.warn( + ' ✅ /developers MCP & /llms.txt localization parity passed (#1866)' +); + // --------------------------------------------------------------------------- // DOS/Rate#1747: Runnable POST snippets, non-JSON HTTP status preservation, // preset state synchronization, decorative icon a11y, th scope & telemetry formatting. 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__/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

+
+
+ RATE.VN +
+
+ {sanitizeOgCardText(params.eyebrow, 80)} +
+
+ +
+ {sanitizeOgCardText(params.badgeText, 64)} +
+
+ ); +} + +function renderFooterBar(params: { + readonly canonicalPath: string; + readonly note: string; + readonly isPortrait: boolean; +}) { + return ( +
+
+ {sanitizeOgCardText(`rate.vn${params.canonicalPath}`, 90)} +
+
+ {sanitizeOgCardText(params.note, 80)} +
+
+ ); +} + +function renderProductCardElement( + data: ProductTruthCardData, + locale: OgTruthCardLocale, + isPortrait: boolean +) { + const copy = OG_COPY[locale]; + const safeBrand = sanitizeOgCardText(data.brand, 40).toUpperCase(); + const safeName = sanitizeOgCardText(data.name, isPortrait ? 90 : 72); + const safeStores = Math.min( + TOTAL_TRACKED_PLATFORMS, + clampSafeCount(data.sellerCount, TOTAL_TRACKED_PLATFORMS) + ); + const minPrice = clampSafeVnd(data.minPriceVnd); + const maxPrice = clampSafeVnd(data.maxPriceVnd); + const spreadVnd = + minPrice > 0 && maxPrice > minPrice ? maxPrice - minPrice : 0; + + const formattedFloor = + minPrice > 0 ? formatOgPriceVnd(minPrice, locale) : copy.outOfStock; + const spreadText = + spreadVnd > 0 + ? copy.spreadLine( + Math.max(2, safeStores), + formatOgPriceVnd(spreadVnd, locale) + ) + : copy.noSpreadLine(safeStores); + + const savingsPctStr = + data.savingsPct > 0 + ? localizeDecimalPoints(clampSafePct(data.savingsPct).toFixed(1), locale) + : ''; + const fakeMarkupStr = + data.fakeMarkupPct > 0 + ? localizeDecimalPoints( + clampSafePct(data.fakeMarkupPct).toFixed(1), + locale + ) + : ''; + + const radarBadge = + data.radarKind === 'multi_platform_floor' + ? { text: copy.radarFloor(savingsPctStr), tone: 'green' as const } + : data.radarKind === 'below_median' + ? { text: copy.radarBelowMedian(savingsPctStr), tone: 'green' as const } + : data.radarKind === 'fake_sale_trap' + ? { text: copy.radarFakeTrap(fakeMarkupStr), tone: 'amber' as const } + : { text: copy.radarVerified, tone: 'blue' as const }; + + const userScoreStr = formatOgScore5(data.userScore5, locale); + const bayesianLabel = userScoreStr + ? copy.bayesianPill(userScoreStr) + : copy.unratedPill; + + const rawExpert = + data.expertScore10 != null && Number.isFinite(data.expertScore10) + ? Math.min(10, Math.max(0, data.expertScore10)) + : 0; + const expertLabel = + rawExpert > 0 + ? copy.expertPill( + localizeDecimalPoints(formatScoreFixed(rawExpert, 1), locale) + ) + : ''; + + const authCount = clampSafeCount(data.authenticReviews); + const filtCount = clampSafeCount(data.filteredReviews); + const totalAnalyzed = authCount + filtCount; + const authenticPct = + totalAnalyzed > 0 + ? Math.min( + 100, + Math.max(0, Math.round((authCount / totalAnalyzed) * 100)) + ) + : 0; + const reviewTrustLabel = + totalAnalyzed > 0 + ? copy.authenticPctPill(authenticPct, formatNumber(authCount, locale)) + : copy.collectingReviewsPill; + + const trapAuditLabel = data.hasFakeSaleTrap + ? copy.trapDetectedPill(fakeMarkupStr) + : copy.zeroTrapsPill; + + const cleanCatPath = data.categoryPath.startsWith('/') + ? data.categoryPath + : `/${data.categoryPath}`; + + return ( +
+ {renderHeaderBar({ + eyebrow: copy.headerAudit22, + badgeText: radarBadge.text, + badgeTone: radarBadge.tone, + isPortrait, + })} + +
+
+ {safeBrand ? ( +
+ {safeBrand} +
+ ) : null} +
+ {safeName} +
+
+ +
+
+ {sanitizeOgCardText(copy.floorPriceLabel(safeStores), 90)} +
+
+
0 ? '#34d399' : '#cbd5e1', + fontSize: + minPrice > 0 ? (isPortrait ? 58 : 48) : isPortrait ? 32 : 28, + fontWeight: 800, + letterSpacing: '-0.02em', + }} + > + {sanitizeOgCardText(formattedFloor, 60)} +
+
+ {sanitizeOgCardText(spreadText, 85)} +
+
+
+ +
+
+ {sanitizeOgCardText( + expertLabel ? `${bayesianLabel} · ${expertLabel}` : bayesianLabel, + 72 + )} +
+ +
+ {sanitizeOgCardText(reviewTrustLabel, 72)} +
+ +
+ {sanitizeOgCardText(trapAuditLabel, 72)} +
+
+
+ + {renderFooterBar({ + canonicalPath: `${cleanCatPath}/${data.slug}`, + note: copy.footerIndependent, + isPortrait, + })} +
+ ); +} + +function renderVersusSideBox(params: { + readonly side: VersusTruthCardSide; + readonly isWinner: boolean; + readonly locale: OgTruthCardLocale; + readonly isPortrait: boolean; +}) { + const copy = OG_COPY[params.locale]; + const scoreStr = formatOgScore5(params.side.score5, params.locale); + const priceStr = + params.side.minPriceVnd > 0 + ? formatOgPriceVnd(params.side.minPriceVnd, params.locale) + : copy.outOfStock; + const stores = Math.min( + TOTAL_TRACKED_PLATFORMS, + clampSafeCount(params.side.sellerCount, TOTAL_TRACKED_PLATFORMS) + ); + + return ( +
+
+
+
+ {sanitizeOgCardText( + params.side.brand || 'DEVICE', + 32 + ).toUpperCase()} +
+ {params.isWinner ? ( +
+ {sanitizeOgCardText(copy.versusLeadingTag, 24)} +
+ ) : null} +
+ +
+ {sanitizeOgCardText(params.side.name, params.isPortrait ? 64 : 46)} +
+
+ +
+
+
+ {sanitizeOgCardText(copy.versusFloorLabel(stores), 48)} +
+
0 ? '#34d399' : '#94a3b8', + fontSize: + params.side.minPriceVnd > 0 + ? params.isPortrait + ? 32 + : 26 + : 20, + fontWeight: 800, + }} + > + {sanitizeOgCardText(priceStr, 36)} +
+
+ +
+
+ {sanitizeOgCardText(copy.versusScoreLabel, 36)} +
+
+ {sanitizeOgCardText(scoreStr || copy.versusUnrated, 24)} +
+
+ {sanitizeOgCardText( + copy.versusCriteriaWins( + clampSafeCount(params.side.criterionWins, 20) + ), + 36 + )} +
+
+
+
+ ); +} + +function renderVersusCardElement( + data: VersusTruthCardData, + locale: OgTruthCardLocale, + isPortrait: boolean +) { + const copy = OG_COPY[locale]; + const winnerName = + data.winnerSide === 'A' + ? sanitizeOgCardText(data.itemA.name, 34) + : data.winnerSide === 'B' + ? sanitizeOgCardText(data.itemB.name, 34) + : ''; + const topBadge = + data.winnerSide === 'tie' || !winnerName + ? { text: copy.versusTieBadge, tone: 'blue' as const } + : { text: copy.versusWinnerBadge(winnerName), tone: 'red' as const }; + + return ( +
+ {renderHeaderBar({ + eyebrow: copy.headerVersus, + badgeText: topBadge.text, + badgeTone: topBadge.tone, + isPortrait, + })} + +
+ {renderVersusSideBox({ + side: data.itemA, + isWinner: data.winnerSide === 'A', + locale, + isPortrait, + })} + +
+ VS +
+ + {renderVersusSideBox({ + side: data.itemB, + isWinner: data.winnerSide === 'B', + locale, + isPortrait, + })} +
+ + {renderFooterBar({ + canonicalPath: `/compare/${data.versusSlug}`, + note: copy.footerIndependent, + isPortrait, + })} +
+ ); +} + +function renderDealsCardElement( + data: DealsTruthCardData, + locale: OgTruthCardLocale, + isPortrait: boolean +) { + const copy = OG_COPY[locale]; + const genuineCount = clampSafeCount(data.genuineDealCount); + const trapCount = clampSafeCount(data.fakeSaleTrapCount); + const offerCount = clampSafeCount(data.totalOffersAnalyzed); + const dealsToShow = data.topDeals.slice(0, isPortrait ? 4 : 2); + + return ( +
+ {renderHeaderBar({ + eyebrow: copy.headerDeals, + badgeText: copy.radarVerified, + badgeTone: 'green', + isPortrait, + })} + +
+
+
+ {sanitizeOgCardText(copy.dealsHeadline, 90)} +
+
+ {sanitizeOgCardText(copy.dealsSubheadline, 120)} +
+
+ +
+
+
+ {sanitizeOgCardText(formatNumber(genuineCount, locale), 24)} +
+
+ {sanitizeOgCardText(copy.dealsKpiGenuine, 40)} +
+
+ +
+
+ {sanitizeOgCardText(formatNumber(trapCount, locale), 24)} +
+
+ {sanitizeOgCardText(copy.dealsKpiTraps, 40)} +
+
+ +
+
+ {sanitizeOgCardText(formatNumber(offerCount, locale), 24)} +
+
+ {sanitizeOgCardText(copy.dealsKpiOffers, 40)} +
+
+
+ +
+
+ {sanitizeOgCardText(copy.dealsTopListLabel, 60)} +
+ + {dealsToShow.length === 0 ? ( +
+ {sanitizeOgCardText(copy.dealsEmptyHint, 96)} +
+ ) : ( + dealsToShow.map((deal, idx) => { + const pctStr = localizeDecimalPoints( + clampSafePct(deal.savingsPct).toFixed(1), + locale + ); + return ( +
+
+ {sanitizeOgCardText(deal.name, isPortrait ? 48 : 54)} +
+
+
+ {sanitizeOgCardText( + formatOgPriceVnd(deal.minPriceVnd, locale), + 32 + )} +
+ {deal.savingsPct > 0 ? ( +
+ {sanitizeOgCardText(copy.dealsSavingsBadge(pctStr), 32)} +
+ ) : null} +
+
+ ); + }) + )} +
+
+ + {renderFooterBar({ + canonicalPath: '/deals', + note: copy.footerIndependent, + isPortrait, + })} +
+ ); +} + +export function buildOgTruthCardElement( + card: OgTruthCardData, + format: OgTruthCardFormat = 'og', + locale: OgTruthCardLocale = 'vi' +) { + const isPortrait = format === 'social'; + if (card.type === 'product') { + return renderProductCardElement(card, locale, isPortrait); + } + if (card.type === 'versus') { + return renderVersusCardElement(card, locale, isPortrait); + } + return renderDealsCardElement(card, locale, isPortrait); +} + +export function createOgTruthCardResponse( + card: OgTruthCardData, + options?: { + readonly format?: OgTruthCardFormat; + readonly locale?: OgTruthCardLocale; + readonly download?: boolean; + readonly extraHeaders?: Record; + } +): ImageResponse { + const format: OgTruthCardFormat = + options?.format === 'social' ? 'social' : 'og'; + const locale: OgTruthCardLocale = + options?.locale === 'en' || options?.locale === 'cs' + ? options.locale + : 'vi'; + const width = + format === 'social' ? SOCIAL_TRUTH_CARD_WIDTH : OG_TRUTH_CARD_WIDTH; + const height = + format === 'social' ? SOCIAL_TRUTH_CARD_HEIGHT : OG_TRUTH_CARD_HEIGHT; + + const baseToken = + card.type === 'product' + ? sanitizeOgFileToken(card.slug) + : card.type === 'versus' + ? sanitizeOgFileToken(card.versusSlug) + : 'deal-radar'; + const suffix = format === 'social' ? '-4x5' : ''; + const disposition = options?.download === true ? 'attachment' : 'inline'; + const filename = `rate-truth-card-${baseToken}${suffix}.png`; + + return new ImageResponse(buildOgTruthCardElement(card, format, locale), { + width, + height, + headers: { + 'Cache-Control': OG_TRUTH_CARD_CACHE_CONTROL, + 'Content-Disposition': `${disposition}; filename="${filename}"`, + 'X-Content-Type-Options': 'nosniff', + ...options?.extraHeaders, + }, + }); +} + +export async function renderOgTruthCardPng( + card: OgTruthCardData, + format: OgTruthCardFormat = 'og', + locale: OgTruthCardLocale = 'vi' +): Promise { + const response = createOgTruthCardResponse(card, { format, locale }); + return new Uint8Array(await response.arrayBuffer()); +} + +/** + * Eagerly materializes the PNG byte buffer before constructing the HTTP Response + * so any Satori/sharp render error is caught inside the route's try/catch block + * rather than failing mid-stream after HTTP 200 + public CDN headers were sent. + */ +export async function renderOgTruthCardHttpResponse( + card: OgTruthCardData, + options?: { + readonly format?: OgTruthCardFormat; + readonly locale?: OgTruthCardLocale; + readonly download?: boolean; + readonly extraHeaders?: Record; + } +): Promise { + const imgResponse = createOgTruthCardResponse(card, options); + const bytes = new Uint8Array(await imgResponse.arrayBuffer()); + const headers = new Headers(imgResponse.headers); + headers.set('Content-Type', 'image/png'); + return new Response(Buffer.from(bytes), { + status: 200, + headers, + }); +} 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..a636873a --- /dev/null +++ b/apps/web/src/lib/omnibus-price-audit.ts @@ -0,0 +1,1277 @@ +/** + * 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 product_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 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, + 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-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/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, +]; diff --git a/apps/web/src/lib/seo.ts b/apps/web/src/lib/seo.ts index 831db563..ba2cf5ff 100644 --- a/apps/web/src/lib/seo.ts +++ b/apps/web/src/lib/seo.ts @@ -164,6 +164,221 @@ const OG_LOCALES: Record = { cs: 'cs_CZ', }; +export const OG_TRUTH_CARD_WIDTH = 1200; +export const OG_TRUTH_CARD_HEIGHT = 630; +export const SOCIAL_TRUTH_CARD_WIDTH = 1080; +export const SOCIAL_TRUTH_CARD_HEIGHT = 1350; + +export type OgTruthCardLocale = 'vi' | 'en' | 'cs'; +export type OgTruthCardFormat = 'og' | 'social'; + +export type OgTruthCardTarget = + | { + readonly type: 'product'; + readonly slug: string; + readonly variant?: string | null; + readonly locale?: string | null; + readonly format?: OgTruthCardFormat; + readonly download?: boolean; + } + | { + readonly type: 'versus'; + readonly versus: string; + readonly locale?: string | null; + readonly format?: OgTruthCardFormat; + readonly download?: boolean; + } + | { + readonly type: 'deals'; + readonly locale?: string | null; + readonly format?: OgTruthCardFormat; + readonly download?: boolean; + }; + +const OG_CATALOG_SLUG_REGEX = /^(?=.*[a-zA-Z0-9])[a-zA-Z0-9._-]+$/; +const OG_VERSUS_SIDE_LEADING_RE = /^[a-zA-Z0-9]/; +const OG_VARIANT_KEY_REGEX = /^[a-z0-9][a-z0-9-]{0,40}$/; +const DISALLOWED_OG_SLUG_TOKENS = new Set([ + 'null', + 'undefined', + 'nan', + 'na', + 'none', + 'infinity', + '-infinity', + 'true', + 'false', + '__proto__', + 'constructor', + 'prototype', + ...Object.getOwnPropertyNames(Object.prototype).map((key) => + key.toLowerCase() + ), +]); + +export function normalizeOgLocale(locale: unknown): OgTruthCardLocale { + const cleaned = + typeof locale === 'string' + ? locale + .replace(/\p{Cc}+/gu, '') + .trim() + .toLowerCase() + : ''; + return cleaned === 'en' || cleaned === 'cs' ? cleaned : 'vi'; +} + +export function isValidOgSlug(slug: unknown, maxLength = 120): boolean { + if (typeof slug !== 'string') return false; + const safeMax = + typeof maxLength === 'number' && Number.isFinite(maxLength) && maxLength > 0 + ? Math.min(240, Math.floor(maxLength)) + : 120; + if ( + !slug || + slug.length > safeMax || + /[\s\p{Cc}\p{Cf}]/u.test(slug) || + slug in Object.prototype + ) { + return false; + } + const lower = slug.toLowerCase(); + return ( + OG_CATALOG_SLUG_REGEX.test(slug) && + (!slug.includes('.') || OG_VERSUS_SIDE_LEADING_RE.test(slug)) && + !slug.startsWith('.') && + !/^0+$/.test(slug) && + !slug.endsWith('.') && + !slug.includes('..') && + !DISALLOWED_OG_SLUG_TOKENS.has(lower) + ); +} + +export function isValidOgVariantKey(variant: unknown): variant is string { + return ( + typeof variant === 'string' && + OG_VARIANT_KEY_REGEX.test(variant) && + !(variant in Object.prototype) && + !DISALLOWED_OG_SLUG_TOKENS.has(variant) + ); +} + +export function parseOgVersusPair( + versus: unknown, + maxSlugLength = 120, + keepCase = false +): [string, string] | null { + if (typeof versus !== 'string') return null; + const trimmed = versus.replace(/\p{Cc}+/gu, '').trim(); + const safeMax = + typeof maxSlugLength === 'number' && + Number.isFinite(maxSlugLength) && + maxSlugLength > 0 + ? Math.min(240, Math.floor(maxSlugLength)) + : 120; + if (!trimmed || trimmed.length > safeMax * 2 + 4 || /\s/.test(trimmed)) { + return null; + } + const parts = trimmed.split(/-vs-/i); + if (parts.length !== 2) return null; + const rawA = parts[0] ?? ''; + const rawB = parts[1] ?? ''; + const sideA = keepCase ? rawA : rawA.toLowerCase(); + const sideB = keepCase ? rawB : rawB.toLowerCase(); + if ( + !isValidOgSlug(sideA, safeMax) || + !isValidOgSlug(sideB, safeMax) || + !OG_VERSUS_SIDE_LEADING_RE.test(sideA) || + !OG_VERSUS_SIDE_LEADING_RE.test(sideB) || + sideA.toLowerCase() === sideB.toLowerCase() + ) { + return null; + } + return [sideA, sideB]; +} + +export function buildOgTruthCardPath(target: OgTruthCardTarget): string { + if (!target || typeof target !== 'object') return SHARE_IMAGE.url; + const locale = normalizeOgLocale(target.locale); + const format: OgTruthCardFormat = + target.format === 'social' ? 'social' : 'og'; + const params = new URLSearchParams(); + + if (target.type === 'product') { + const cleanSlug = + typeof target.slug === 'string' + ? target.slug.replace(/\p{Cc}+/gu, '').trim() + : ''; + if (!isValidOgSlug(cleanSlug)) return SHARE_IMAGE.url; + params.set('type', 'product'); + params.set('slug', cleanSlug); + if (typeof target.variant === 'string' && target.variant.trim()) { + const cleanVar = target.variant.trim().toLowerCase(); + if (!isValidOgVariantKey(cleanVar)) return SHARE_IMAGE.url; + params.set('variant', cleanVar); + } + } else if (target.type === 'versus') { + const pair = parseOgVersusPair(target.versus, 120, true); + if (!pair) return SHARE_IMAGE.url; + params.set('type', 'versus'); + params.set('versus', `${pair[0]}-vs-${pair[1]}`); + } else if (target.type === 'deals') { + params.set('type', 'deals'); + } else { + return SHARE_IMAGE.url; + } + + params.set('locale', locale); + if (format === 'social') { + params.set('format', 'social'); + } + if (target.download === true) { + params.set('download', '1'); + } + return `/api/v1/rate/og?${params.toString()}`; +} + +export function buildOgTruthCardImage( + target: OgTruthCardTarget & { readonly alt?: string | null } +) { + const relPath = buildOgTruthCardPath(target); + if (relPath === SHARE_IMAGE.url) { + return SHARE_IMAGE; + } + const safeAlt = + typeof target.alt === 'string' + ? target.alt + .replace(/\p{Cc}+/gu, ' ') + .replace(/\s+/g, ' ') + .trim() + .slice(0, 160) || 'Rate.vn' + : 'Rate.vn'; + const isSocial = target.format === 'social'; + return { + url: absoluteUrl(relPath), + width: isSocial ? SOCIAL_TRUTH_CARD_WIDTH : OG_TRUTH_CARD_WIDTH, + height: isSocial ? SOCIAL_TRUTH_CARD_HEIGHT : OG_TRUTH_CARD_HEIGHT, + type: 'image/png' as const, + alt: safeAlt, + }; +} + +export function defaultTwitterCard( + image: + | { + readonly url: string; + readonly width?: number; + readonly height?: number; + readonly alt?: string; + } + | string = SHARE_IMAGE +) { + return { + card: 'summary_large_image' as const, + site: '@rate_vn', + images: [image], + }; +} + /** * Base Open Graph fields shared by every route. A page that sets its own * `openGraph` replaces the layout's object, so it spreads this first and adds diff --git a/apps/web/src/lib/use-case-weights.ts b/apps/web/src/lib/use-case-weights.ts new file mode 100644 index 00000000..50914769 --- /dev/null +++ b/apps/web/src/lib/use-case-weights.ts @@ -0,0 +1,1169 @@ +/** + * RTINGS-style category use-case presets, normalized 0..100 custom weight math, + * per-criterion score extraction, and shareable URL query state (DOS/Rate#1864). + * + * Pure client-safe module: zero server-only imports. + * Preserves Design Rule #1531 D3/D9: + * - Official `Rate.vn Score` stays unchanged alongside `Your Custom Score`. + * - Missing or unrated criteria are never fabricated; weights renormalize over + * rated criteria or return `null` when none exist. + * - Decimal-safe rounding matches `weightedCriteriaScore5` (`roundScore(..., 2)`) + * and `displayedScore5` (`roundScore(..., 1)`). + */ +import type { MasterProduct } from '@repo/shared-data'; +import { + getRatingCriteria, + getRatingCriterionLabel, + getRatingUseCasePresetLabel, + getRatingUseCasePresets, + isRatingCriterionKey, + type RatingCriterion, + type RatingCriterionKey, + type RatingUseCasePreset, + type UseCasePresetId, +} from '@repo/shared-data/rules'; +import { + CRITERION_RANK_WRITERS, + type LeaderboardCriteriaBreakdown, + type LeaderboardCriteriaWeights, +} from './leaderboard-engine'; +import { formatPercent } from './locale-format'; +import { + getMasterProductCategorySlug, + resolveCompareEffectiveUserRating, +} from './rate-domain-core'; +import { displayedScore5, roundScore } from './rating-display'; +import type { PersonaPresetKey } from './versus-score'; + +export type ActiveWeightMode = UseCasePresetId | 'custom'; + +export type CategoryCriterionWeights = Partial< + Record +>; + +export type CategoryCriteriaScores = Partial< + Record +>; + +export interface NormalizedCategoryWeights { + readonly sliderWeights: Record; + readonly normalizedPercent: Record; + readonly wasAllZeroReset: boolean; +} + +export interface ParsedUseCaseUrlState { + readonly mode: ActiveWeightMode; + readonly weights: Record; + readonly normalizedPercent: Record; +} + +export interface CustomWeightedScoreResult { + readonly customScore5: number | null; + readonly displayedCustomScore5: number | null; + readonly officialScore5: number; + readonly displayedOfficialScore5: number; + readonly ratedCriteriaCount: number; + readonly totalCriteriaCount: number; + readonly effectiveSharesPercent: Partial>; +} + +const CONTROL_CHARS_RE = /\p{Cc}+/gu; +const HEX_BIN_OCT_RE = /^[+-]?0[xbo]/i; +const PRESET_SLUG_RE = /^[a-z0-9][a-z0-9_-]{0,39}$/; +const WEIGHT_TOKEN_DECIMAL_RE = /^(?:0|[1-9]\d{0,2})(?:\.\d{1,4})?$/; +const MAX_QUERY_PARAM_LEN = 256; +const MAX_WEIGHT_TOKENS = 16; + +const UNSAFE_OBJECT_KEYS = new Set([ + '__proto__', + 'constructor', + 'prototype', + 'toString', + 'valueOf', +]); + +function isPlainObject(value: unknown): value is Record { + return Boolean(value && typeof value === 'object' && !Array.isArray(value)); +} + +function ownValue(record: Record, key: string): unknown { + if (UNSAFE_OBJECT_KEYS.has(key)) return undefined; + return Object.prototype.hasOwnProperty.call(record, key) + ? record[key] + : undefined; +} + +function setSafeKey(target: Record, key: string, value: V): void { + if (UNSAFE_OBJECT_KEYS.has(key)) return; + target[key] = value; +} + +/** + * Sanitizes an interactive slider input into an integer `0..100`. + * Rejects NaN, Infinity, control chars, hex/octal/binary prefixes, and + * non-primitive values by falling back to `fallback` (clamped `0..100`). + */ +export function sanitizeSliderWeight(value: unknown, fallback = 0): number { + const safeFallback = + typeof fallback === 'number' && Number.isFinite(fallback) + ? Math.max(0, Math.min(100, Math.round(fallback))) + : 0; + if (typeof value === 'number') { + if (!Number.isFinite(value)) return safeFallback; + return Math.max(0, Math.min(100, Math.round(value))); + } + if (typeof value === 'string') { + if (/\p{Cc}/u.test(value)) return safeFallback; + const trimmed = value.trim(); + if (!trimmed || trimmed.length > 16 || HEX_BIN_OCT_RE.test(trimmed)) { + return safeFallback; + } + const parsed = Number(trimmed); + if (!Number.isFinite(parsed)) return safeFallback; + return Math.max(0, Math.min(100, Math.round(parsed))); + } + return safeFallback; +} + +/** + * Strict parser for URL query weight values (`?weights=camera:45,...`). + * Rejects negative numbers, NaN, Infinity, values > 100, and non-decimal strings + * rather than clamping huge or negative query input silently. + */ +function parseStrictQueryWeight(raw: string): number | null { + if (/\p{Cc}/u.test(raw)) return null; + const trimmed = raw.trim(); + if ( + !trimmed || + trimmed.length > 12 || + !WEIGHT_TOKEN_DECIMAL_RE.test(trimmed) + ) { + return null; + } + const num = Number(trimmed); + if (!Number.isFinite(num) || num < 0 || num > 100) { + return null; + } + return Math.round(num); +} + +function normalizeCategorySlugInput( + categorySlug: string | null | undefined +): string { + if (typeof categorySlug !== 'string' || categorySlug.length > 64) { + return 'smartphones'; + } + const cleaned = categorySlug + .replace(CONTROL_CHARS_RE, '') + .trim() + .toLowerCase(); + return cleaned || 'smartphones'; +} + +/** + * Returns the category's Balanced Default weights from `@repo/shared-data/rules` + * (`sum === 100`). + */ +export function defaultCategoryWeights( + categorySlug: string | null | undefined +): Record { + const cat = normalizeCategorySlugInput(categorySlug); + const out = {} as Record; + for (const criterion of getRatingCriteria(cat)) { + setSafeKey(out, criterion.key, criterion.weight); + } + return out; +} + +/** + * Largest-remainder (Hare-Niemeyer) integer normalization to exact `100%` + * using exact integer arithmetic (`(w * 100) / sum` and `(w * 100) % sum`). + */ +function largestRemainderPercent( + orderedKeys: readonly RatingCriterionKey[], + weights: Readonly> +): Partial> { + const out: Partial> = {}; + let sum = 0; + for (const key of orderedKeys) { + const w = weights[key] ?? 0; + if (w > 0) sum += w; + } + if (sum <= 0) { + for (const key of orderedKeys) setSafeKey(out, key, 0); + return out; + } + const entries = orderedKeys.map((key, index) => { + const w = Math.max(0, weights[key] ?? 0); + const scaled = w * 100; + const floor = Math.floor(scaled / sum); + const rem = scaled % sum; + return { key, index, w, floor, rem }; + }); + let remainder = 100 - entries.reduce((acc, item) => acc + item.floor, 0); + const byRemainder = [...entries].sort((a, b) => { + if (b.rem !== a.rem) return b.rem - a.rem; + if (b.w !== a.w) return b.w - a.w; + return a.index - b.index; + }); + const bonusKeys = new Set(); + for (let i = 0; i < byRemainder.length && remainder > 0; i++) { + const candidate = byRemainder[i]; + if (candidate && candidate.w > 0) { + bonusKeys.add(candidate.key); + remainder -= 1; + } + } + for (const entry of entries) { + setSafeKey( + out, + entry.key, + entry.floor + (bonusKeys.has(entry.key) ? 1 : 0) + ); + } + return out; +} + +/** + * Normalizes custom `0..100` integer slider weights for a category so their + * normalized shares always sum to exact `100%`. + * + * When all active criteria sliders are `0` (or `rawWeights` is invalid), + * gracefully resets to Balanced Default (`wasAllZeroReset: true`). + */ +export function normalizeCategoryWeights( + categorySlug: string | null | undefined, + rawWeights: unknown, + availableCriteria?: readonly RatingCriterionKey[] +): NormalizedCategoryWeights { + const cat = normalizeCategorySlugInput(categorySlug); + const criteria = getRatingCriteria(cat); + const allKeys = criteria.map((c) => c.key); + const activeSet = + availableCriteria && availableCriteria.length > 0 + ? new Set( + availableCriteria.filter((k) => allKeys.includes(k)) + ) + : null; + const effectiveActiveKeys = + activeSet && activeSet.size > 0 + ? allKeys.filter((k) => activeSet.has(k)) + : allKeys; + + const defaults = defaultCategoryWeights(cat); + const record = isPlainObject(rawWeights) ? rawWeights : null; + + const sliderWeights = {} as Record; + let activeRawSum = 0; + + if (record) { + for (const criterion of criteria) { + const rawVal = ownValue(record, criterion.key); + const safeVal = + rawVal === undefined ? 0 : sanitizeSliderWeight(rawVal, 0); + setSafeKey(sliderWeights, criterion.key, safeVal); + if (effectiveActiveKeys.includes(criterion.key)) { + activeRawSum += safeVal; + } + } + } + + if (!record || activeRawSum <= 0) { + const resetNormalized = {} as Record; + for (const key of allKeys) setSafeKey(resetNormalized, key, 0); + const activeShares = largestRemainderPercent(effectiveActiveKeys, defaults); + for (const key of effectiveActiveKeys) { + setSafeKey(resetNormalized, key, activeShares[key] ?? 0); + } + return { + sliderWeights: { ...defaults }, + normalizedPercent: resetNormalized, + wasAllZeroReset: true, + }; + } + + const normalizedPercent = {} as Record; + for (const key of allKeys) setSafeKey(normalizedPercent, key, 0); + const activeShares = largestRemainderPercent( + effectiveActiveKeys, + sliderWeights + ); + for (const key of effectiveActiveKeys) { + setSafeKey(normalizedPercent, key, activeShares[key] ?? 0); + } + + return { + sliderWeights, + normalizedPercent, + wasAllZeroReset: false, + }; +} + +const PRESET_URL_ALIASES: Readonly> = { + balanced: 'default', + none: 'default', + standard: 'default', + photography: 'camera', + photo: 'camera', + vlog: 'camera', + value_hunter: 'value', + best_value: 'value', + anc: 'commute_anc', + commute: 'commute_anc', + calls: 'calls_work', + meetings: 'calls_work', + music: 'audiophile', + sound: 'audiophile', + study: 'study_work', + productivity: 'study_work', + health: 'fitness', +}; + +function mapCategoryPresetAlias( + categorySlug: string | null | undefined, + cleaned: string +): string { + if (cleaned === 'business') { + const cat = (categorySlug ?? '').toLowerCase().trim(); + if (cat === 'laptops') return 'office'; + if (cat === 'tablets') return 'study_work'; + if (cat === 'smartwatches') return 'smart_daily'; + } + if (ownValue(PRESET_URL_ALIASES, cleaned) !== undefined) { + return PRESET_URL_ALIASES[cleaned]!; + } + return cleaned; +} + +/** + * Resolves a preset id or URL alias for `categorySlug`, falling back safely to + * `'default'` when unknown or unsafe (`__proto__`, `constructor`, etc.). + */ +export function resolveCategoryPreset( + categorySlug: string | null | undefined, + presetInput: unknown +): RatingUseCasePreset { + const cat = normalizeCategorySlugInput(categorySlug); + const presets = getRatingUseCasePresets(cat); + const defaultPreset = presets[0]!; + if (typeof presetInput !== 'string' || presetInput.length > 64) { + return defaultPreset; + } + const cleaned = presetInput + .replace(CONTROL_CHARS_RE, '') + .trim() + .toLowerCase(); + if ( + !cleaned || + UNSAFE_OBJECT_KEYS.has(cleaned) || + !PRESET_SLUG_RE.test(cleaned) + ) { + return defaultPreset; + } + const targetId = mapCategoryPresetAlias(cat, cleaned); + const matched = presets.find((p) => p.id === targetId); + return matched ?? defaultPreset; +} + +/** + * Returns presets worth offering when only `availableCriteria` have real scores + * (`#1553` / `#1556`). Empty when `availableCriteria` has zero valid category keys. + */ +export function availableCategoryUseCasePresets( + categorySlug: string | null | undefined, + availableCriteria: readonly RatingCriterionKey[] +): RatingUseCasePreset[] { + if (!availableCriteria || availableCriteria.length === 0) return []; + const cat = normalizeCategorySlugInput(categorySlug); + const availableSet = new Set(availableCriteria); + const presets = getRatingUseCasePresets(cat); + const criteria = getRatingCriteria(cat); + if (!criteria.some((c) => availableSet.has(c.key))) return []; + return presets.filter((preset) => { + if (preset.id === 'default') return true; + let leadKey: RatingCriterionKey | null = null; + let leadWeight = -1; + for (const c of criteria) { + const w = preset.weights[c.key] ?? 0; + if (w > leadWeight) { + leadWeight = w; + leadKey = c.key; + } + } + return leadKey !== null && availableSet.has(leadKey); + }); +} + +export function isDefaultCategoryWeights( + categorySlug: string | null | undefined, + mode: ActiveWeightMode, + weights: unknown, + availableCriteria?: readonly RatingCriterionKey[] +): boolean { + if (mode === 'default') return true; + const cat = normalizeCategorySlugInput(categorySlug); + const criteria = getRatingCriteria(cat); + const allKeys = criteria.map((c) => c.key); + const activeSet = + availableCriteria && availableCriteria.length > 0 + ? new Set( + availableCriteria.filter((k) => allKeys.includes(k)) + ) + : null; + const activeKeys = + activeSet && activeSet.size > 0 + ? allKeys.filter((k) => activeSet.has(k)) + : allKeys; + + const normalized = normalizeCategoryWeights(cat, weights, availableCriteria); + if (normalized.wasAllZeroReset) return true; + const defaults = defaultCategoryWeights(cat); + + let sliderSum = 0; + let defaultSum = 0; + for (const key of activeKeys) { + sliderSum += normalized.sliderWeights[key] ?? 0; + defaultSum += defaults[key] ?? 0; + } + if (sliderSum <= 0 || defaultSum <= 0) return true; + for (const key of activeKeys) { + const w = normalized.sliderWeights[key] ?? 0; + const d = defaults[key] ?? 0; + if (w * defaultSum !== d * sliderSum) { + return false; + } + } + return true; +} + +/** + * Encodes custom slider weights compactly as `key:weight,key:weight` in canonical + * category criterion order (omitting zero weights while keeping integer percentages + * for display). + */ +export function serializeWeightsParam( + categorySlug: string | null | undefined, + rawWeights: unknown, + availableCriteria?: readonly RatingCriterionKey[] +): string { + const cat = normalizeCategorySlugInput(categorySlug); + const criteria = getRatingCriteria(cat); + const allKeys = criteria.map((c) => c.key); + const activeSet = + availableCriteria && availableCriteria.length > 0 + ? new Set( + availableCriteria.filter((k) => allKeys.includes(k)) + ) + : null; + const normalized = normalizeCategoryWeights( + cat, + rawWeights, + availableCriteria + ); + if (normalized.wasAllZeroReset) return ''; + const parts: string[] = []; + for (const criterion of criteria) { + if (activeSet && activeSet.size > 0 && !activeSet.has(criterion.key)) { + continue; + } + const weight = normalized.sliderWeights[criterion.key] ?? 0; + if (weight > 0) { + parts.push(`${criterion.key}:${weight}`); + } + } + return parts.join(','); +} + +/** + * Parses a `?weights=...` query value strictly for `categorySlug`. + * Rejects prototype keys, duplicate keys, foreign criteria, negative/NaN/huge + * numbers, and oversized query strings. Returns `null` when invalid or all-zero. + */ +export function parseWeightsParam( + categorySlug: string | null | undefined, + rawParam: unknown +): Record | null { + if (typeof rawParam !== 'string' || rawParam.length > MAX_QUERY_PARAM_LEN) { + return null; + } + if (/\p{Cc}/u.test(rawParam)) return null; + const trimmed = rawParam.trim(); + if (!trimmed || trimmed.length > MAX_QUERY_PARAM_LEN) return null; + + const cat = normalizeCategorySlugInput(categorySlug); + const criteria = getRatingCriteria(cat); + const validKeys = new Set(criteria.map((c) => c.key)); + const legacyKeyToCanonical = (key: string): RatingCriterionKey | null => { + if (key === 'screen') { + return cat === 'earbuds' + ? 'sound' + : validKeys.has('display') + ? 'display' + : null; + } + if (isRatingCriterionKey(key) && validKeys.has(key)) { + return key; + } + return null; + }; + + const tokens = trimmed.split(','); + if (tokens.length === 0 || tokens.length > MAX_WEIGHT_TOKENS) return null; + + const parsed = {} as Record; + for (const c of criteria) setSafeKey(parsed, c.key, 0); + const seenKeys = new Set(); + + for (const rawToken of tokens) { + const token = rawToken.trim(); + if (!token) return null; + const colonIdx = token.indexOf(':'); + if (colonIdx <= 0 || token.indexOf(':', colonIdx + 1) !== -1) { + return null; + } + const rawKey = token.slice(0, colonIdx).trim().toLowerCase(); + const rawVal = token.slice(colonIdx + 1).trim(); + if (!rawKey || UNSAFE_OBJECT_KEYS.has(rawKey)) { + return null; + } + const canonicalKey = legacyKeyToCanonical(rawKey); + if (!canonicalKey || seenKeys.has(canonicalKey)) { + return null; + } + const weight = parseStrictQueryWeight(rawVal); + if (weight === null) { + return null; + } + seenKeys.add(canonicalKey); + setSafeKey(parsed, canonicalKey, weight); + } + + let finalPositiveSum = 0; + for (const c of criteria) { + finalPositiveSum += parsed[c.key] ?? 0; + } + if (seenKeys.size === 0 || finalPositiveSum <= 0) { + return null; + } + return parsed; +} + +type SearchParamsInput = + | URLSearchParams + | Readonly> + | string + | null + | undefined; + +function readFirstSearchParam( + input: SearchParamsInput, + key: 'preset' | 'weights' +): string | undefined { + if (!input) return undefined; + if (typeof input === 'string') { + const q = input.startsWith('?') ? input.slice(1) : input; + if (q.length > 2048) return undefined; + const sp = new URLSearchParams(q); + return sp.get(key) ?? undefined; + } + if (input instanceof URLSearchParams) { + return input.get(key) ?? undefined; + } + if (isPlainObject(input)) { + const v = ownValue(input, key); + if (typeof v === 'string') return v; + if (Array.isArray(v) && typeof v[0] === 'string') return v[0]; + } + return undefined; +} + +/** + * Restores `{ mode, weights, normalizedPercent }` from URL query params + * (`?preset=...` or `?weights=...`), falling back cleanly to Balanced Default + * when absent, malformed, all-zero, or containing prototype keys. + */ +export function parseUseCaseWeightsFromParams( + categorySlug: string | null | undefined, + params: SearchParamsInput, + availableCriteria?: readonly RatingCriterionKey[] +): ParsedUseCaseUrlState { + const rawWeights = readFirstSearchParam(params, 'weights'); + if (rawWeights !== undefined && rawWeights.trim() !== '') { + const parsedWeights = parseWeightsParam(categorySlug, rawWeights); + if (parsedWeights) { + const normalized = normalizeCategoryWeights( + categorySlug, + parsedWeights, + availableCriteria + ); + if (!normalized.wasAllZeroReset) { + const isDef = isDefaultCategoryWeights( + categorySlug, + 'custom', + normalized.sliderWeights, + availableCriteria + ); + if (isDef) { + const defNorm = normalizeCategoryWeights( + categorySlug, + defaultCategoryWeights(categorySlug), + availableCriteria + ); + return { + mode: 'default', + weights: defNorm.sliderWeights, + normalizedPercent: defNorm.normalizedPercent, + }; + } + return { + mode: 'custom', + weights: normalized.sliderWeights, + normalizedPercent: normalized.normalizedPercent, + }; + } + } + } + + const rawPreset = readFirstSearchParam(params, 'preset'); + if (rawPreset !== undefined && rawPreset.trim() !== '') { + const preset = resolveCategoryPreset(categorySlug, rawPreset); + const allowed = + availableCriteria && availableCriteria.length > 0 + ? availableCategoryUseCasePresets(categorySlug, availableCriteria).some( + (p) => p.id === preset.id + ) + : true; + const effectivePreset = allowed + ? preset + : getRatingUseCasePresets(categorySlug)[0]!; + const normalized = normalizeCategoryWeights( + categorySlug, + effectivePreset.weights, + availableCriteria + ); + return { + mode: effectivePreset.id, + weights: normalized.sliderWeights, + normalizedPercent: normalized.normalizedPercent, + }; + } + + const defNorm = normalizeCategoryWeights( + categorySlug, + defaultCategoryWeights(categorySlug), + availableCriteria + ); + return { + mode: 'default', + weights: defNorm.sliderWeights, + normalizedPercent: defNorm.normalizedPercent, + }; +} + +/** + * Merges `preset` or `weights` into an existing query string (`window.location.search`), + * removing both when Balanced Default is active so default URLs stay clean. + */ +export function mergeUseCaseQueryIntoSearch( + currentSearch: string, + categorySlug: string | null | undefined, + mode: ActiveWeightMode, + weights: unknown, + availableCriteria?: readonly RatingCriterionKey[] +): string { + const cleanSearch = currentSearch.startsWith('?') + ? currentSearch.slice(1) + : currentSearch; + const params = new URLSearchParams(cleanSearch); + params.delete('preset'); + params.delete('weights'); + + if ( + !isDefaultCategoryWeights(categorySlug, mode, weights, availableCriteria) + ) { + if (mode === 'custom') { + const encoded = serializeWeightsParam( + categorySlug, + weights, + availableCriteria + ); + if (encoded) params.set('weights', encoded); + } else { + params.set('preset', mode); + } + } + + const next = params.toString(); + return next ? `?${next}` : ''; +} + +function toSafePositiveNumber(raw: unknown): number { + if (typeof raw === 'number') { + return Number.isFinite(raw) && raw > 0 ? raw : 0; + } + if (typeof raw === 'string') { + if (/\p{Cc}/u.test(raw)) return 0; + const cleaned = raw.trim(); + if (!cleaned || cleaned.length > 32 || HEX_BIN_OCT_RE.test(cleaned)) { + return 0; + } + const n = Number(cleaned); + return Number.isFinite(n) && n > 0 ? n : 0; + } + return 0; +} + +function legacyAliasesForCriterion( + categorySlug: string, + key: RatingCriterionKey +): readonly string[] { + switch (key) { + case 'display': + return categorySlug === 'earbuds' ? [] : ['screen', 'man_hinh']; + case 'sound': + return categorySlug === 'earbuds' + ? ['screen', 'audio', 'multimedia'] + : ['audio', 'multimedia']; + case 'anc': + return categorySlug === 'earbuds' ? ['camera'] : []; + case 'health': + return categorySlug === 'smartwatches' ? ['sensors'] : []; + case 'apps': + return categorySlug === 'smartwatches' ? ['connectivity'] : []; + case 'performance': + return ['hardware', 'hieu_nang']; + case 'battery': + return ['pin', 'endurance']; + case 'value': + return ['price_value', 'dang_tien']; + default: + return []; + } +} + +function legacyBreakdownFallback( + categorySlug: string, + key: RatingCriterionKey, + breakdown: LeaderboardCriteriaBreakdown | null | undefined +): number | null { + if (!breakdown || !isPlainObject(breakdown)) return null; + let candidate: unknown; + if (key === 'display' && categorySlug !== 'earbuds') { + candidate = breakdown.screen; + } else if (key === 'sound' && categorySlug === 'earbuds') { + candidate = breakdown.screen; + } else if (key === 'anc' && categorySlug === 'earbuds') { + candidate = breakdown.camera; + } else if ( + key === 'performance' && + (categorySlug === 'smartphones' || + categorySlug === 'tablets' || + categorySlug === 'laptops') + ) { + candidate = breakdown.performance; + } else if (key === 'camera' && categorySlug === 'smartphones') { + candidate = breakdown.camera; + } else if (key === 'battery') { + candidate = breakdown.battery; + } else if (key === 'value') { + candidate = breakdown.value; + } + const n = toSafePositiveNumber(candidate); + return n > 0 && n <= 5 ? n : null; +} + +/** + * Extracts a product's real per-criterion scores (`0..5`) for `categorySlug` + * without ever fabricating missing criteria from overall ratings, specs, or prices + * (`#1143`, `#1531 D9`). + */ +export function extractCategoryCriteriaScores( + product: Partial | null | undefined, + categorySlug?: string | null, + minWriters: number = CRITERION_RANK_WRITERS, + fallbackBreakdown?: LeaderboardCriteriaBreakdown | null +): Record { + const safeProduct = isPlainObject(product) ? product : {}; + const effectiveMinWriters = Math.max( + 1, + Number.isFinite(minWriters) ? minWriters : CRITERION_RANK_WRITERS + ); + const resolvedCat = + typeof categorySlug === 'string' && categorySlug.trim() + ? normalizeCategorySlugInput(categorySlug) + : normalizeCategorySlugInput( + getMasterProductCategorySlug(safeProduct as MasterProduct) + ); + const community = isPlainObject(safeProduct.criteria_scores) + ? safeProduct.criteria_scores + : {}; + const expert = isPlainObject(safeProduct.expert_criteria_scores) + ? safeProduct.expert_criteria_scores + : {}; + + const readCommunity = (k: string): number | null => { + const entry = ownValue(community, k); + if (!isPlainObject(entry)) return null; + const writers = toSafePositiveNumber(ownValue(entry, 'writers')); + const score = toSafePositiveNumber(ownValue(entry, 'score')); + return writers >= effectiveMinWriters && score > 0 && score <= 5 + ? score + : null; + }; + + const readExpert = (k: string): number | null => { + const v = toSafePositiveNumber(ownValue(expert, k)); + if (v > 0 && v <= 10) { + return roundScore(Math.min(5, v > 5 ? v / 2 : v), 2); + } + return null; + }; + + const out = {} as Record; + for (const criterion of getRatingCriteria(resolvedCat)) { + const keysToTry = [ + criterion.key, + ...legacyAliasesForCriterion(resolvedCat, criterion.key), + ]; + let resolvedScore: number | null = null; + for (const k of keysToTry) { + const comm = readCommunity(k); + if (comm !== null) { + resolvedScore = comm; + break; + } + } + if (resolvedScore === null) { + for (const k of keysToTry) { + const exp = readExpert(k); + if (exp !== null) { + resolvedScore = exp; + break; + } + } + } + if (resolvedScore === null && fallbackBreakdown) { + resolvedScore = legacyBreakdownFallback( + resolvedCat, + criterion.key, + fallbackBreakdown + ); + } + setSafeKey(out, criterion.key, resolvedScore); + } + return out; +} + +/** + * Returns the category's criteria for which at least one product in `items` + * has a real criterion score (`> 0`). + */ +export function scoredCategoryCriteriaForProducts( + categorySlug: string | null | undefined, + items: ReadonlyArray<{ + readonly product?: Partial | null; + readonly rankCriteria?: LeaderboardCriteriaBreakdown | null; + }>, + minWriters: number = CRITERION_RANK_WRITERS +): RatingCriterionKey[] { + const cat = normalizeCategorySlugInput(categorySlug); + const criteria = getRatingCriteria(cat); + const scored = new Set(); + for (const entry of items) { + if (!entry) continue; + const map = extractCategoryCriteriaScores( + entry.product, + cat, + minWriters, + entry.rankCriteria + ); + for (const c of criteria) { + const val = map[c.key]; + if (typeof val === 'number' && val > 0) { + scored.add(c.key); + } + } + if (scored.size === criteria.length) break; + } + return criteria.map((c) => c.key).filter((k) => scored.has(k)); +} + +/** + * Returns the category's criteria that BOTH sides of a 1v1 pair have a real + * criterion score for (`#1556`). + */ +export function sharedCategoryCriteriaForPair( + categorySlug: string | null | undefined, + scoresA: CategoryCriteriaScores, + scoresB: CategoryCriteriaScores +): RatingCriterionKey[] { + return getRatingCriteria(normalizeCategorySlugInput(categorySlug)) + .map((c) => c.key) + .filter((k) => (scoresA?.[k] ?? 0) > 0 && (scoresB?.[k] ?? 0) > 0); +} + +/** + * Computes `Your Custom Score` (`0..5`, decimal-safe 2 decimals matching + * `weightedCriteriaScore5`) alongside the unchanged official `Rate.vn Score` + * (`#1531 D3/D9`). + * + * Unrated criteria (`null`) are never fabricated: weights renormalize over + * rated criteria, or `customScore5` is `null` when none of the weighted + * criteria has a real score. + */ +export function computeCustomWeightedScore5( + categorySlug: string | null | undefined, + criteriaScores: CategoryCriteriaScores | null | undefined, + rawWeights: unknown, + options?: { + readonly onlyCriteria?: readonly RatingCriterionKey[]; + readonly officialScore5?: number; + readonly product?: Partial | null; + } +): CustomWeightedScoreResult { + const cat = normalizeCategorySlugInput(categorySlug); + const criteria = getRatingCriteria(cat); + const allowedSet = + options?.onlyCriteria !== undefined + ? new Set(options.onlyCriteria) + : null; + const candidateCriteria: readonly RatingCriterion[] = allowedSet + ? criteria.filter((c) => allowedSet.has(c.key)) + : criteria; + + const rawOfficial = + options?.officialScore5 !== undefined + ? options.officialScore5 + : options?.product + ? resolveCompareEffectiveUserRating(options.product as MasterProduct) + : 0; + const officialScore5 = + typeof rawOfficial === 'number' && + Number.isFinite(rawOfficial) && + rawOfficial > 0 + ? Math.min(5, rawOfficial) + : 0; + const displayedOfficialScore5 = displayedScore5(officialScore5); + + if (candidateCriteria.length === 0 || !isPlainObject(rawWeights)) { + return { + customScore5: null, + displayedCustomScore5: null, + officialScore5, + displayedOfficialScore5, + ratedCriteriaCount: 0, + totalCriteriaCount: candidateCriteria.length, + effectiveSharesPercent: {}, + }; + } + + const candidateKeys = candidateCriteria.map((c) => c.key); + const normalized = normalizeCategoryWeights(cat, rawWeights, candidateKeys); + if (normalized.wasAllZeroReset) { + return { + customScore5: null, + displayedCustomScore5: null, + officialScore5, + displayedOfficialScore5, + ratedCriteriaCount: 0, + totalCriteriaCount: candidateCriteria.length, + effectiveSharesPercent: {}, + }; + } + + const safeScores = isPlainObject(criteriaScores) ? criteriaScores : {}; + + let weightedSum = 0; + let weightSum = 0; + const contributingKeys: RatingCriterionKey[] = []; + const contributingWeights: Record = {}; + + for (const criterion of candidateCriteria) { + const rawScore = ownValue(safeScores, criterion.key); + const weight = normalized.sliderWeights[criterion.key] ?? 0; + if ( + typeof rawScore !== 'number' || + !Number.isFinite(rawScore) || + rawScore <= 0 || + rawScore > 5 || + weight <= 0 + ) { + continue; + } + weightedSum += rawScore * weight; + weightSum += weight; + contributingKeys.push(criterion.key); + contributingWeights[criterion.key] = weight; + } + + if (weightSum <= 0) { + return { + customScore5: null, + displayedCustomScore5: null, + officialScore5, + displayedOfficialScore5, + ratedCriteriaCount: 0, + totalCriteriaCount: candidateCriteria.length, + effectiveSharesPercent: {}, + }; + } + + const customScore5 = Math.min(5, roundScore(weightedSum / weightSum, 2)); + const displayedCustomScore5 = displayedScore5(customScore5); + const effectiveSharesPercent = largestRemainderPercent( + contributingKeys, + contributingWeights + ); + + return { + customScore5, + displayedCustomScore5, + officialScore5, + displayedOfficialScore5, + ratedCriteriaCount: contributingKeys.length, + totalCriteriaCount: candidateCriteria.length, + effectiveSharesPercent, + }; +} + +/** + * Formats a concise localized weight breakdown summary + * (e.g. `Hiệu năng 40% · Pin và sạc 25% · Màn hình 15% ...`). + */ +export function formatNormalizedWeightSummary( + categorySlug: string | null | undefined, + normalizedPercent: Readonly>>, + locale: string | null | undefined, + criterionLabels?: Readonly>>, + availableCriteria?: readonly RatingCriterionKey[] +): string { + const cat = normalizeCategorySlugInput(categorySlug); + const allowed = + availableCriteria && availableCriteria.length > 0 + ? new Set(availableCriteria) + : null; + const parts: string[] = []; + for (const criterion of getRatingCriteria(cat)) { + if (allowed && !allowed.has(criterion.key)) continue; + const pct = normalizedPercent[criterion.key] ?? 0; + if (pct <= 0) continue; + const label = + (criterionLabels && + Object.prototype.hasOwnProperty.call(criterionLabels, criterion.key) + ? criterionLabels[criterion.key] + : undefined) || getRatingCriterionLabel(criterion, locale); + parts.push(`${label} ${formatPercent(pct, locale)}`); + } + return parts.join(' · '); +} + +export function resolveLocalizedPresetName( + categorySlug: string | null | undefined, + mode: ActiveWeightMode, + locale: string | null | undefined, + presetLabels?: Readonly>>, + customLabel = 'Custom' +): string { + if (mode === 'custom') return customLabel; + if ( + presetLabels && + Object.prototype.hasOwnProperty.call(presetLabels, mode) + ) { + const fromCopy = presetLabels[mode]; + if (typeof fromCopy === 'string' && fromCopy.trim()) return fromCopy; + } + const preset = resolveCategoryPreset(categorySlug, mode); + return getRatingUseCasePresetLabel(preset, locale); +} + +/** + * Bridges category criterion weights onto the 5 legacy `LeaderboardCriteriaWeights` + * buckets (`screen`, `performance`, `camera`, `battery`, `value`) used by + * `computeVersusResult` and legacy exports. + */ +export function toLegacyCriteriaWeights( + categorySlug: string | null | undefined, + rawWeights: unknown, + availableCriteria?: readonly RatingCriterionKey[] +): LeaderboardCriteriaWeights { + const cat = normalizeCategorySlugInput(categorySlug); + const norm = normalizeCategoryWeights( + cat, + rawWeights, + availableCriteria + ).normalizedPercent; + if (cat === 'earbuds') { + return { + screen: 0, + performance: (norm.comfort ?? 0) + (norm.calls ?? 0), + camera: (norm.sound ?? 0) + (norm.anc ?? 0), + battery: norm.battery ?? 0, + value: norm.value ?? 0, + }; + } + if (cat === 'smartwatches') { + return { + screen: (norm.display ?? 0) + (norm.design ?? 0), + performance: norm.apps ?? 0, + camera: norm.health ?? 0, + battery: norm.battery ?? 0, + value: norm.value ?? 0, + }; + } + if (cat === 'laptops') { + return { + screen: (norm.display ?? 0) + (norm.design ?? 0) + (norm.keyboard ?? 0), + performance: (norm.performance ?? 0) + (norm.thermals ?? 0), + camera: 0, + battery: norm.battery ?? 0, + value: norm.value ?? 0, + }; + } + if (cat === 'tablets') { + return { + screen: (norm.display ?? 0) + (norm.design ?? 0), + performance: (norm.performance ?? 0) + (norm.software ?? 0), + camera: norm.sound ?? 0, + battery: norm.battery ?? 0, + value: norm.value ?? 0, + }; + } + return { + screen: (norm.display ?? 0) + (norm.design ?? 0), + performance: norm.performance ?? 0, + camera: norm.camera ?? 0, + battery: norm.battery ?? 0, + value: norm.value ?? 0, + }; +} + +/** + * Maps an `ActiveWeightMode` onto `PersonaPresetKey` for `computeVersusResult`. + */ +export function toLegacyVersusPersona( + mode: ActiveWeightMode +): PersonaPresetKey { + switch (mode) { + case 'default': + return 'default'; + case 'camera': + case 'audiophile': + case 'commute_anc': + case 'media': + return 'photography'; + case 'gaming': + case 'creator': + return 'gaming'; + case 'endurance': + case 'fitness': + return 'endurance'; + case 'office': + case 'study_work': + case 'smart_daily': + return 'business'; + case 'value': + return 'value_hunter'; + default: + return 'custom'; + } +} diff --git a/apps/web/src/proxy.ts b/apps/web/src/proxy.ts index 4b4997d8..cda4aa11 100644 --- a/apps/web/src/proxy.ts +++ b/apps/web/src/proxy.ts @@ -43,6 +43,13 @@ async function refreshSupabaseSession( } } +/** Direct API and AI discovery endpoints that never undergo locale rewriting. */ +export function isDirectNonLocalePath(pathname: string): boolean { + return /^\/(?:api(?:\/|$)|llms\.txt\/?$|(?:\.well-known)(?:\/|$))/i.test( + pathname + ); +} + /** HTTPS + locale routing (synchronous, so it is testable without a network). */ export function localeProxy(req: NextRequest): NextResponse { const xForwardedProtoHeader = req.headers.get('x-forwarded-proto'); @@ -63,6 +70,10 @@ export function localeProxy(req: NextRequest): NextResponse { // Strip any explicit /vi, /en, /cs URL prefix so URLs never contain a locale slug const pathname = req.nextUrl.pathname; + if (isDirectNonLocalePath(pathname)) { + req.headers.delete('content-security-policy'); + return NextResponse.next(); + } const localePrefixMatch = pathname.match(/^\/(vi|en|cs)(\/.*)?$/i); if (localePrefixMatch) { const matchedLocale = localePrefixMatch[1]!.toLowerCase(); @@ -109,8 +120,13 @@ export function localeProxy(req: NextRequest): NextResponse { export async function proxy(req: NextRequest): Promise { const response = localeProxy(req); - // Redirects carry no page; refresh the session on the request that renders. - if (response.status >= 300 && response.status < 400) return response; + // Redirects and stateless API / AI discovery routes skip cookie session refresh. + if ( + isDirectNonLocalePath(req.nextUrl.pathname) || + (response.status >= 300 && response.status < 400) + ) { + return response; + } await refreshSupabaseSession(req, response); return response; } diff --git a/apps/web/src/server/rate/__tests__/mcp.test.ts b/apps/web/src/server/rate/__tests__/mcp.test.ts new file mode 100644 index 00000000..cea051a7 --- /dev/null +++ b/apps/web/src/server/rate/__tests__/mcp.test.ts @@ -0,0 +1,1925 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { NextRequest } from 'next/server'; +import { BoundedSlidingWindowRateLimiter } from '../api-handler'; +import { + CANONICAL_RATE_ORIGIN, + MAX_MCP_BODY_BYTES, + MAX_MCP_RESULT_ITEMS, + MCP_LATEST_PROTOCOL_VERSION, + MCP_TOOL_DEFINITIONS, + buildRateLlmsTxt, + buildRateWellKnownMcpDescriptor, + handleMcpHttpPost, + type McpDataReaders, +} from '../mcp'; +import { + DELETE as deleteMcpRoute, + GET as getMcpRoute, + OPTIONS as optionsMcpRoute, + POST as postMcpRoute, +} from '../../../app/api/mcp/route'; +import { GET as getLlmsTxtRoute } from '../../../app/llms.txt/route'; +import { GET as getWellKnownMcpRoute } from '../../../app/.well-known/mcp.json/route'; +import { + parseEcommerceUrlOrQuery, + type MasterProduct, + type MasterProductPriceHistorySummary, + type MerchantOffer, + type ReviewAnalysisSummary, + type UrlInspectionResult, +} from '../../../lib/rate-api'; +import type { CrossPlatformDealRadarResponse } from '../deals'; + +const FIXED_NOW_ISO = '2026-11-22T14:30:00.000Z'; + +function makeProduct( + overrides: Partial & { id: string; slug: string; name: string } +): MasterProduct { + return { + brand: 'Apple', + model: overrides.name, + model_key: overrides.slug, + has_5g: true, + specifications: { + display: { refresh_rate_hz: 120, type: 'LTPO OLED' }, + hardware: { chipset: 'Apple A18 Pro', ram_gb: 8 }, + battery: { capacity_mah: 4685, fast_charging_w: 30 }, + }, + key_specs: { + chipset: 'Apple A18 Pro', + ram_gb: 8, + storage_gb: 256, + }, + images: ['/img/devices/apple-iphone-16-pro-max-256gb.jpg'], + colors: ['Natural Titanium'], + min_price: 28_990_000, + max_price: 32_990_000, + merchant_count: 4, + total_reviews: 48, + average_rating: 4.8, + rating_score: 4.82, + user_rating_weighted: 4.82, + expert_rating: 9.4, + authentic_review_count: 42, + criteria_scores: { + screen: { score: 4.8, writers: 12 }, + performance: { score: 4.9, writers: 12 }, + camera: { score: 4.9, writers: 12 }, + battery: { score: 4.6, writers: 12 }, + value: { score: 4.2, writers: 12 }, + }, + status: 'published', + metadata: { category_slug: 'smartphones' }, + updated_at: '2026-11-22T12:00:00.000Z', + ...overrides, + } as MasterProduct; +} + +function makeOffer( + overrides: Partial & { + id: string; + platform: string; + price_current: number; + } +): MerchantOffer { + return { + title: 'Apple iPhone 16 Pro Max 256GB Chính hãng VN/A', + price_original: 34_990_000, + stock: 15, + rating_star: 4.9, + rating_count: 120, + url: `https://${overrides.platform}.vn/product/${overrides.id}`, + availability: 'in_stock', + merchant: { + id: `merchant-${overrides.platform}`, + name: `${overrides.platform.toUpperCase()} Official`, + platform: overrides.platform, + is_official: true, + rating_star: 4.9, + follower_count: 50_000, + location: 'Ho Chi Minh City', + risk_score: 8, + dosafe_risk_score: 0, + review_risk_score: 8, + review_risk_breakdown: { total_reviews: 25 }, + }, + ...overrides, + }; +} + +const iphoneProduct = makeProduct({ + id: '11111111-1111-4111-8111-000000000001', + slug: 'apple-iphone-16-pro-max-256gb', + name: 'Apple iPhone 16 Pro Max 256GB', + brand: 'Apple', +}); + +const galaxyProduct = makeProduct({ + id: '11111111-1111-4111-8111-000000000002', + slug: 'samsung-galaxy-s25-ultra-256gb', + name: 'Samsung Galaxy S25 Ultra 256GB', + brand: 'Samsung', + min_price: 26_490_000, + max_price: 30_990_000, + rating_score: 4.78, + user_rating_weighted: 4.78, + expert_rating: 9.2, + criteria_scores: { + screen: { score: 4.9, writers: 10 }, + performance: { score: 4.95, writers: 10 }, + camera: { score: 4.6, writers: 10 }, + battery: { score: 4.85, writers: 10 }, + value: { score: 4.7, writers: 10 }, + }, +}); + +const macbookProduct = makeProduct({ + id: '11111111-1111-4111-8111-000000000003', + slug: 'apple-macbook-air-m3-16gb-256gb', + name: 'Apple MacBook Air M3 16GB 256GB', + brand: 'Apple', + metadata: { category_slug: 'laptops' }, +}); + +const sampleOffersForIphone: MerchantOffer[] = [ + // Bait-price silicone case trap (must be excluded from floor!) + makeOffer({ + id: 'offer-bait-case', + platform: 'shopee', + title: 'Ốp lưng silicon iPhone 16 Pro Max', + price_current: 89_000, + price_original: 150_000, + merchant: { + id: 'merchant-random', + name: 'Random Case Shop', + platform: 'shopee', + is_official: false, + rating_star: 4.2, + follower_count: 100, + location: 'Hanoi', + risk_score: 45, + dosafe_risk_score: 0, + // No analysed reviews -> must be nulled by withPublicOfferReviewRisk + review_risk_score: 25, + review_risk_breakdown: { total_reviews: 0 }, + }, + }), + // Sold-out stale cheap listing (must be excluded from floor!) + makeOffer({ + id: 'offer-sold-out', + platform: 'tiki', + price_current: 25_990_000, + availability: 'out_of_stock', + }), + // Valid Official Mall floor offer + makeOffer({ + id: 'offer-cps-official', + platform: 'cellphones', + price_current: 28_990_000, + price_original: 34_990_000, + url: 'https://cellphones.com.vn/iphone-16-pro-max.html', + }), + makeOffer({ + id: 'offer-shopee-mall', + platform: 'shopee', + price_current: 29_490_000, + price_original: 34_990_000, + url: 'https://shopee.vn/Apple-iPhone-16-Pro-Max-i.88201679.27110898667', + merchant: { + id: 'merchant-shopee-unanalysed', + name: 'Apple Flagship Store', + platform: 'shopee', + is_official: true, + rating_star: 4.9, + follower_count: 900_000, + location: 'Ho Chi Minh City', + risk_score: 5, + dosafe_risk_score: 0, + dosafe_risk_known: false, + review_risk_score: 12, + review_risk_breakdown: { total_reviews: 0 }, + } as MerchantOffer['merchant'] & { dosafe_risk_known: boolean }, + }), + makeOffer({ + id: 'offer-tgdd', + platform: 'tgdd', + price_current: 30_990_000, + price_original: 34_990_000, + url: 'https://www.thegioididong.com/dtdd/iphone-16-pro-max', + }), +]; + +const sampleOffersForGalaxy: MerchantOffer[] = [ + makeOffer({ + id: 'offer-galaxy-cps', + platform: 'cellphones', + title: 'Samsung Galaxy S25 Ultra 256GB', + price_current: 26_490_000, + price_original: 31_990_000, + url: 'https://cellphones.com.vn/samsung-galaxy-s25-ultra.html', + }), + makeOffer({ + id: 'offer-galaxy-fpt', + platform: 'fptshop', + title: 'Samsung Galaxy S25 Ultra 256GB', + price_current: 27_990_000, + price_original: 31_990_000, + url: 'https://fptshop.com.vn/dien-thoai/samsung-galaxy-s25-ultra', + }), + makeOffer({ + id: 'offer-galaxy-hhm', + platform: 'hoangha', + title: 'Samsung Galaxy S25 Ultra 256GB', + price_current: 26_790_000, + price_original: 31_990_000, + url: 'https://hoanghamobile.com/dien-thoai/samsung-galaxy-s25-ultra', + }), +]; + +function createMockReaders(): McpDataReaders { + const catalog = Array.from({ length: 14 }, (_, i) => + i === 0 + ? iphoneProduct + : i === 1 + ? galaxyProduct + : makeProduct({ + id: `11111111-1111-4111-8111-0000000000${String(i + 10).padStart(2, '0')}`, + slug: `sample-phone-${i + 1}`, + name: `Sample Phone ${i + 1}`, + min_price: 10_000_000 + i * 500_000, + }) + ); + + return { + nowIso: () => FIXED_NOW_ISO, + resolveCompareTokenTarget: async (rawToken) => { + const trimmed = rawToken.trim(); + if (trimmed.includes('@')) { + const [base, vKey] = trimmed.split('@'); + if ( + base?.toLowerCase() === 'iphone-16-pro-max' && + vKey?.toLowerCase() === '256gb' + ) { + return { + variantSlug: iphoneProduct.slug, + itemId: 'item-iphone-16-pro-max', + }; + } + return { variantSlug: null, itemId: null }; + } + if (trimmed.toLowerCase() === 'iphone-16-pro-max') { + return { + variantSlug: iphoneProduct.slug, + itemId: 'item-iphone-16-pro-max', + }; + } + if (trimmed.toLowerCase() === iphoneProduct.slug) { + return { + variantSlug: iphoneProduct.slug, + itemId: 'item-iphone-16-pro-max', + }; + } + return { variantSlug: trimmed.toLowerCase(), itemId: null }; + }, + getCachedMasterProducts: async (params) => { + const lim = params?.limit ?? 24; + return catalog + .filter((p) => + params?.search + ? p.name.toLowerCase().includes(params.search.toLowerCase()) + : true + ) + .slice(0, lim); + }, + getCachedMasterProductBySlug: async (slug) => { + const lower = slug.toLowerCase(); + if (lower === iphoneProduct.slug) return iphoneProduct; + if (lower === galaxyProduct.slug) return galaxyProduct; + if (lower === macbookProduct.slug) return macbookProduct; + return null; + }, + getCachedMasterProductOffers: async (id) => { + if (id === iphoneProduct.id) return sampleOffersForIphone; + if (id === galaxyProduct.id) return sampleOffersForGalaxy; + return [ + makeOffer({ + id: `offer-${id}-1`, + platform: 'cellphones', + price_current: 15_990_000, + }), + makeOffer({ + id: `offer-${id}-2`, + platform: 'fptshop', + price_current: 16_490_000, + }), + ]; + }, + getCachedMasterProductReviews: async () => [], + getCachedMasterProductReviewSummary: + async (): Promise => ({ + total_analyzed: 48, + authentic_pct: 88, + suspicious_pct: 8, + fake_pct: 4, + pros: [ + 'Excellent 5x tetraprism camera', + 'Cool thermals under sustained load', + ], + cons: ['30W wired charging is slower than peers'], + ai_summary: + 'Verified buyers praise camera consistency and battery life.', + }), + getCachedMasterProductPriceHistory: + async (): Promise => ({ + points: [ + { + id: 1, + product_id: 'offer-cps-official', + merchant_name: 'CELLPHONES Official', + platform: 'cellphones', + is_official: true, + price: 28_990_000, + price_original: 34_990_000, + recorded_at: '2026-11-22T13:45:00.000Z', + source: 'crawler', + }, + ], + byOffer: { + 'offer-cps-official': { + product_id: 'offer-cps-official', + merchant_name: 'CELLPHONES Official', + platform: 'cellphones', + price_current: 28_990_000, + price_original: 34_990_000, + claimed_discount_pct: 17, + real_discount_vs_median_pct: 4.9, + historical_min_price: 28_790_000, + historical_max_price: 33_990_000, + historical_median_price: 30_490_000, + observation_count: 14, + verdict: 'genuine_deal', + badge_label: 'Genuine Deal', + explanation: '4.9% below historical median.', + }, + }, + lowestEverPrice: 28_790_000, + lowestEverDate: '2026-11-11T00:00:00.000Z', + lowestEverMerchant: 'CELLPHONES Official', + highestEverPrice: 33_990_000, + currentMinPrice: 28_990_000, + fakeDiscountCount: 0, + genuineDealCount: 2, + }), + getCachedCompareMasterProducts: async (csv) => { + const slugs = csv.split(',').map((s) => s.trim().toLowerCase()); + const matched = slugs + .map((s) => { + if (s === iphoneProduct.slug) return iphoneProduct; + if (s === galaxyProduct.slug) return galaxyProduct; + if (s === macbookProduct.slug) return macbookProduct; + return null; + }) + .filter((p): p is MasterProduct => p !== null); + if (matched.length === 0) return []; + const firstCat = + (matched[0]!.metadata as { category_slug?: string })?.category_slug ?? + 'smartphones'; + return matched.filter( + (p) => + ((p.metadata as { category_slug?: string })?.category_slug ?? + 'smartphones') === firstCat + ); + }, + getCachedFilteredReviewCountsByMaster: async () => ({ + [iphoneProduct.id]: 6, + [galaxyProduct.id]: 3, + }), + getCachedInspectProductOrShopUrl: async ( + rawQuery + ): Promise => ({ + query: rawQuery, + matchedType: 'product_listing', + parsedUrl: parseEcommerceUrlOrQuery(rawQuery), + masterProduct: iphoneProduct, + matchedOffer: sampleOffersForIphone[3]!, + allOffers: sampleOffersForIphone, + discountAnalysis: null, + priceHistory: null, + reviewSummary: null, + merchantProfile: null, + suggestions: [galaxyProduct], + }), + getCrossPlatformDealRadar: async ( + opts + ): Promise => { + const deals = Array.from({ length: 12 }, (_, idx) => ({ + id: `deal-phone-${idx + 1}`, + verdict: + idx === 0 + ? ('genuine_all_time_low' as const) + : ('best_market_deal' as const), + verdictBadgeVi: 'Giá Tốt Nhất Hiện Có', + productSlug: idx === 0 ? iphoneProduct.slug : `sample-phone-${idx + 1}`, + productName: idx === 0 ? iphoneProduct.name : `Sample Phone ${idx + 1}`, + brand: idx % 2 === 0 ? 'Apple' : 'Samsung', + categorySlug: 'smartphones' as const, + productHref: `/smartphones/${idx === 0 ? iphoneProduct.slug : `sample-phone-${idx + 1}`}`, + imageUrl: '/img/devices/apple-iphone-16-pro-max-256gb.jpg', + platform: idx % 2 === 0 ? 'cellphones' : 'shopee', + merchantId: `merchant-${idx + 1}`, + merchantName: + idx % 2 === 0 ? 'CellphoneS Official' : 'Third-Party Shop', + isOfficialMall: idx % 2 === 0, + merchantRiskScore: 8, + offerUrl: 'https://cellphones.com.vn/iphone-16-pro-max.html', + priceCurrent: 18_000_000 + idx * 2_000_000, + priceOriginal: 22_000_000 + idx * 2_000_000, + marketMedianPrice: 20_500_000 + idx * 2_000_000, + marketMinPrice: 18_000_000 + idx * 2_000_000, + marketMaxPrice: 23_000_000 + idx * 2_000_000, + savingsVsMedianVnd: 2_500_000, + savingsVsMedianPct: 11.2, + marketOfferCount: 6, + claimedDiscountPct: 18, + fakeMarkupPct: 0, + jreviewsScore10: 9.4, + explanationVi: 'Rẻ hơn trung vị.', + })); + return { + generatedAt: FIXED_NOW_ISO, + categoryFilter: opts?.categorySlug ?? 'all', + platformFilter: opts?.platform ?? 'all', + totalClustersAnalyzed: 28, + totalOffersAnalyzed: 164, + totalMerchantsAnalyzed: 22, + genuineDeals: deals, + fakeSaleTraps: [], + priceSpreadLeaders: [], + }; + }, + }; +} + +function makeMcpRequest( + body: string | ReadableStream, + headers?: Record +): NextRequest { + const init: RequestInit & { duplex?: 'half' } = { + method: 'POST', + headers: { + 'content-type': 'application/json', + 'x-forwarded-for': '203.0.113.10', + ...headers, + }, + body, + ...(typeof body !== 'string' ? { duplex: 'half' } : {}), + }; + return new NextRequest('https://rate.vn/api/mcp', init as never); +} + +async function runMcpTestSuite() { + console.warn( + '🧪 Running Rate Shopping MCP Server & AI Discovery Test Suite...' + ); + + // 0. Source-level server-only and zero em-dash / en-dash check + const mcpSourcePath = path.resolve(__dirname, '../mcp.ts'); + const mcpSource = fs.readFileSync(mcpSourcePath, 'utf8'); + assert.ok( + mcpSource.startsWith("import 'server-only';"), + "mcp.ts must start with import 'server-only';" + ); + for (const [label, text] of [ + ['mcp.ts', mcpSource], + ['/llms.txt', buildRateLlmsTxt()], + [ + '/.well-known/mcp.json', + JSON.stringify(buildRateWellKnownMcpDescriptor()), + ], + ] as const) { + assert.equal( + /[\u2013\u2014]/.test(text), + false, + `${label} must contain zero em-dashes or en-dashes` + ); + } + + // 1. Route HTTP method guards (GET -> 405, DELETE -> 405, OPTIONS -> 204) + const getRes = await getMcpRoute(); + assert.equal(getRes.status, 405); + assert.equal(getRes.headers.get('allow'), 'POST, OPTIONS'); + assert.equal(getRes.headers.get('access-control-allow-origin'), '*'); + const getErrJson = (await getRes.json()) as { + jsonrpc: string; + error: { code: number }; + }; + assert.equal(getErrJson.jsonrpc, '2.0'); + assert.equal(getErrJson.error.code, -32600); + + const deleteRes = await deleteMcpRoute(); + assert.equal(deleteRes.status, 405); + assert.equal(deleteRes.headers.get('allow'), 'POST, OPTIONS'); + + const optRes = await optionsMcpRoute(); + assert.equal(optRes.status, 204); + assert.equal(optRes.headers.get('allow'), 'POST, OPTIONS'); + assert.equal( + optRes.headers.get('access-control-allow-methods'), + 'POST, OPTIONS' + ); + + const readers = createMockReaders(); + const limiter = new BoundedSlidingWindowRateLimiter({ + windowMs: 60_000, + maxRequests: 100, + }); + const auditLimiter = new BoundedSlidingWindowRateLimiter({ + windowMs: 60_000, + maxRequests: 100, + }); + + // 2. initialize (2025-06-18, 2025-03-26 backward compatibility, and unknown version negotiation) + const initRes = await postMcpRoute( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 1, + method: 'initialize', + params: { + protocolVersion: '2025-06-18', + capabilities: {}, + clientInfo: { name: 'claude-desktop', version: '1.2.0' }, + }, + }) + ) + ); + assert.equal(initRes.status, 200); + assert.equal( + initRes.headers.get('mcp-protocol-version'), + MCP_LATEST_PROTOCOL_VERSION + ); + const initBody = (await initRes.json()) as { + jsonrpc: string; + id: number; + result: { + protocolVersion: string; + capabilities: { tools: { listChanged: boolean } }; + serverInfo: { name: string }; + }; + }; + assert.equal(initBody.jsonrpc, '2.0'); + assert.equal(initBody.id, 1); + assert.equal(initBody.result.protocolVersion, '2025-06-18'); + assert.equal(initBody.result.capabilities.tools.listChanged, false); + assert.equal(initBody.result.serverInfo.name, 'rate-vn-shopping-mcp'); + + const initLegacyRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'init-legacy', + method: 'initialize', + params: { protocolVersion: '2025-03-26' }, + }) + ), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + assert.equal(initLegacyRes.status, 200); + assert.equal(initLegacyRes.headers.get('mcp-protocol-version'), '2025-03-26'); + const initLegacyJson = (await initLegacyRes.json()) as { + result: { protocolVersion: string }; + }; + assert.equal(initLegacyJson.result.protocolVersion, '2025-03-26'); + + const initFutureRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'init-future', + method: 'initialize', + params: { protocolVersion: '2099-01-01' }, + }) + ), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + assert.equal(initFutureRes.status, 200); + const initFutureJson = (await initFutureRes.json()) as { + result: { protocolVersion: string }; + }; + assert.equal(initFutureJson.result.protocolVersion, '2025-06-18'); + + // 3. notifications/initialized (202 Accepted without id, 200 JSON-RPC ack with id) & ping + const notifRes = await postMcpRoute( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + method: 'notifications/initialized', + }) + ) + ); + assert.equal(notifRes.status, 202); + assert.equal(await notifRes.text(), ''); + + const notifWithIdRes = await postMcpRoute( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'notif-1', + method: 'notifications/initialized', + }) + ) + ); + assert.equal(notifWithIdRes.status, 200); + assert.deepEqual(await notifWithIdRes.json(), { + jsonrpc: '2.0', + id: 'notif-1', + result: {}, + }); + + const pingRes = await postMcpRoute( + makeMcpRequest(JSON.stringify({ jsonrpc: '2.0', id: 7, method: 'ping' })) + ); + assert.equal(pingRes.status, 200); + assert.deepEqual(await pingRes.json(), { + jsonrpc: '2.0', + id: 7, + result: {}, + }); + + // 4. tools/list & Zod 4 JSON Schema verification + const listRes = await postMcpRoute( + makeMcpRequest( + JSON.stringify({ jsonrpc: '2.0', id: 'list-1', method: 'tools/list' }) + ) + ); + assert.equal(listRes.status, 200); + const listJson = (await listRes.json()) as { + result: { tools: typeof MCP_TOOL_DEFINITIONS }; + }; + assert.equal(listJson.result.tools.length, 5); + assert.deepEqual( + listJson.result.tools.map((t) => t.name), + [ + 'search_verified_catalog', + 'get_22_store_offers_and_price_truth', + 'compare_devices_by_use_case', + 'audit_listing_url', + 'get_genuine_deals', + ] + ); + for (const tool of listJson.result.tools) { + assert.equal(tool.inputSchema.type, 'object'); + assert.equal(tool.inputSchema.additionalProperties, false); + assert.equal(tool.annotations.readOnlyHint, true); + assert.equal(tool.annotations.destructiveHint, false); + } + const offersSchema = listJson.result.tools.find( + (t) => t.name === 'get_22_store_offers_and_price_truth' + )!.inputSchema as { + required?: string[]; + properties: Record; + }; + assert.deepEqual(offersSchema.required, ['slug']); + assert.equal(offersSchema.properties.limit?.maximum, MAX_MCP_RESULT_ITEMS); + + // 5. Tool 1: search_verified_catalog (caps <= 10, excludes bait/sold-out, includes citations + freshness) + const searchRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'call-search', + method: 'tools/call', + params: { + name: 'search_verified_catalog', + arguments: { category: 'smartphones', limit: 10 }, + }, + }) + ), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + assert.equal(searchRes.status, 200); + const searchJson = (await searchRes.json()) as { + result: { + isError?: boolean; + content: Array<{ type: string; text: string }>; + structuredContent: { + ok: boolean; + returned_count: number; + canonical_citation_url: string; + observed_at: string; + items: Array<{ + slug: string; + verified_min_price_vnd: number | null; + excluded_unavailable_offer_count: number; + excluded_bait_offer_count: number; + canonical_citation_url: string; + observed_at: string; + price_observed_at: string; + }>; + }; + }; + }; + assert.equal(searchJson.result.isError, undefined); + assert.equal(searchJson.result.structuredContent.ok, true); + assert.equal(searchJson.result.structuredContent.returned_count, 10); + assert.equal( + searchJson.result.structuredContent.canonical_citation_url, + 'https://rate.vn/smartphones' + ); + const firstSearchItem = searchJson.result.structuredContent.items[0]!; + assert.equal(firstSearchItem.slug, 'apple-iphone-16-pro-max-256gb'); + // Bait 89k case and 25.99M sold-out listing must be excluded -> floor is 28,990,000 VND! + assert.equal(firstSearchItem.verified_min_price_vnd, 28_990_000); + assert.equal(firstSearchItem.excluded_unavailable_offer_count, 1); + assert.equal(firstSearchItem.excluded_bait_offer_count, 1); + for (const item of searchJson.result.structuredContent.items) { + assert.ok( + item.canonical_citation_url.startsWith(`${CANONICAL_RATE_ORIGIN}/`) + ); + assert.ok(Date.parse(item.observed_at) > 0); + assert.ok(Date.parse(item.price_observed_at) > 0); + } + assert.deepEqual( + JSON.parse(searchJson.result.content[0]!.text), + searchJson.result.structuredContent + ); + + // 6. Tool 2: get_22_store_offers_and_price_truth + const offersRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'call-offers', + method: 'tools/call', + params: { + name: 'get_22_store_offers_and_price_truth', + arguments: { + slug: 'apple-iphone-16-pro-max-256gb', + officialOnly: true, + limit: 10, + }, + }, + }) + ), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + assert.equal(offersRes.status, 200); + const offersBody = (await offersRes.json()) as { + result: { + structuredContent: { + ok: boolean; + canonical_citation_url: string; + price_observed_at: string; + price_truth: { + verified_min_price_vnd: number; + excluded_unavailable_offer_count: number; + excluded_bait_offer_count: number; + }; + review_trust_summary: { + trust_model: string; + authentic_pct: number; + }; + offers: Array<{ + id: string; + price_current_vnd: number; + merchant: { review_risk_score: number | null }; + canonical_citation_url: string; + price_observed_at: string; + }>; + }; + }; + }; + const offersData = offersBody.result.structuredContent; + assert.equal(offersData.ok, true); + assert.equal( + offersData.canonical_citation_url, + 'https://rate.vn/smartphones/apple-iphone-16-pro-max-256gb' + ); + assert.equal(offersData.price_observed_at, '2026-11-22T13:45:00.000Z'); + assert.equal(offersData.price_truth.verified_min_price_vnd, 28_990_000); + assert.equal(offersData.price_truth.excluded_unavailable_offer_count, 1); + assert.equal(offersData.price_truth.excluded_bait_offer_count, 1); + assert.equal( + offersData.review_trust_summary.trust_model, + 'review_trust_v2_6_axis' + ); + assert.equal(offersData.review_trust_summary.authentic_pct, 88); + assert.equal(offersData.offers.length, 3); + assert.equal(offersData.offers[0]!.id, 'offer-cps-official'); + // Merchant with 0 analysed reviews must report null review_risk_score (#1376) + const shopeeOffer = offersData.offers.find( + (o) => o.id === 'offer-shopee-mall' + )!; + assert.equal(shopeeOffer.merchant.review_risk_score, null); + for (const offer of offersData.offers) { + assert.equal( + offer.canonical_citation_url, + 'https://rate.vn/smartphones/apple-iphone-16-pro-max-256gb#offers-table' + ); + assert.ok(Date.parse(offer.price_observed_at) > 0); + } + + // Not-found slug returns domain isError: true with citation URL + const missingSlugRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'call-missing-slug', + method: 'tools/call', + params: { + name: 'get_22_store_offers_and_price_truth', + arguments: { slug: 'unknown-device-slug-2026' }, + }, + }) + ), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + const missingSlugJson = (await missingSlugRes.json()) as { + result: { + isError: boolean; + structuredContent: { ok: boolean; canonical_citation_url: string }; + }; + }; + assert.equal(missingSlugJson.result.isError, true); + assert.equal(missingSlugJson.result.structuredContent.ok, false); + assert.equal( + missingSlugJson.result.structuredContent.canonical_citation_url, + CANONICAL_RATE_ORIGIN + ); + + // 7. Tool 3: compare_devices_by_use_case (weight overrides shift winner & cross-category check) + const comparePhotoRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'call-compare-photo', + method: 'tools/call', + params: { + name: 'compare_devices_by_use_case', + arguments: { + slugs: [ + 'apple-iphone-16-pro-max-256gb', + 'samsung-galaxy-s25-ultra-256gb', + ], + weights: { + camera: 90, + screen: 0, + performance: 0, + battery: 0, + value: 10, + }, + }, + }, + }) + ), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + const comparePhotoJson = (await comparePhotoRes.json()) as { + result: { + structuredContent: { + ok: boolean; + recommended_slug_for_use_case: string; + canonical_citation_url: string; + devices: Array<{ + slug: string; + canonical_citation_url: string; + observed_at: string; + }>; + }; + }; + }; + assert.equal(comparePhotoJson.result.structuredContent.ok, true); + assert.equal( + comparePhotoJson.result.structuredContent.recommended_slug_for_use_case, + 'apple-iphone-16-pro-max-256gb' + ); + assert.ok( + comparePhotoJson.result.structuredContent.canonical_citation_url.startsWith( + 'https://rate.vn/compare?cat=smartphones&slugs=' + ) + ); + + const compareValueRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'call-compare-value', + method: 'tools/call', + params: { + name: 'compare_devices_by_use_case', + arguments: { + slugs: [ + 'apple-iphone-16-pro-max-256gb', + 'samsung-galaxy-s25-ultra-256gb', + ], + weights: { + camera: 0, + screen: 0, + performance: 10, + battery: 40, + value: 50, + }, + }, + }, + }) + ), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + const compareValueJson = (await compareValueRes.json()) as { + result: { structuredContent: { recommended_slug_for_use_case: string } }; + }; + assert.equal( + compareValueJson.result.structuredContent.recommended_slug_for_use_case, + 'samsung-galaxy-s25-ultra-256gb' + ); + + const crossCatRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'call-compare-cross', + method: 'tools/call', + params: { + name: 'compare_devices_by_use_case', + arguments: { + slugs: [ + 'apple-iphone-16-pro-max-256gb', + 'apple-macbook-air-m3-16gb-256gb', + ], + }, + }, + }) + ), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + const crossCatJson = (await crossCatRes.json()) as { + result: { + isError: boolean; + structuredContent: { excluded_cross_category_slugs: string[] }; + }; + }; + assert.equal(crossCatJson.result.isError, true); + assert.deepEqual( + crossCatJson.result.structuredContent.excluded_cross_category_slugs, + ['apple-macbook-air-m3-16gb-256gb'] + ); + + // 8. Tool 4: audit_listing_url + SSRF / unsupported host rejection + const auditRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'call-audit', + method: 'tools/call', + params: { + name: 'audit_listing_url', + arguments: { + url: 'https://shopee.vn/Apple-iPhone-16-Pro-Max-i.88201679.27110898667?utm_source=fb&sp_atk=xyz', + observedPriceVnd: 29_490_000, + observedOriginalPriceVnd: 45_990_000, + }, + }, + }) + ), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + const auditJson = (await auditRes.json()) as { + result: { + structuredContent: { + ok: boolean; + canonical_listing_url: string; + canonical_citation_url: string; + inspect_citation_url: string; + observed_at: string; + merchant_risk_summary: { review_risk_score: number | null }; + top_competing_offers: Array<{ canonical_citation_url: string }>; + }; + }; + }; + assert.equal(auditJson.result.structuredContent.ok, true); + assert.ok( + !auditJson.result.structuredContent.canonical_listing_url.includes( + 'utm_source' + ) + ); + assert.equal( + auditJson.result.structuredContent.canonical_citation_url, + 'https://rate.vn/smartphones/apple-iphone-16-pro-max-256gb' + ); + assert.equal( + auditJson.result.structuredContent.merchant_risk_summary.review_risk_score, + null + ); + assert.ok( + auditJson.result.structuredContent.top_competing_offers.length <= 5 + ); + + for (const badUrl of [ + 'http://localhost:3000/secret', + 'http://127.0.0.1/admin', + 'javascript:alert(1)', + 'https://evil.example/product/123', + ]) { + const badUrlRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'bad-url', + method: 'tools/call', + params: { name: 'audit_listing_url', arguments: { url: badUrl } }, + }) + ), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + const badUrlJson = (await badUrlRes.json()) as { error: { code: number } }; + assert.equal( + badUrlJson.error.code, + -32602, + `must reject unsafe URL ${badUrl}` + ); + } + + // 9. Tool 5: get_genuine_deals (caps <= 10, filters officialOnly & maxBudgetVnd) + const dealsRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'call-deals', + method: 'tools/call', + params: { + name: 'get_genuine_deals', + arguments: { + category: 'smartphones', + officialOnly: true, + maxBudgetVnd: 30_000_000, + limit: 10, + }, + }, + }) + ), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + const dealsJson = (await dealsRes.json()) as { + result: { + structuredContent: { + ok: boolean; + canonical_citation_url: string; + deals: Array<{ + is_official_mall: boolean; + price_current_vnd: number; + canonical_citation_url: string; + observed_at: string; + }>; + }; + }; + }; + assert.equal(dealsJson.result.structuredContent.ok, true); + assert.equal( + dealsJson.result.structuredContent.canonical_citation_url, + 'https://rate.vn/deals' + ); + assert.ok( + dealsJson.result.structuredContent.deals.length > 0 && + dealsJson.result.structuredContent.deals.length <= MAX_MCP_RESULT_ITEMS + ); + for (const deal of dealsJson.result.structuredContent.deals) { + assert.equal(deal.is_official_mall, true); + assert.ok(deal.price_current_vnd <= 30_000_000); + assert.ok( + deal.canonical_citation_url.startsWith('https://rate.vn/smartphones/') + ); + assert.equal(deal.observed_at, FIXED_NOW_ISO); + } + + // 10. Security & anti-DoS guards: oversize body (413 / -32600), streamed oversize, Content-Type (415), + // batch arrays, invalid JSON-RPC, prototype keys, lone surrogates, rate limit 429, and error sanitization + const oversizeHeaderRes = await handleMcpHttpPost( + makeMcpRequest('{"jsonrpc":"2.0","id":1,"method":"ping"}', { + 'content-length': String(MAX_MCP_BODY_BYTES + 1), + }), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + assert.equal(oversizeHeaderRes.status, 413); + const oversizeHeaderJson = (await oversizeHeaderRes.json()) as { + error: { code: number; data: { code: string } }; + }; + assert.equal(oversizeHeaderJson.error.code, -32600); + assert.equal(oversizeHeaderJson.error.data.code, 'PAYLOAD_TOO_LARGE'); + + let streamedBytes = 0; + const hugeStream = new ReadableStream({ + pull(controller) { + streamedBytes += 4096; + if (streamedBytes > 128 * 1024) controller.close(); + else controller.enqueue(new Uint8Array(4096).fill(65)); + }, + }); + const oversizeStreamRes = await handleMcpHttpPost( + makeMcpRequest(hugeStream), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + assert.equal(oversizeStreamRes.status, 413); + assert.ok( + streamedBytes <= MAX_MCP_BODY_BYTES + 8192, + `oversize stream cancelled early at ${streamedBytes} bytes` + ); + + // Exact 16384-byte valid JSON body passes size guard + const padPrefix = '{"jsonrpc":"2.0","id":"'; + const padSuffix = '","method":"ping"}'; + const exact16kId = 'x'.repeat(200); + const exactPadded = + `${padPrefix}${exact16kId}${padSuffix}` + + ' '.repeat( + MAX_MCP_BODY_BYTES - + Buffer.byteLength(`${padPrefix}${exact16kId}${padSuffix}`, 'utf8') + ); + assert.equal(Buffer.byteLength(exactPadded, 'utf8'), MAX_MCP_BODY_BYTES); + const exact16kRes = await handleMcpHttpPost(makeMcpRequest(exactPadded), { + readers, + rateLimiter: limiter, + auditUrlRateLimiter: auditLimiter, + }); + assert.equal(exact16kRes.status, 200); + + // Wrong Content-Type -> 415 + const wrongCtRes = await handleMcpHttpPost( + makeMcpRequest('{"jsonrpc":"2.0","id":1,"method":"ping"}', { + 'content-type': 'text/plain', + }), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + assert.equal(wrongCtRes.status, 415); + + // Batch array -> 400 -32600 + const batchRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify([ + { jsonrpc: '2.0', id: 1, method: 'ping' }, + { jsonrpc: '2.0', id: 2, method: 'ping' }, + ]) + ), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + assert.equal(batchRes.status, 400); + assert.equal( + ((await batchRes.json()) as { error: { code: number } }).error.code, + -32600 + ); + + // Invalid JSON & invalid JSON-RPC envelopes + const badJsonRes = await handleMcpHttpPost(makeMcpRequest('{broken'), { + readers, + rateLimiter: limiter, + auditUrlRateLimiter: auditLimiter, + }); + assert.equal(badJsonRes.status, 400); + assert.equal( + ((await badJsonRes.json()) as { error: { code: number } }).error.code, + -32700 + ); + + for (const invalidEnvelope of [ + '{"jsonrpc":"1.0","id":1,"method":"ping"}', + '{"jsonrpc":"2.0","id":null,"method":"ping"}', + '{"jsonrpc":"2.0","method":"tools/list"}', + '{"jsonrpc":"2.0","id":{},"method":"ping"}', + ]) { + const res = await handleMcpHttpPost(makeMcpRequest(invalidEnvelope), { + readers, + rateLimiter: limiter, + auditUrlRateLimiter: auditLimiter, + }); + assert.equal(res.status, 400); + assert.equal( + ((await res.json()) as { error: { code: number } }).error.code, + -32600 + ); + } + + // Prototype pollution keys rejected at root, params, and nested arguments + for (const protoPayload of [ + '{"jsonrpc":"2.0","id":1,"method":"ping","__proto__":{"polluted":true}}', + '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"get_genuine_deals","arguments":{"constructor":{"prototype":{"polluted":true}}}}}', + '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"prototype":{}}}', + ]) { + const protoRes = await handleMcpHttpPost(makeMcpRequest(protoPayload), { + readers, + rateLimiter: limiter, + auditUrlRateLimiter: auditLimiter, + }); + assert.equal(protoRes.status, 400); + assert.equal( + ((await protoRes.json()) as { error: { code: number } }).error.code, + -32600 + ); + assert.equal( + ({} as Record).polluted, + undefined, + 'Object.prototype must never be polluted' + ); + } + + // Lone UTF-16 surrogate sanitization via .toWellFormed() + let capturedWellFormedSearch = ''; + const surrogateRes = await handleMcpHttpPost( + makeMcpRequest( + '{"jsonrpc":"2.0","id":"surr-1","method":"tools/call","params":{"name":"search_verified_catalog","arguments":{"query":"iPhone \\uD800 16"}}}' + ), + { + readers: { + ...readers, + getCachedMasterProducts: async (p) => { + capturedWellFormedSearch = p?.search ?? ''; + return [iphoneProduct]; + }, + }, + rateLimiter: limiter, + auditUrlRateLimiter: auditLimiter, + } + ); + assert.equal(surrogateRes.status, 200); + assert.equal(capturedWellFormedSearch, 'iPhone \uFFFD 16'); + + // Strict Zod 4 rejection of limit > 10 and unknown extra arguments + for (const invalidCallArgs of [ + { category: 'smartphones', limit: 11 }, + { category: 'smartphones', offset: 20 }, + { minPriceVnd: 30_000_000, maxPriceVnd: 10_000_000 }, + ]) { + const badArgsRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'bad-args', + method: 'tools/call', + params: { + name: 'search_verified_catalog', + arguments: invalidCallArgs, + }, + }) + ), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + assert.equal(badArgsRes.status, 200); + assert.equal( + ((await badArgsRes.json()) as { error: { code: number } }).error.code, + -32602 + ); + } + + // Unknown method (-32601) and unknown tool (-32602) + const unknownMethodRes = await handleMcpHttpPost( + makeMcpRequest('{"jsonrpc":"2.0","id":9,"method":"resources/list"}'), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + assert.equal( + ((await unknownMethodRes.json()) as { error: { code: number } }).error.code, + -32601 + ); + + const unknownToolRes = await handleMcpHttpPost( + makeMcpRequest( + '{"jsonrpc":"2.0","id":10,"method":"tools/call","params":{"name":"drop_database","arguments":{}}}' + ), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + assert.equal( + ((await unknownToolRes.json()) as { error: { code: number } }).error.code, + -32602 + ); + + // Internal DB error sanitization (never leak PGRST / table / schema names) + const dbFailRes = await handleMcpHttpPost( + makeMcpRequest( + '{"jsonrpc":"2.0","id":"db-err","method":"tools/call","params":{"name":"get_genuine_deals","arguments":{}}}' + ), + { + readers: { + ...readers, + getCrossPlatformDealRadar: async () => { + throw new Error( + 'PGRST116: relation "rate.master_products" does not exist in schema "rate" on supabase' + ); + }, + }, + rateLimiter: limiter, + auditUrlRateLimiter: auditLimiter, + } + ); + assert.equal(dbFailRes.status, 200); + const dbFailText = await dbFailRes.text(); + assert.doesNotMatch( + dbFailText, + /PGRST|master_products|schema|supabase/i, + 'must never leak internal database details' + ); + const dbFailParsed = JSON.parse(dbFailText) as { + result: { isError: boolean }; + }; + assert.equal(dbFailParsed.result.isError, true); + + // Rate limit 429 + Retry-After on both overall MCP limiter and audit_listing_url limiter + const strictLimiter = new BoundedSlidingWindowRateLimiter({ + windowMs: 60_000, + maxRequests: 2, + }); + for (let i = 0; i < 2; i++) { + const ok = await handleMcpHttpPost( + makeMcpRequest('{"jsonrpc":"2.0","id":1,"method":"ping"}', { + 'x-forwarded-for': '198.51.100.77', + }), + { readers, rateLimiter: strictLimiter, auditUrlRateLimiter: auditLimiter } + ); + assert.equal(ok.status, 200); + } + const rlRes = await handleMcpHttpPost( + makeMcpRequest('{"jsonrpc":"2.0","id":3,"method":"ping"}', { + 'x-forwarded-for': '198.51.100.77', + }), + { readers, rateLimiter: strictLimiter, auditUrlRateLimiter: auditLimiter } + ); + assert.equal(rlRes.status, 429); + assert.equal(rlRes.headers.get('retry-after'), '60'); + assert.match( + rlRes.headers.get('access-control-expose-headers') ?? '', + /Retry-After/ + ); + const rlJson = (await rlRes.json()) as { + error: { code: number; data: { code: string } }; + }; + assert.equal(rlJson.error.code, -32029); + assert.equal(rlJson.error.data.code, 'RATE_LIMIT_EXCEEDED'); + + const strictAuditLimiter = new BoundedSlidingWindowRateLimiter({ + windowMs: 60_000, + maxRequests: 1, + }); + const auditOk = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'a1', + method: 'tools/call', + params: { + name: 'audit_listing_url', + arguments: { + url: 'https://cellphones.com.vn/iphone-16-pro-max.html', + }, + }, + }), + { 'x-forwarded-for': '198.51.100.88' } + ), + { readers, rateLimiter: limiter, auditUrlRateLimiter: strictAuditLimiter } + ); + assert.equal(auditOk.status, 200); + const auditRl = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'a2', + method: 'tools/call', + params: { + name: 'audit_listing_url', + arguments: { + url: 'https://cellphones.com.vn/iphone-16-pro-max.html', + }, + }, + }), + { 'x-forwarded-for': '198.51.100.88' } + ), + { readers, rateLimiter: limiter, auditUrlRateLimiter: strictAuditLimiter } + ); + assert.equal(auditRl.status, 429); + assert.equal(auditRl.headers.get('retry-after'), '60'); + + // 11. /llms.txt and /.well-known/mcp.json route handlers + const llmsRes = await getLlmsTxtRoute(); + assert.equal(llmsRes.status, 200); + assert.equal( + llmsRes.headers.get('content-type'), + 'text/plain; charset=utf-8' + ); + assert.equal( + llmsRes.headers.get('cache-control'), + 'public, s-maxage=3600, stale-while-revalidate=86400' + ); + const llmsAllowHeaders = + llmsRes.headers.get('access-control-allow-headers') ?? ''; + assert.match(llmsAllowHeaders, /MCP-Protocol-Version/); + assert.match(llmsAllowHeaders, /Accept/); + const llmsBody = await llmsRes.text(); + for (const expectedFragment of [ + 'https://rate.vn/api/mcp', + 'https://rate.vn/.well-known/mcp.json', + 'https://rate.vn/api/v1/rate/openapi.json', + 'search_verified_catalog', + 'get_22_store_offers_and_price_truth', + 'compare_devices_by_use_case', + 'audit_listing_url', + 'get_genuine_deals', + '6-axis Review Trust Model v2', + 'anphatpc', + 'availability', + 'design', + 'display', + 'hardware', + 'battery', + 'camera', + 'connectivity', + 'cellular', + 'multimedia', + 'regulatory', + ]) { + assert.ok( + llmsBody.includes(expectedFragment), + `/llms.txt must mention ${expectedFragment}` + ); + } + + const wkRes = await getWellKnownMcpRoute(); + assert.equal(wkRes.status, 200); + assert.match(wkRes.headers.get('content-type') ?? '', /application\/json/); + assert.match( + wkRes.headers.get('access-control-allow-headers') ?? '', + /MCP-Protocol-Version/ + ); + assert.equal( + wkRes.headers.get('cache-control'), + 'public, s-maxage=3600, stale-while-revalidate=86400' + ); + const wkJson = (await wkRes.json()) as { + mcpVersion: string; + transport: string; + url: string; + endpoints: { mcp: string; transport: string }; + tools: Array<{ name: string }>; + }; + assert.equal(wkJson.mcpVersion, '2025-06-18'); + assert.equal(wkJson.transport, 'streamable-http'); + assert.equal(wkJson.url, 'https://rate.vn/api/mcp'); + assert.equal(wkJson.endpoints.mcp, 'https://rate.vn/api/mcp'); + assert.equal(wkJson.endpoints.transport, 'streamable-http'); + assert.equal(wkJson.tools.length, 5); + + // 12. Round-1 review regressions (protocol headers, stream errors, IDs, price filters, synthetic points, DOSafe masking, compare deduplication) + // 12a. audit_listing_url canonicalizes tracking params BEFORE getCachedInspectProductOrShopUrl and handles rate.vn dotted paths safely + let capturedInspectQuery = ''; + const canonicalAuditRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'audit-canon', + method: 'tools/call', + params: { + name: 'audit_listing_url', + arguments: { + url: 'https://shopee.vn/Apple-iPhone-16-Pro-Max-i.88201679.27110898667?utm_source=zalo&sp_atk=abc123&fbclid=xyz', + }, + }, + }) + ), + { + readers: { + ...readers, + getCachedInspectProductOrShopUrl: async (rawQuery) => { + capturedInspectQuery = rawQuery; + return readers.getCachedInspectProductOrShopUrl(rawQuery); + }, + }, + rateLimiter: limiter, + auditUrlRateLimiter: auditLimiter, + } + ); + assert.equal(canonicalAuditRes.status, 200); + assert.ok( + !capturedInspectQuery.includes('utm_source') && + !capturedInspectQuery.includes('sp_atk') && + !capturedInspectQuery.includes('fbclid'), + `expected canonicalized URL before cache reader, got: ${capturedInspectQuery}` + ); + + for (const allowedRateUrl of [ + 'https://rate.vn/smartphones/nokia-8.1', + 'https://rate.vn/merchants/anker.vn', + ]) { + const okRateUrlRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'ok-rate-url', + method: 'tools/call', + params: { + name: 'audit_listing_url', + arguments: { url: allowedRateUrl }, + }, + }) + ), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + const okRateUrlJson = (await okRateUrlRes.json()) as { + result?: { structuredContent: { ok: boolean } }; + error?: unknown; + }; + assert.equal( + okRateUrlJson.error, + undefined, + `must allow ${allowedRateUrl}` + ); + assert.equal(okRateUrlJson.result?.structuredContent.ok, true); + } + + for (const rejectedRateUrl of [ + 'https://rate.vn/merchants/..', + 'https://rate.vn/api/mcp', + ]) { + const rejRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'rej-rate-url', + method: 'tools/call', + params: { + name: 'audit_listing_url', + arguments: { url: rejectedRateUrl }, + }, + }) + ), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + assert.equal( + ((await rejRes.json()) as { error: { code: number } }).error.code, + -32602, + `must reject ${rejectedRateUrl}` + ); + } + + // 12b. Aborted/errored ReadableStream returns 400 JSON-RPC -32700 (never unhandled 500) + const abortedStream = new ReadableStream({ + pull(controller) { + controller.error(new Error('client socket reset mid-stream')); + }, + }); + const abortedRes = await handleMcpHttpPost(makeMcpRequest(abortedStream), { + readers, + rateLimiter: limiter, + auditUrlRateLimiter: auditLimiter, + }); + assert.equal(abortedRes.status, 400); + assert.equal( + ((await abortedRes.json()) as { error: { code: number } }).error.code, + -32700 + ); + + // 12c. MCP-Protocol-Version header negotiation on initialize vs strict check on ping + const initFutureHeaderRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'init-hdr', + method: 'initialize', + params: { protocolVersion: '2099-01-01' }, + }), + { 'mcp-protocol-version': '2099-01-01' } + ), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + assert.equal(initFutureHeaderRes.status, 200); + assert.equal( + initFutureHeaderRes.headers.get('mcp-protocol-version'), + '2025-06-18' + ); + + const ping202503Res = await handleMcpHttpPost( + makeMcpRequest('{"jsonrpc":"2.0","id":1,"method":"ping"}', { + 'mcp-protocol-version': '2025-03-26', + }), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + assert.equal(ping202503Res.status, 200); + assert.equal(ping202503Res.headers.get('mcp-protocol-version'), '2025-03-26'); + + const pingUnsupportedVerRes = await handleMcpHttpPost( + makeMcpRequest('{"jsonrpc":"2.0","id":1,"method":"ping"}', { + 'mcp-protocol-version': '2099-01-01', + }), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + assert.equal(pingUnsupportedVerRes.status, 400); + assert.equal( + ((await pingUnsupportedVerRes.json()) as { error: { code: number } }).error + .code, + -32600 + ); + + // 12d. search_verified_catalog enforces minPriceVnd/maxPriceVnd & price_asc on verified_min_price_vnd (never bait stored min_price) + const baitStoredFloorProduct = makeProduct({ + id: '11111111-1111-4111-8111-000000000099', + slug: 'bait-stored-floor-phone', + name: 'Bait Stored Floor Phone', + // Stored min_price polluted by 89k case, while real offer is 28.99M + min_price: 89_000, + max_price: 30_990_000, + }); + const searchPriceFilterRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'search-price-truth', + method: 'tools/call', + params: { + name: 'search_verified_catalog', + arguments: { + category: 'smartphones', + maxPriceVnd: 27_000_000, + sort: 'price_asc', + limit: 10, + }, + }, + }) + ), + { + readers: { + ...readers, + getCachedMasterProducts: async () => [ + baitStoredFloorProduct, + galaxyProduct, + ], + getCachedMasterProductOffers: async (id) => + id === baitStoredFloorProduct.id + ? sampleOffersForIphone + : sampleOffersForGalaxy, + }, + rateLimiter: limiter, + auditUrlRateLimiter: auditLimiter, + } + ); + const searchPriceFilterJson = (await searchPriceFilterRes.json()) as { + result: { + structuredContent: { + items: Array<{ slug: string; verified_min_price_vnd: number }>; + }; + }; + }; + assert.deepEqual( + searchPriceFilterJson.result.structuredContent.items.map((i) => i.slug), + ['samsung-galaxy-s25-ultra-256gb'] + ); + + // 12e. get_22_store_offers_and_price_truth ignores synthetic live_listing / id < 0 points and sold-out offer timestamps, and masks dosafe_risk_known: false -> null (#1465) + const syntheticHistRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'offers-synth', + method: 'tools/call', + params: { + name: 'get_22_store_offers_and_price_truth', + arguments: { slug: 'apple-iphone-16-pro-max-256gb' }, + }, + }) + ), + { + readers: { + ...readers, + getCachedMasterProductPriceHistory: async () => ({ + points: [ + { + id: -1, + product_id: 'offer-cps-official', + merchant_name: 'CELLPHONES Official', + platform: 'cellphones', + is_official: true, + price: 28_990_000, + price_original: 34_990_000, + recorded_at: '2099-01-01T00:00:00.000Z', + source: 'live_listing', + }, + { + id: 2, + product_id: 'offer-sold-out', + merchant_name: 'TIKI Sold Out', + platform: 'tiki', + is_official: true, + price: 25_990_000, + price_original: 34_990_000, + recorded_at: '2098-01-01T00:00:00.000Z', + source: 'crawler', + }, + { + id: 3, + product_id: 'offer-cps-official', + merchant_name: 'CELLPHONES Official', + platform: 'cellphones', + is_official: true, + price: 28_990_000, + price_original: 34_990_000, + recorded_at: '2026-11-22T11:15:00.000Z', + source: 'crawler', + }, + ], + byOffer: {}, + lowestEverPrice: 28_790_000, + lowestEverDate: '2026-11-11T00:00:00.000Z', + lowestEverMerchant: 'CELLPHONES Official', + highestEverPrice: 33_990_000, + currentMinPrice: 28_990_000, + fakeDiscountCount: 0, + genuineDealCount: 1, + }), + }, + rateLimiter: limiter, + auditUrlRateLimiter: auditLimiter, + } + ); + const syntheticHistJson = (await syntheticHistRes.json()) as { + result: { + structuredContent: { + price_observed_at: string; + offers: Array<{ + id: string; + merchant: { + dosafe_risk_score: number | null; + review_risk_score: number | null; + }; + }>; + }; + }; + }; + assert.equal( + syntheticHistJson.result.structuredContent.price_observed_at, + '2026-11-22T11:15:00.000Z' + ); + const shopeeMasked = syntheticHistJson.result.structuredContent.offers.find( + (o) => o.id === 'offer-shopee-mall' + )!; + assert.equal(shopeeMasked.merchant.dosafe_risk_score, null); + assert.equal(shopeeMasked.merchant.review_risk_score, null); + + // 12f. JSON-RPC numeric IDs (0 and -5 allowed, fractional 1.5 & >53-bit integer rejected), Accept q=0 -> 406, enum message, and compare deduplication/not_found/unrated + for (const validNumericId of [0, -5]) { + const idOkRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ jsonrpc: '2.0', id: validNumericId, method: 'ping' }) + ), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + assert.equal(idOkRes.status, 200); + assert.equal(((await idOkRes.json()) as { id: number }).id, validNumericId); + } + + for (const unsafeIdBody of [ + '{"jsonrpc":"2.0","id":1.5,"method":"ping"}', + '{"jsonrpc":"2.0","id":9007199254740993,"method":"ping"}', + ]) { + const badIdRes = await handleMcpHttpPost(makeMcpRequest(unsafeIdBody), { + readers, + rateLimiter: limiter, + auditUrlRateLimiter: auditLimiter, + }); + assert.equal(badIdRes.status, 400); + assert.equal( + ((await badIdRes.json()) as { error: { code: number } }).error.code, + -32600 + ); + } + + const qZeroAcceptRes = await handleMcpHttpPost( + makeMcpRequest('{"jsonrpc":"2.0","id":1,"method":"ping"}', { + accept: 'application/json;q=0, text/event-stream;q=1', + }), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + assert.equal(qZeroAcceptRes.status, 406); + + const invalidPlatformRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'bad-plat', + method: 'tools/call', + params: { + name: 'get_genuine_deals', + arguments: { platform: 'amazon' }, + }, + }) + ), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + const invalidPlatformJson = (await invalidPlatformRes.json()) as { + error: { code: number; message: string }; + }; + assert.equal(invalidPlatformJson.error.code, -32602); + assert.match(invalidPlatformJson.error.message, /platform/i); + + const compareDedupRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'cmp-dedup', + method: 'tools/call', + params: { + name: 'compare_devices_by_use_case', + arguments: { + slugs: [ + 'iphone-16-pro-max', + 'apple-iphone-16-pro-max-256gb', + 'iphone-16-pro-max@999tb', + 'samsung-galaxy-s25-ultra-256gb', + ], + }, + }, + }) + ), + { readers, rateLimiter: limiter, auditUrlRateLimiter: auditLimiter } + ); + const compareDedupJson = (await compareDedupRes.json()) as { + result: { + structuredContent: { + ok: boolean; + deduplicated_slugs: string[]; + not_found_slugs: string[]; + }; + }; + }; + assert.equal(compareDedupJson.result.structuredContent.ok, true); + assert.deepEqual( + compareDedupJson.result.structuredContent.deduplicated_slugs, + ['apple-iphone-16-pro-max-256gb'] + ); + assert.deepEqual(compareDedupJson.result.structuredContent.not_found_slugs, [ + 'iphone-16-pro-max@999tb', + ]); + + // Unrated devices return recommended_slug_for_use_case: null rather than fabricating a winner + const unratedA = makeProduct({ + id: '11111111-1111-4111-8111-000000000091', + slug: 'unrated-phone-a', + name: 'Unrated Phone A', + total_reviews: 0, + average_rating: 0, + rating_score: 0, + user_rating_weighted: 0, + expert_rating: 0, + authentic_review_count: 0, + criteria_scores: {}, + }); + const unratedB = makeProduct({ + id: '11111111-1111-4111-8111-000000000092', + slug: 'unrated-phone-b', + name: 'Unrated Phone B', + total_reviews: 0, + average_rating: 0, + rating_score: 0, + user_rating_weighted: 0, + expert_rating: 0, + authentic_review_count: 0, + criteria_scores: {}, + }); + const compareUnratedRes = await handleMcpHttpPost( + makeMcpRequest( + JSON.stringify({ + jsonrpc: '2.0', + id: 'cmp-unrated', + method: 'tools/call', + params: { + name: 'compare_devices_by_use_case', + arguments: { slugs: ['unrated-phone-a', 'unrated-phone-b'] }, + }, + }) + ), + { + readers: { + ...readers, + getCachedCompareMasterProducts: async () => [unratedA, unratedB], + getCachedFilteredReviewCountsByMaster: async () => ({}), + }, + rateLimiter: limiter, + auditUrlRateLimiter: auditLimiter, + } + ); + const compareUnratedJson = (await compareUnratedRes.json()) as { + result: { + structuredContent: { + ok: boolean; + recommended_slug_for_use_case: string | null; + }; + }; + }; + assert.equal(compareUnratedJson.result.structuredContent.ok, true); + assert.equal( + compareUnratedJson.result.structuredContent.recommended_slug_for_use_case, + null + ); + + console.warn( + ' ✅ Rate Shopping MCP Server (/api/mcp), /llms.txt & /.well-known/mcp.json suite passed (#1866)' + ); +} + +runMcpTestSuite().catch((err) => { + console.error(err); + process.exit(1); +}); 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('|') ) diff --git a/apps/web/src/server/rate/mcp.ts b/apps/web/src/server/rate/mcp.ts new file mode 100644 index 00000000..f056a730 --- /dev/null +++ b/apps/web/src/server/rate/mcp.ts @@ -0,0 +1,3008 @@ +import 'server-only'; +import { NextResponse } from 'next/server'; +import { z } from 'zod'; +import { + applyCategorySpecTemplate, + normalizeOfferId, + plausibleOffers, +} from '@repo/shared-data/rules'; +import { + MAX_VALID_VND_PRICE, + getMasterProductCategorySlug, + getMasterProductHref, + normalizeOfferOriginalPrice, + parseEcommerceUrlOrQuery, + type CanonicalCategorySlug, + type MasterProduct, + type MasterProductFilterParams, + type MasterProductPriceHistorySummary, + type MerchantOffer, + type ReviewAnalysisSummary, + type ReviewItem, + type UrlInspectionResult, +} from '@/lib/rate-api'; +import { radarExportFields } from '@/lib/deal-radar'; +import { compareTarget, lookupSlugAnyCase } from '@/lib/item-compare'; +import { + LEADERBOARD_SCORE_CRITERIA, + displayedScore5, + leaderboardCriteriaForCategory, + scoreMasterProductForLeaderboard, + sharedScoredCriteria, + weightedCriteriaScore5, + type FilteredReviewCountsByMaster, + type LeaderboardCriteriaWeights, + type LeaderboardScoreCriterion, +} from '@/lib/leaderboard-engine'; +import { isOfferUnavailable } from '@/lib/product-market-stats'; +import { productRatingScore5 } from '@/lib/rate-domain'; +import { roundScore } from '@/lib/rating-display'; +import { listingCountForSaleState, saleStateOfMaster } from '@/lib/sale-state'; +import { + getCachedCompareMasterProducts, + getCachedFilteredReviewCountsByMaster, + getCachedInspectProductOrShopUrl, + getCachedMasterProductBySlug, + getCachedMasterProductOffers, + getCachedMasterProductPriceHistory, + getCachedMasterProductReviewSummary, + getCachedMasterProductReviews, + getCachedMasterProducts, + sanitizeCachedEntityId, +} from './index'; +import { + BoundedSlidingWindowRateLimiter, + SUPPORTED_PLATFORM_SLUGS, + extractClientRateLimitKey, + inspectRateLimiter, + isSafeCrowdIngestHttpUrl, + parseFiniteDecimalInput, + resolveInspectObservedPrices, + splitComparePinToken, + withPublicOfferReviewRisk, + withPublicReviewRisk, +} from './api-handler'; +import { + computeProductRadarSignal, + getCrossPlatformDealRadar, + type CrossPlatformDealRadarResponse, +} from './deals'; +import { + canonicalizeProductUrl, + detectAccessoryOrJunk, + detectPlatformFromInput, + evaluateExtensionPriceVerdict, +} from './extension'; +import { isItemModelOn } from './item-model'; +import { + getCachedCatalogSlugResolution, + getCachedItemVariants, +} from './item-route'; + +export const CANONICAL_RATE_ORIGIN = 'https://rate.vn'; +export const MCP_LATEST_PROTOCOL_VERSION = '2025-06-18'; +export const SUPPORTED_MCP_PROTOCOL_VERSIONS = [ + '2025-06-18', + '2025-03-26', + '2024-11-05', +] as const; + +export const MAX_MCP_BODY_BYTES = 16_384; +export const MAX_MCP_RESULT_ITEMS = 10; +export const MCP_RATE_LIMIT_WINDOW_MS = 60_000; +export const MCP_RATE_LIMIT_MAX_REQUESTS = 60; +export const MCP_RETRY_AFTER_SECONDS = 60; + +const MAX_JSON_NESTING_DEPTH = 24; +const MAX_JSON_OBJECT_KEYS = 64; +const MAX_JSON_ARRAY_ITEMS = 64; +const MAX_RPC_ID_LENGTH = 256; +const MAX_SAFE_PUBLIC_ERROR_LENGTH = 512; +const MAX_SEARCH_PRICE_FILTER_CANDIDATES = 40; + +const FORBIDDEN_OBJECT_KEYS = new Set([ + '__proto__', + 'constructor', + 'prototype', +]); +const DISALLOWED_IDENTIFIER_TOKENS = new Set([ + 'null', + 'undefined', + 'nan', + 'none', + 'infinity', + '-infinity', + 'true', + 'false', + '__proto__', + 'constructor', + 'prototype', +]); +const DB_INTERNAL_ERROR_REGEX = + /PGRST\d+|relation\s+"[^"]+"|column\s+"[^"]+"|permission denied|syntax error at|duplicate key value|violates foreign key|violates check constraint|schema\s+"rate"|rate-api:\s*failed to|supabase/i; + +export const MCP_SERVER_INFO = { + name: 'rate-vn-shopping-mcp', + title: 'Rate.vn Verified Shopping & Price Truth MCP Server', + version: '1.0.0', +} as const; + +export const MCP_SERVER_INSTRUCTIONS = + 'Read-only Vietnamese tech shopping intelligence across 22 retail platforms and 5 device categories (smartphones, tablets, laptops, smartwatches, earbuds). Always cite canonical_citation_url (https://rate.vn/...) and freshness timestamps (observed_at / price_observed_at) when presenting prices, specifications, or 6-axis review trust verdicts to users. Sold-out and implausibly low bait-price listings are excluded from market floor calculations.'; + +export const MCP_CORS_HEADERS: Record = { + 'Access-Control-Allow-Origin': '*', + 'Access-Control-Allow-Methods': 'POST, OPTIONS', + 'Access-Control-Allow-Headers': + 'Content-Type, Accept, MCP-Protocol-Version, Mcp-Session-Id', + 'Access-Control-Expose-Headers': 'Retry-After, MCP-Protocol-Version', +}; + +export const MCP_DISCOVERY_CORS_HEADERS: Record = { + 'Access-Control-Allow-Origin': '*', + 'Access-Control-Allow-Methods': 'GET, OPTIONS', + 'Access-Control-Allow-Headers': + 'Content-Type, Accept, MCP-Protocol-Version, Authorization, X-Rate-Extension-Version', +}; + +export const mcpRateLimiter = new BoundedSlidingWindowRateLimiter({ + windowMs: MCP_RATE_LIMIT_WINDOW_MS, + maxRequests: MCP_RATE_LIMIT_MAX_REQUESTS, + maxBuckets: 5_000, +}); + +const SUPPORTED_PLATFORM_LIST = Array.from(SUPPORTED_PLATFORM_SLUGS) as [ + string, + ...string[], +]; + +const SUPPORTED_CATEGORY_ENUM = z.enum([ + 'all', + 'smartphones', + 'tablets', + 'laptops', + 'smartwatches', + 'earbuds', +]); + +const SUPPORTED_PLATFORM_OR_ALL_ENUM = z.enum([ + 'all', + ...SUPPORTED_PLATFORM_LIST, +]); + +function isValidSlugToken(raw: string, maxLength = 120): boolean { + if (typeof raw !== 'string') return false; + const lower = raw.toLowerCase(); + return ( + raw.length >= 1 && + raw.length <= maxLength && + /^[a-zA-Z0-9._-]+$/.test(raw) && + /[a-zA-Z0-9]/.test(raw) && + !/^0+$/.test(raw) && + !DISALLOWED_IDENTIFIER_TOKENS.has(lower) && + !raw.startsWith('.') && + !raw.endsWith('.') && + !raw.includes('..') + ); +} + +function isValidCompareSlugOrPin(token: string): boolean { + const atIdx = token.indexOf('@'); + if (atIdx === -1) { + return isValidSlugToken(token, 120); + } + if (token.indexOf('@', atIdx + 1) !== -1) return false; + const slugPart = token.slice(0, atIdx); + const variantPart = token.slice(atIdx + 1); + return ( + isValidSlugToken(slugPart, 120) && + variantPart.length >= 1 && + variantPart.length <= 64 && + /^[a-zA-Z0-9_-]+$/.test(variantPart) && + /[a-zA-Z0-9]/.test(variantPart) && + !DISALLOWED_IDENTIFIER_TOKENS.has(variantPart.toLowerCase()) + ); +} + +function isValidBrandFilter(raw: string): boolean { + const trimmed = raw.trim(); + const lower = trimmed.toLowerCase(); + return ( + trimmed.length >= 1 && + trimmed.length <= 40 && + /^[\p{L}\p{N}\s.+-]+$/u.test(trimmed) && + /[\p{L}\p{N}]/u.test(trimmed) && + !/^0+$/.test(trimmed) && + !DISALLOWED_IDENTIFIER_TOKENS.has(lower) && + !trimmed.includes('..') + ); +} + +function isSupportedRetailOrRateInspectionUrl(rawUrl: string): boolean { + if (!isSafeCrowdIngestHttpUrl(rawUrl)) return false; + const detected = detectPlatformFromInput(null, rawUrl); + if (detected && SUPPORTED_PLATFORM_SLUGS.has(detected)) return true; + const parsed = parseEcommerceUrlOrQuery(rawUrl); + if ( + typeof parsed.platform === 'string' && + SUPPORTED_PLATFORM_SLUGS.has(parsed.platform) + ) { + return true; + } + try { + const urlObj = new URL(rawUrl.trim()); + const host = urlObj.hostname.toLowerCase(); + if (host === 'rate.vn' || host === 'www.rate.vn') { + const cleanPath = urlObj.pathname.replace(/\/+$/, ''); + const segments = cleanPath.split('/').filter(Boolean); + if (segments.length === 2) { + const [section, identifier] = segments; + const lowerSection = section!.toLowerCase(); + if ( + (lowerSection === 'smartphones' || + lowerSection === 'tablets' || + lowerSection === 'laptops' || + lowerSection === 'smartwatches' || + lowerSection === 'earbuds' || + lowerSection === 'merchants') && + isValidSlugToken(identifier!, 128) + ) { + return true; + } + } + } + } catch { + return false; + } + return false; +} + +export const SearchVerifiedCatalogInputSchema = z + .strictObject({ + query: z + .string() + .trim() + .min(1) + .max(160) + .optional() + .describe( + 'Model name, series, or chipset keyword (for example "iPhone 16 Pro", "Snapdragon 8 Elite", "Sony WF-1000XM5").' + ), + category: SUPPORTED_CATEGORY_ENUM.default('all').describe( + 'Canonical device category filter across the 5 supported categories, or "all".' + ), + brand: z + .string() + .trim() + .min(1) + .max(40) + .refine(isValidBrandFilter, 'Invalid brand filter') + .optional() + .describe('Manufacturer name filter (for example "Apple", "Samsung").'), + minPriceVnd: z + .number() + .int() + .min(1) + .max(MAX_VALID_VND_PRICE) + .optional() + .describe('Minimum verified VND price floor.'), + maxPriceVnd: z + .number() + .int() + .min(1) + .max(MAX_VALID_VND_PRICE) + .optional() + .describe('Maximum verified VND price ceiling.'), + sort: z + .enum([ + 'default', + 'price_asc', + 'price_desc', + 'rating_desc', + 'merchants_desc', + 'newest', + ]) + .default('rating_desc') + .describe('Sort order for matched catalog devices.'), + limit: z + .number() + .int() + .min(1) + .max(MAX_MCP_RESULT_ITEMS) + .default(5) + .describe('Maximum results to return (1 to 10, default 5).'), + }) + .refine( + (v) => + v.minPriceVnd === undefined || + v.maxPriceVnd === undefined || + v.minPriceVnd <= v.maxPriceVnd, + { message: 'minPriceVnd must not exceed maxPriceVnd' } + ); + +export const GetStoreOffersAndPriceTruthInputSchema = z.strictObject({ + slug: z + .string() + .trim() + .min(1) + .max(120) + .refine((v) => isValidSlugToken(v, 120), 'Invalid product slug') + .describe( + 'Canonical product or item slug on Rate.vn (for example "apple-iphone-16-pro-max-256gb").' + ), + officialOnly: z + .boolean() + .default(false) + .describe( + 'When true, keep only verified Official Mall / authorized chain listings.' + ), + platform: SUPPORTED_PLATFORM_OR_ALL_ENUM.default('all').describe( + 'Optional filter for one of the 22 tracked Vietnamese retail platforms, or "all".' + ), + limit: z + .number() + .int() + .min(1) + .max(MAX_MCP_RESULT_ITEMS) + .default(MAX_MCP_RESULT_ITEMS) + .describe('Maximum verified in-stock offers to return (1 to 10).'), +}); + +export const CompareDevicesByUseCaseInputSchema = z + .strictObject({ + slugs: z + .array( + z + .string() + .trim() + .min(1) + .max(185) + .refine(isValidCompareSlugOrPin, 'Invalid compare product slug') + ) + .min(2) + .max(4) + .describe( + '2 to 4 canonical product slugs in the same device category to compare side-by-side.' + ), + persona: z + .enum([ + 'balanced', + 'photography', + 'gaming', + 'endurance', + 'business', + 'value_hunter', + ]) + .default('balanced') + .describe('Preset use-case scoring profile across 5 JReviews criteria.'), + weights: z + .strictObject({ + screen: z.number().min(0).max(100).optional(), + performance: z.number().min(0).max(100).optional(), + camera: z.number().min(0).max(100).optional(), + battery: z.number().min(0).max(100).optional(), + value: z.number().min(0).max(100).optional(), + }) + .optional() + .describe( + 'Optional custom weight overrides (0 to 100) for screen, performance, camera (or ANC on earbuds), battery, and value.' + ), + }) + .refine( + (v) => new Set(v.slugs.map((s) => s.toLowerCase())).size >= 2, + 'Provide at least 2 distinct product slugs' + ); + +export const AuditListingUrlInputSchema = z.strictObject({ + url: z + .string() + .trim() + .min(8) + .max(1024) + .refine( + (v) => isSafeCrowdIngestHttpUrl(v), + 'Provide a valid public HTTP/HTTPS listing URL' + ) + .refine( + isSupportedRetailOrRateInspectionUrl, + 'URL must belong to one of the 22 supported Vietnamese retail platforms or rate.vn' + ) + .describe( + 'Public listing URL from one of the 22 supported Vietnamese e-commerce platforms (Shopee, Lazada, Tiki, TikTok Shop, CellphoneS, TGDD, FPT Shop, Hoang Ha, Di Dong Viet, Phong Vu, Dien May Xanh, TopZone, GearVN, Nguyen Kim, ShopDunk, HACOM, Clickbuy, Viettel Store, Pico, MediaMart, MemoryZone, An Phat).' + ), + observedPriceVnd: z + .number() + .int() + .min(1) + .max(MAX_VALID_VND_PRICE) + .optional() + .describe('Optional live selling price in VND observed on the page.'), + observedOriginalPriceVnd: z + .number() + .int() + .min(1) + .max(MAX_VALID_VND_PRICE) + .optional() + .describe( + 'Optional strikethrough original price in VND declared by the seller.' + ), +}); + +export const GetGenuineDealsInputSchema = z.strictObject({ + category: SUPPORTED_CATEGORY_ENUM.default('all').describe( + 'Canonical device category filter across the 5 tech categories, or "all".' + ), + platform: SUPPORTED_PLATFORM_OR_ALL_ENUM.default('all').describe( + 'Optional filter for one of the 22 tracked retail platforms, or "all".' + ), + maxBudgetVnd: z + .number() + .int() + .min(1) + .max(MAX_VALID_VND_PRICE) + .optional() + .describe('Optional maximum VND budget ceiling for returned deals.'), + officialOnly: z + .boolean() + .default(false) + .describe( + 'When true, return deals from Official Mall / authorized stores only.' + ), + limit: z + .number() + .int() + .min(1) + .max(MAX_MCP_RESULT_ITEMS) + .default(MAX_MCP_RESULT_ITEMS) + .describe('Maximum genuine deals to return (1 to 10, default 10).'), +}); + +export type McpToolName = + | 'search_verified_catalog' + | 'get_22_store_offers_and_price_truth' + | 'compare_devices_by_use_case' + | 'audit_listing_url' + | 'get_genuine_deals'; + +export interface McpToolAnnotations { + title: string; + readOnlyHint: true; + destructiveHint: false; + idempotentHint: true; + openWorldHint: false; +} + +export interface McpToolDefinition { + name: McpToolName; + title: string; + description: string; + inputSchema: Record; + annotations: McpToolAnnotations; +} + +function exportToolInputJsonSchema(schema: z.ZodType): Record { + const raw = z.toJSONSchema(schema, { + io: 'input', + target: 'draft-2020-12', + unrepresentable: 'any', + }) as Record; + return { + ...raw, + type: 'object', + additionalProperties: false, + }; +} + +const READ_ONLY_ANNOTATIONS = (title: string): McpToolAnnotations => ({ + title, + readOnlyHint: true, + destructiveHint: false, + idempotentHint: true, + openWorldHint: false, +}); + +export const MCP_TOOL_DEFINITIONS: readonly McpToolDefinition[] = [ + { + name: 'search_verified_catalog', + title: 'Search Verified Tech Catalog', + description: + 'Search normalized tech products across 5 categories (smartphones, tablets, laptops, smartwatches, earbuds) with brand and VND price filters. Excludes sold-out and bait-price traps from floor prices and returns canonical_citation_url plus freshness timestamps (max 10 items).', + inputSchema: exportToolInputJsonSchema(SearchVerifiedCatalogInputSchema), + annotations: READ_ONLY_ANNOTATIONS('Search Verified Tech Catalog'), + }, + { + name: 'get_22_store_offers_and_price_truth', + title: 'Get 22-Store Offers & Price Truth', + description: + 'Return verified in-stock offers across 22 Vietnamese retail platforms, historical floor/median price truth, Deal Radar fake-sale flags, Bayesian rating, and 6-axis Review Trust Model v2 summary for a product slug (max 10 offers).', + inputSchema: exportToolInputJsonSchema( + GetStoreOffersAndPriceTruthInputSchema + ), + annotations: READ_ONLY_ANNOTATIONS('Get 22-Store Offers & Price Truth'), + }, + { + name: 'compare_devices_by_use_case', + title: 'Compare Devices by Use Case', + description: + 'Compare 2 to 4 same-category product slugs side-by-side across standardized 10-group specs, verified multi-store floor prices, and 5-criterion JReviews scores with optional persona or custom criterion weight overrides.', + inputSchema: exportToolInputJsonSchema(CompareDevicesByUseCaseInputSchema), + annotations: READ_ONLY_ANNOTATIONS('Compare Devices by Use Case'), + }, + { + name: 'audit_listing_url', + title: 'Audit Marketplace Listing URL', + description: + 'Inspect a product listing URL from any of the 22 supported Vietnamese marketplaces and retail chains, returning catalog match, 5-level fake-discount price verdict, accessory gatekeeper check, and DOSafe + AI review seller risk scores.', + inputSchema: exportToolInputJsonSchema(AuditListingUrlInputSchema), + annotations: READ_ONLY_ANNOTATIONS('Audit Marketplace Listing URL'), + }, + { + name: 'get_genuine_deals', + title: 'Get Genuine Multi-Store Floor Deals', + description: + 'List verified below-median and cross-platform floor deals across 22 Vietnamese retail platforms (limit <= 10), filtering out sold-out listings, implausibly low bait traps, high-risk sellers, and inflated strikethrough fake sales.', + inputSchema: exportToolInputJsonSchema(GetGenuineDealsInputSchema), + annotations: READ_ONLY_ANNOTATIONS('Get Genuine Multi-Store Floor Deals'), + }, +] as const; + +export interface McpResolvedCompareTarget { + variantSlug: string | null; + itemId: string | null; +} + +export interface McpDataReaders { + getCachedMasterProducts: ( + params?: MasterProductFilterParams + ) => Promise; + getCachedMasterProductBySlug: (slug: string) => Promise; + getCachedMasterProductOffers: ( + masterProductId: string + ) => Promise; + getCachedMasterProductReviews: ( + masterProductId: string + ) => Promise; + getCachedMasterProductReviewSummary: ( + masterProductId: string, + existingReviews?: ReviewItem[] + ) => Promise; + getCachedMasterProductPriceHistory: ( + masterProductId: string, + existingOffers?: MerchantOffer[] + ) => Promise; + getCachedCompareMasterProducts: ( + slugsCsv: string + ) => Promise; + getCachedFilteredReviewCountsByMaster: () => Promise; + getCachedInspectProductOrShopUrl: ( + rawQuery: string + ) => Promise; + getCrossPlatformDealRadar: (options?: { + categorySlug?: CanonicalCategorySlug | 'all'; + platform?: string; + limit?: number; + }) => Promise; + resolveCompareTokenTarget?: ( + rawToken: string + ) => Promise; + nowIso?: () => string; +} + +const ITEM_RESOLVER_SLUG_REGEX = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,159}$/; + +async function defaultResolveCompareTokenTarget( + rawToken: string +): Promise { + const typed = splitComparePinToken(rawToken, true); + const lower = splitComparePinToken(rawToken, false); + if (!isItemModelOn()) { + // Without the Item model, explicit @variant pins have no variant table to resolve against. + return typed.variantKey === null + ? { variantSlug: lower.slug, itemId: null } + : { variantSlug: null, itemId: null }; + } + if (!ITEM_RESOLVER_SLUG_REGEX.test(typed.slug)) { + return typed.variantKey === null + ? { variantSlug: lower.slug, itemId: null } + : { variantSlug: null, itemId: null }; + } + try { + const found = await lookupSlugAnyCase( + typed.slug, + getCachedCatalogSlugResolution + ); + const catalogRes = found.found; + const cmpRes = + !catalogRes || catalogRes.kind === 'unlinked' + ? { kind: 'unlinked' as const } + : catalogRes.kind === 'item' + ? { + kind: 'item' as const, + item: catalogRes.item, + variants: await getCachedItemVariants(catalogRes.item), + } + : { + kind: 'variant' as const, + item: catalogRes.item, + variant: catalogRes.variant, + variants: await getCachedItemVariants(catalogRes.item), + retired: catalogRes.retired, + }; + const target = compareTarget(cmpRes, lower); + if (!target) { + return { variantSlug: null, itemId: null }; + } + return { variantSlug: target.variantSlug, itemId: target.itemId }; + } catch { + return typed.variantKey === null + ? { variantSlug: lower.slug, itemId: null } + : { variantSlug: null, itemId: null }; + } +} + +const DEFAULT_MCP_READERS: McpDataReaders = { + getCachedMasterProducts, + getCachedMasterProductBySlug, + getCachedMasterProductOffers, + getCachedMasterProductReviews, + getCachedMasterProductReviewSummary, + getCachedMasterProductPriceHistory, + getCachedCompareMasterProducts, + getCachedFilteredReviewCountsByMaster, + getCachedInspectProductOrShopUrl, + getCrossPlatformDealRadar, + resolveCompareTokenTarget: defaultResolveCompareTokenTarget, + nowIso: () => new Date().toISOString(), +}; + +const PERSONA_WEIGHT_PRESETS: Record< + | 'balanced' + | 'photography' + | 'gaming' + | 'endurance' + | 'business' + | 'value_hunter', + LeaderboardCriteriaWeights +> = { + balanced: { + screen: 20, + performance: 20, + camera: 20, + battery: 20, + value: 20, + }, + photography: { + screen: 20, + performance: 15, + camera: 45, + battery: 10, + value: 10, + }, + gaming: { + screen: 25, + performance: 45, + camera: 5, + battery: 15, + value: 10, + }, + endurance: { + screen: 15, + performance: 15, + camera: 10, + battery: 45, + value: 15, + }, + business: { + screen: 35, + performance: 25, + camera: 10, + battery: 20, + value: 10, + }, + value_hunter: { + screen: 15, + performance: 20, + camera: 10, + battery: 15, + value: 40, + }, +}; + +function toWellFormedString(raw: string): string { + const maybeWellFormed = (raw as string & { toWellFormed?: () => string }) + .toWellFormed; + if (typeof maybeWellFormed === 'function') { + return maybeWellFormed.call(raw); + } + let out = ''; + for (let i = 0; i < raw.length; i++) { + const code = raw.charCodeAt(i); + if (code >= 0xd800 && code <= 0xdbff) { + const next = i + 1 < raw.length ? raw.charCodeAt(i + 1) : 0; + if (next >= 0xdc00 && next <= 0xdfff) { + out += raw[i]! + raw[i + 1]!; + i++; + } else { + out += '\ufffd'; + } + } else if (code >= 0xdc00 && code <= 0xdfff) { + out += '\ufffd'; + } else { + out += raw[i]!; + } + } + return out; +} + +export function deepSanitizeWellFormed(value: T): T { + if (typeof value === 'string') { + return toWellFormedString(value) as T; + } + if (Array.isArray(value)) { + return value.map((entry) => deepSanitizeWellFormed(entry)) as T; + } + if (value && typeof value === 'object') { + const out: Record = {}; + for (const key of Object.keys(value)) { + if (FORBIDDEN_OBJECT_KEYS.has(key)) continue; + if (!Object.hasOwn(value, key)) continue; + const safeKey = toWellFormedString(key); + if (FORBIDDEN_OBJECT_KEYS.has(safeKey)) continue; + out[safeKey] = deepSanitizeWellFormed( + (value as Record)[key] + ); + } + return out as T; + } + return value; +} + +function sanitizeMcpPublicText(raw: unknown, maxLength = 320): string { + if (typeof raw !== 'string') return ''; + const cleaned = toWellFormedString(raw) + .replace(/\p{Cc}+/gu, ' ') + .replace(/\s+/g, ' ') + .trim(); + return cleaned.length > maxLength + ? cleaned.slice(0, maxLength).trim() + : cleaned; +} + +function isSafeExternalHttpUrlWithMax( + rawUrl: string, + maxLength = 2048 +): boolean { + if (typeof rawUrl !== 'string') return false; + const trimmed = rawUrl.trim(); + if ( + !trimmed || + trimmed.length > maxLength || + /\s/.test(trimmed) || + /\p{Cc}/u.test(trimmed) + ) { + return false; + } + try { + const parsed = new URL(trimmed); + if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') { + return false; + } + if (parsed.username || parsed.password) return false; + const host = parsed.hostname.toLowerCase(); + if ( + !host || + !host.includes('.') || + host.startsWith('.') || + host.endsWith('.') || + host.includes('..') || + host.startsWith('[') || + host === 'localhost' || + host.endsWith('.localhost') || + host.endsWith('.local') || + host.endsWith('.internal') || + /^\d+(?:\.\d+){3}$/.test(host) + ) { + return false; + } + if (parsed.port !== '' && parsed.port !== '80' && parsed.port !== '443') { + return false; + } + return true; + } catch { + return false; + } +} + +function sanitizeExternalOfferUrl(raw: unknown): string | null { + if (typeof raw !== 'string') return null; + const trimmed = toWellFormedString(raw).trim(); + if (!isSafeExternalHttpUrlWithMax(trimmed, 2048)) return null; + return trimmed; +} + +export function buildCanonicalRateUrl(pathOrHref: string): string { + const cleaned = + typeof pathOrHref === 'string' ? toWellFormedString(pathOrHref).trim() : ''; + if ( + !cleaned || + !cleaned.startsWith('/') || + cleaned.startsWith('//') || + cleaned.includes('\\') || + /[\s\p{Cc}]/u.test(cleaned) + ) { + return CANONICAL_RATE_ORIGIN; + } + const pathPart = cleaned.split(/[?#]/)[0] ?? ''; + const segments = pathPart.split('/').filter(Boolean); + if (segments.some((seg) => seg === '.' || seg === '..')) { + return CANONICAL_RATE_ORIGIN; + } + return `${CANONICAL_RATE_ORIGIN}${cleaned}`; +} + +function buildSafeMerchantCitationUrl( + rawMerchantId: unknown, + fallbackUrl: string +): string { + const safeId = sanitizeCachedEntityId(rawMerchantId); + return safeId + ? buildCanonicalRateUrl(`/merchants/${encodeURIComponent(safeId)}`) + : fallbackUrl; +} + +function resolveValidIsoTimestamp(raw: unknown): string | null { + if (typeof raw !== 'string') return null; + const trimmed = raw.trim(); + if (!trimmed || trimmed.length > 64) return null; + const ms = Date.parse(trimmed); + if (!Number.isFinite(ms) || ms <= 0) return null; + return new Date(ms).toISOString(); +} + +function resolveProductObservedAt( + product: { updated_at?: unknown } | null | undefined, + fallbackIso: string +): { + observedAt: string; + freshnessSource: 'product_updated_at' | 'cache_snapshot'; +} { + const fromProduct = resolveValidIsoTimestamp(product?.updated_at); + if (fromProduct) { + return { observedAt: fromProduct, freshnessSource: 'product_updated_at' }; + } + return { observedAt: fallbackIso, freshnessSource: 'cache_snapshot' }; +} + +function computeMedianPrice(prices: readonly number[]): number | null { + const valid = prices + .filter((v) => Number.isFinite(v) && v > 0 && v <= MAX_VALID_VND_PRICE) + .sort((a, b) => a - b); + if (valid.length === 0) return null; + const mid = Math.floor(valid.length / 2); + if (valid.length % 2 === 1) return valid[mid]!; + return Math.round((valid[mid - 1]! + valid[mid]!) / 2); +} + +function getPlausibleInStockMerchantOffers(offers: readonly MerchantOffer[]): { + inStockOffers: MerchantOffer[]; + plausibleInStockOffers: MerchantOffer[]; + excludedUnavailableCount: number; + excludedBaitCount: number; +} { + const safeAll = Array.isArray(offers) + ? offers.filter((o): o is MerchantOffer => + Boolean(o && typeof o === 'object' && !Array.isArray(o)) + ) + : []; + const inStockOffers = safeAll.filter((o) => { + if (isOfferUnavailable(o)) return false; + const price = parseFiniteDecimalInput(o.price_current); + return Number.isFinite(price) && price > 0 && price <= MAX_VALID_VND_PRICE; + }); + const plausibleInStockOffers = plausibleOffers(inStockOffers); + return { + inStockOffers, + plausibleInStockOffers, + excludedUnavailableCount: Math.max( + 0, + safeAll.length - inStockOffers.length + ), + excludedBaitCount: Math.max( + 0, + inStockOffers.length - plausibleInStockOffers.length + ), + }; +} + +function resolveExpertRating10(product: MasterProduct): number | null { + const raw = parseFiniteDecimalInput(product.expert_rating); + if (!Number.isFinite(raw) || raw <= 0 || raw > 100) return null; + const normalized10 = raw > 10 ? raw / 10 : raw <= 5 ? raw * 2 : raw; + return roundScore(Math.min(10, normalized10), 1); +} + +function toBoundedPositiveVndOrNull(raw: unknown): number | null { + const parsed = parseFiniteDecimalInput(raw); + if (!Number.isFinite(parsed) || parsed <= 0 || parsed > MAX_VALID_VND_PRICE) { + return null; + } + return Math.round(parsed); +} + +export function sanitizeMcpErrorMessage( + rawMessage: unknown, + fallbackMessage: string +): string { + if (typeof rawMessage !== 'string') return fallbackMessage; + const cleaned = toWellFormedString(rawMessage) + .replace(/\p{Cc}+/gu, ' ') + .replace(/\s+/g, ' ') + .trim(); + if (!cleaned || DB_INTERNAL_ERROR_REGEX.test(cleaned)) { + return fallbackMessage; + } + return cleaned.length > MAX_SAFE_PUBLIC_ERROR_LENGTH + ? `${cleaned.slice(0, MAX_SAFE_PUBLIC_ERROR_LENGTH - 3).trim()}...` + : cleaned; +} + +function formatZodIssuesForMcp(issues: readonly z.core.$ZodIssue[]): string { + const parts: string[] = []; + for (const issue of issues.slice(0, 4)) { + const rawPath = + issue.path.length > 0 + ? issue.path.map((seg) => String(seg)).join('.') + : 'arguments'; + const pathLabel = sanitizeMcpPublicText(rawPath, 64) || 'arguments'; + const msg = sanitizeMcpErrorMessage(issue.message, 'invalid value'); + parts.push(`${pathLabel}: ${msg}`); + } + const combined = + parts.length > 0 + ? `Invalid tool arguments (${parts.join('; ')})` + : 'Invalid tool arguments'; + return sanitizeMcpErrorMessage(combined, 'Invalid tool arguments'); +} + +interface McpToolCallResult { + content: Array<{ type: 'text'; text: string }>; + structuredContent: Record; + isError?: boolean; +} + +function buildToolCallResult( + payload: Record, + isError = false +): McpToolCallResult { + const sanitized = deepSanitizeWellFormed(payload); + return { + content: [{ type: 'text', text: JSON.stringify(sanitized) }], + structuredContent: sanitized, + ...(isError ? { isError: true } : {}), + }; +} + +async function executeSearchVerifiedCatalog( + rawArgs: z.infer, + readers: McpDataReaders +): Promise { + const snapshotAt = (readers.nowIso ?? DEFAULT_MCP_READERS.nowIso!)(); + const limit = Math.min(rawArgs.limit, MAX_MCP_RESULT_ITEMS); + const needsVerifiedPriceFilteringOrSorting = + rawArgs.minPriceVnd !== undefined || + rawArgs.maxPriceVnd !== undefined || + rawArgs.sort === 'price_asc' || + rawArgs.sort === 'price_desc'; + const candidateLimit = needsVerifiedPriceFilteringOrSorting + ? Math.min(MAX_SEARCH_PRICE_FILTER_CANDIDATES, Math.max(limit * 3, 24)) + : limit; + + const products = await readers.getCachedMasterProducts({ + categorySlug: rawArgs.category, + brands: rawArgs.brand ? [rawArgs.brand] : undefined, + search: rawArgs.query, + minPrice: rawArgs.minPriceVnd, + maxPrice: rawArgs.maxPriceVnd, + sort: rawArgs.sort, + limit: candidateLimit, + }); + + const boundedCandidates = products.slice(0, candidateLimit); + const offersList = await Promise.all( + boundedCandidates.map((p) => readers.getCachedMasterProductOffers(p.id)) + ); + + const computedItems = boundedCandidates.map((stored, idx) => { + const category = getMasterProductCategorySlug(stored); + const scoped = applyCategorySpecTemplate(category, stored); + const rawOffers = offersList[idx] ?? []; + const { + inStockOffers, + plausibleInStockOffers, + excludedUnavailableCount, + excludedBaitCount, + } = getPlausibleInStockMerchantOffers(rawOffers); + const plausiblePrices = plausibleInStockOffers.map((o) => + Math.round(parseFiniteDecimalInput(o.price_current)) + ); + const verifiedMinPrice = + plausiblePrices.length > 0 ? Math.min(...plausiblePrices) : null; + const verifiedMaxPrice = + plausiblePrices.length > 0 ? Math.max(...plausiblePrices) : null; + const verifiedMedianPrice = computeMedianPrice(plausiblePrices); + const href = getMasterProductHref(scoped); + const { observedAt, freshnessSource } = resolveProductObservedAt( + scoped, + snapshotAt + ); + + return { + slug: sanitizeMcpPublicText(scoped.slug, 120), + name: sanitizeMcpPublicText(scoped.name, 240), + brand: sanitizeMcpPublicText(scoped.brand, 80), + category, + verified_min_price_vnd: verifiedMinPrice, + verified_median_price_vnd: verifiedMedianPrice, + verified_max_price_vnd: verifiedMaxPrice, + in_stock_offer_count: plausibleInStockOffers.length, + excluded_unavailable_offer_count: excludedUnavailableCount, + excluded_bait_offer_count: excludedBaitCount, + sale_state: saleStateOfMaster( + scoped, + listingCountForSaleState(rawOffers.length, inStockOffers.length) + ), + bayesian_rating_5: productRatingScore5(scoped), + expert_rating_10: resolveExpertRating10(scoped), + authentic_review_count: + typeof scoped.authentic_review_count === 'number' && + Number.isFinite(scoped.authentic_review_count) && + scoped.authentic_review_count >= 0 + ? Math.trunc(scoped.authentic_review_count) + : 0, + key_specs: scoped.key_specs ?? {}, + deal_radar: radarExportFields( + computeProductRadarSignal(scoped, plausibleInStockOffers) + ), + canonical_citation_url: buildCanonicalRateUrl(href), + observed_at: observedAt, + price_observed_at: observedAt, + freshness_source: freshnessSource, + }; + }); + + const priceFiltered = computedItems.filter((item) => { + if ( + rawArgs.minPriceVnd === undefined && + rawArgs.maxPriceVnd === undefined + ) { + return true; + } + if (item.verified_min_price_vnd === null) return false; + if ( + rawArgs.minPriceVnd !== undefined && + item.verified_min_price_vnd < rawArgs.minPriceVnd + ) { + return false; + } + if ( + rawArgs.maxPriceVnd !== undefined && + item.verified_min_price_vnd > rawArgs.maxPriceVnd + ) { + return false; + } + return true; + }); + + if (rawArgs.sort === 'price_asc' || rawArgs.sort === 'price_desc') { + priceFiltered.sort((a, b) => { + if ( + a.verified_min_price_vnd === null && + b.verified_min_price_vnd === null + ) { + return 0; + } + if (a.verified_min_price_vnd === null) return 1; + if (b.verified_min_price_vnd === null) return -1; + return rawArgs.sort === 'price_asc' + ? a.verified_min_price_vnd - b.verified_min_price_vnd + : b.verified_min_price_vnd - a.verified_min_price_vnd; + }); + } + + const items = priceFiltered.slice(0, limit); + const categoryUrl = + rawArgs.category === 'all' + ? CANONICAL_RATE_ORIGIN + : buildCanonicalRateUrl(`/${rawArgs.category}`); + + return buildToolCallResult({ + ok: true, + tool: 'search_verified_catalog', + category_filter: rawArgs.category, + returned_count: items.length, + max_limit: MAX_MCP_RESULT_ITEMS, + canonical_citation_url: categoryUrl, + observed_at: snapshotAt, + items, + }); +} + +async function executeGetStoreOffersAndPriceTruth( + rawArgs: z.infer, + readers: McpDataReaders +): Promise { + const snapshotAt = (readers.nowIso ?? DEFAULT_MCP_READERS.nowIso!)(); + const limit = Math.min(rawArgs.limit, MAX_MCP_RESULT_ITEMS); + + let resolvedSlug = rawArgs.slug; + if (readers.resolveCompareTokenTarget) { + const resolved = await readers.resolveCompareTokenTarget(rawArgs.slug); + if (resolved.variantSlug) resolvedSlug = resolved.variantSlug; + } + + const storedProduct = + await readers.getCachedMasterProductBySlug(resolvedSlug); + if (!storedProduct) { + return buildToolCallResult( + { + ok: false, + error: 'Product not found in Rate.vn verified catalog', + requested_slug: rawArgs.slug, + canonical_citation_url: CANONICAL_RATE_ORIGIN, + observed_at: snapshotAt, + }, + true + ); + } + + const category = getMasterProductCategorySlug(storedProduct); + const product = applyCategorySpecTemplate(category, storedProduct); + const [rawOffers, rawReviews] = await Promise.all([ + readers.getCachedMasterProductOffers(product.id), + readers.getCachedMasterProductReviews(product.id), + ]); + const [reviewSummary, priceHistory] = await Promise.all([ + readers.getCachedMasterProductReviewSummary(product.id, rawReviews), + readers.getCachedMasterProductPriceHistory(product.id, rawOffers), + ]); + + const { + inStockOffers, + plausibleInStockOffers, + excludedUnavailableCount, + excludedBaitCount, + } = getPlausibleInStockMerchantOffers(rawOffers); + + const plausibleOfferIdSet = new Set(); + for (const offer of plausibleInStockOffers) { + if (offer.id) { + plausibleOfferIdSet.add(offer.id); + const normalized = normalizeOfferId(offer.id); + if (normalized) plausibleOfferIdSet.add(normalized); + } + } + + const latestPointIsoByOfferId = new Map(); + let latestGlobalPriceIso: string | null = null; + for (const pt of priceHistory?.points ?? []) { + // Ignore synthetic live_listing fallback points (`id < 0`) so unrecorded offers + // never overwrite real crawl timestamps with `new Date()`. + if ( + pt.source === 'live_listing' || + (typeof pt.id === 'number' && pt.id < 0) + ) { + continue; + } + const iso = resolveValidIsoTimestamp(pt.recorded_at); + if (!iso) continue; + const rawPtOfferId = typeof pt.product_id === 'string' ? pt.product_id : ''; + const normPtOfferId = normalizeOfferId(rawPtOfferId); + if (rawPtOfferId) { + const existing = latestPointIsoByOfferId.get(rawPtOfferId); + if (!existing || iso > existing) { + latestPointIsoByOfferId.set(rawPtOfferId, iso); + } + } + if (normPtOfferId && normPtOfferId !== rawPtOfferId) { + const existingNorm = latestPointIsoByOfferId.get(normPtOfferId); + if (!existingNorm || iso > existingNorm) { + latestPointIsoByOfferId.set(normPtOfferId, iso); + } + } + if ( + (rawPtOfferId && plausibleOfferIdSet.has(rawPtOfferId)) || + (normPtOfferId && plausibleOfferIdSet.has(normPtOfferId)) + ) { + if (!latestGlobalPriceIso || iso > latestGlobalPriceIso) { + latestGlobalPriceIso = iso; + } + } + } + + const { observedAt: productObservedAt, freshnessSource } = + resolveProductObservedAt(product, snapshotAt); + const productPriceObservedAt = latestGlobalPriceIso ?? productObservedAt; + + const allPlausiblePrices = plausibleInStockOffers.map((o) => + Math.round(parseFiniteDecimalInput(o.price_current)) + ); + const verifiedMinPrice = + allPlausiblePrices.length > 0 ? Math.min(...allPlausiblePrices) : null; + const verifiedMaxPrice = + allPlausiblePrices.length > 0 ? Math.max(...allPlausiblePrices) : null; + const verifiedMedianPrice = computeMedianPrice(allPlausiblePrices); + + const filteredOffers = plausibleInStockOffers + .filter((o) => { + if (rawArgs.officialOnly && !o.merchant?.is_official) return false; + if ( + rawArgs.platform !== 'all' && + String(o.merchant?.platform || o.platform || '').toLowerCase() !== + rawArgs.platform + ) { + return false; + } + return true; + }) + .sort((a, b) => { + const priceDiff = + parseFiniteDecimalInput(a.price_current) - + parseFiniteDecimalInput(b.price_current); + if (priceDiff !== 0) return priceDiff; + return ( + (b.merchant?.is_official ? 1 : 0) - (a.merchant?.is_official ? 1 : 0) + ); + }) + .slice(0, limit); + + const productHref = getMasterProductHref(product); + const productCitationUrl = buildCanonicalRateUrl(productHref); + + const offers = filteredOffers.map((rawOffer) => { + const publicOffer = withPublicOfferReviewRisk(rawOffer); + const currentPrice = Math.round( + parseFiniteDecimalInput(publicOffer.price_current) + ); + const rawOrig = parseFiniteDecimalInput(publicOffer.price_original); + const normalizedOrig = normalizeOfferOriginalPrice( + currentPrice, + Number.isFinite(rawOrig) ? rawOrig : 0 + ); + const normOfferId = normalizeOfferId(publicOffer.id); + const offerAnalysis = + priceHistory?.byOffer && + Object.hasOwn(priceHistory.byOffer, publicOffer.id) + ? priceHistory.byOffer[publicOffer.id] + : normOfferId && + priceHistory?.byOffer && + Object.hasOwn(priceHistory.byOffer, normOfferId) + ? priceHistory.byOffer[normOfferId] + : null; + const offerObservedAt = + latestPointIsoByOfferId.get(publicOffer.id) ?? + (normOfferId ? latestPointIsoByOfferId.get(normOfferId) : undefined) ?? + productPriceObservedAt; + const platformSlug = sanitizeMcpPublicText( + publicOffer.merchant?.platform || publicOffer.platform || 'shopee', + 32 + ).toLowerCase(); + + return { + id: sanitizeMcpPublicText(publicOffer.id, 128), + platform: platformSlug, + title: sanitizeMcpPublicText(publicOffer.title, 280), + price_current_vnd: currentPrice, + price_original_vnd: normalizedOrig, + discount_verdict: offerAnalysis?.verdict ?? null, + historical_median_price_vnd: + offerAnalysis?.historical_median_price ?? verifiedMedianPrice, + merchant: { + id: sanitizeMcpPublicText(publicOffer.merchant?.id, 128), + name: sanitizeMcpPublicText(publicOffer.merchant?.name, 160), + is_official_mall: Boolean(publicOffer.merchant?.is_official), + risk_score: publicOffer.merchant?.risk_score ?? null, + dosafe_risk_score: publicOffer.merchant?.dosafe_risk_score ?? null, + review_risk_score: publicOffer.merchant?.review_risk_score ?? null, + }, + offer_url: sanitizeExternalOfferUrl(publicOffer.url), + canonical_citation_url: `${productCitationUrl}#offers-table`, + price_observed_at: offerObservedAt, + observed_at: offerObservedAt, + }; + }); + + return buildToolCallResult({ + ok: true, + tool: 'get_22_store_offers_and_price_truth', + canonical_citation_url: productCitationUrl, + observed_at: productObservedAt, + price_observed_at: productPriceObservedAt, + freshness_source: latestGlobalPriceIso ? 'price_history' : freshnessSource, + product: { + slug: sanitizeMcpPublicText(product.slug, 120), + name: sanitizeMcpPublicText(product.name, 240), + brand: sanitizeMcpPublicText(product.brand, 80), + category, + sale_state: saleStateOfMaster( + product, + listingCountForSaleState(rawOffers.length, inStockOffers.length) + ), + bayesian_rating_5: productRatingScore5(product), + expert_rating_10: resolveExpertRating10(product), + authentic_review_count: + typeof product.authentic_review_count === 'number' && + Number.isFinite(product.authentic_review_count) && + product.authentic_review_count >= 0 + ? Math.trunc(product.authentic_review_count) + : 0, + key_specs: product.key_specs ?? {}, + canonical_citation_url: productCitationUrl, + observed_at: productObservedAt, + }, + price_truth: { + verified_min_price_vnd: verifiedMinPrice, + verified_median_price_vnd: verifiedMedianPrice, + verified_max_price_vnd: verifiedMaxPrice, + lowest_ever_price_vnd: priceHistory?.lowestEverPrice ?? null, + lowest_ever_date: priceHistory?.lowestEverDate ?? null, + highest_ever_price_vnd: priceHistory?.highestEverPrice ?? null, + fake_discount_offer_count: priceHistory?.fakeDiscountCount ?? 0, + genuine_deal_offer_count: priceHistory?.genuineDealCount ?? 0, + total_plausible_in_stock_offers: plausibleInStockOffers.length, + excluded_unavailable_offer_count: excludedUnavailableCount, + excluded_bait_offer_count: excludedBaitCount, + deal_radar: radarExportFields( + computeProductRadarSignal(product, plausibleInStockOffers) + ), + }, + review_trust_summary: { + trust_model: 'review_trust_v2_6_axis', + total_analyzed: reviewSummary?.total_analyzed ?? 0, + authentic_pct: reviewSummary?.authentic_pct ?? 0, + suspicious_pct: reviewSummary?.suspicious_pct ?? 0, + fake_pct: reviewSummary?.fake_pct ?? 0, + pros: (reviewSummary?.pros ?? []) + .slice(0, 6) + .map((s) => sanitizeMcpPublicText(s, 200)), + cons: (reviewSummary?.cons ?? []) + .slice(0, 6) + .map((s) => sanitizeMcpPublicText(s, 200)), + ai_summary: reviewSummary?.ai_summary + ? sanitizeMcpPublicText(reviewSummary.ai_summary, 500) + : null, + }, + returned_offer_count: offers.length, + offers, + }); +} + +async function executeCompareDevicesByUseCase( + rawArgs: z.infer, + readers: McpDataReaders +): Promise { + const snapshotAt = (readers.nowIso ?? DEFAULT_MCP_READERS.nowIso!)(); + const resolveToken = + readers.resolveCompareTokenTarget ?? defaultResolveCompareTokenTarget; + + const rawResolved = await Promise.all( + rawArgs.slugs.map(async (requested) => { + const target = await resolveToken(requested); + return { requested, target }; + }) + ); + + const seenItems = new Set(); + const seenVariantSlugs = new Set(); + const resolvedEntries = rawResolved.map(({ requested, target }) => { + if (!target.variantSlug) { + return { + requested, + variantSlug: null as string | null, + deduplicated: false, + }; + } + const lowerVariantSlug = target.variantSlug.toLowerCase(); + if ( + seenVariantSlugs.has(lowerVariantSlug) || + (target.itemId !== null && seenItems.has(target.itemId)) + ) { + return { + requested, + variantSlug: target.variantSlug, + deduplicated: true, + }; + } + seenVariantSlugs.add(lowerVariantSlug); + if (target.itemId !== null) seenItems.add(target.itemId); + return { + requested, + variantSlug: target.variantSlug, + deduplicated: false, + }; + }); + + const deduplicatedSlugs = resolvedEntries + .filter((entry) => entry.deduplicated) + .map((entry) => entry.requested); + const comparedSlugs = resolvedEntries + .filter( + ( + entry + ): entry is { + requested: string; + variantSlug: string; + deduplicated: false; + } => !entry.deduplicated && entry.variantSlug !== null + ) + .map((entry) => entry.variantSlug); + + const [comparedProducts, filteredReviewCounts] = await Promise.all([ + comparedSlugs.length >= 2 + ? readers.getCachedCompareMasterProducts(comparedSlugs.join(',')) + : comparedSlugs.length === 1 + ? readers + .getCachedMasterProductBySlug(comparedSlugs[0]!) + .then((p) => (p ? [p] : [])) + : Promise.resolve([]), + readers + .getCachedFilteredReviewCountsByMaster() + .catch(() => ({}) as FilteredReviewCountsByMaster), + ]); + + const returnedSlugSet = new Set( + comparedProducts.map((p) => p.slug.toLowerCase()) + ); + const missingEntries = resolvedEntries.filter( + (entry) => + !entry.deduplicated && + (entry.variantSlug === null || + !returnedSlugSet.has(entry.variantSlug.toLowerCase())) + ); + const missingLookup = await Promise.all( + missingEntries.map((entry) => + entry.variantSlug === null + ? Promise.resolve(false) + : readers.getCachedMasterProductBySlug(entry.variantSlug).then( + (p) => p !== null, + () => false + ) + ) + ); + const excludedCrossCategorySlugs = missingEntries + .filter((_, idx) => missingLookup[idx]) + .map((entry) => entry.requested); + const notFoundSlugs = missingEntries + .filter((_, idx) => !missingLookup[idx]) + .map((entry) => entry.requested); + + if (comparedProducts.length < 2) { + return buildToolCallResult( + { + ok: false, + error: + 'At least 2 distinct published products in the same device category are required for side-by-side comparison.', + requested_slugs: rawArgs.slugs, + deduplicated_slugs: deduplicatedSlugs, + excluded_cross_category_slugs: excludedCrossCategorySlugs, + not_found_slugs: notFoundSlugs, + canonical_citation_url: buildCanonicalRateUrl('/compare'), + observed_at: snapshotAt, + }, + true + ); + } + + const lockedCategory = getMasterProductCategorySlug(comparedProducts[0]!); + const presetWeights = PERSONA_WEIGHT_PRESETS[rawArgs.persona]; + const rawMergedWeights: LeaderboardCriteriaWeights = { + screen: rawArgs.weights?.screen ?? presetWeights.screen, + performance: rawArgs.weights?.performance ?? presetWeights.performance, + camera: rawArgs.weights?.camera ?? presetWeights.camera, + battery: rawArgs.weights?.battery ?? presetWeights.battery, + value: rawArgs.weights?.value ?? presetWeights.value, + }; + const applicableCriteria = leaderboardCriteriaForCategory(lockedCategory); + + const offersList = await Promise.all( + comparedProducts.map((p) => readers.getCachedMasterProductOffers(p.id)) + ); + + const scoredEntries = comparedProducts.map((stored, idx) => { + const scoped = applyCategorySpecTemplate(lockedCategory, stored); + const scored = scoreMasterProductForLeaderboard( + scoped, + 'combined', + filteredReviewCounts + ); + return { + scoped, + scored, + rawOffers: offersList[idx] ?? [], + }; + }); + + // Only criteria where every compared model meets CRITERION_RANK_WRITERS (>= 5) participate. + let sharedCriteria: LeaderboardScoreCriterion[] = [...applicableCriteria]; + for (let i = 1; i < scoredEntries.length; i++) { + const pairShared = new Set( + sharedScoredCriteria( + scoredEntries[0]!.scored.rankCriteria, + scoredEntries[i]!.scored.rankCriteria + ) + ); + sharedCriteria = sharedCriteria.filter((c) => pairShared.has(c)); + } + + const totalSharedWeight = sharedCriteria.reduce( + (acc, key) => acc + rawMergedWeights[key], + 0 + ); + const weightsFallbackApplied = + sharedCriteria.length === 0 || totalSharedWeight <= 0; + const appliedWeightsPct = Object.fromEntries( + LEADERBOARD_SCORE_CRITERIA.map((key) => { + if (!sharedCriteria.includes(key)) return [key, 0]; + if (totalSharedWeight <= 0) { + return [key, roundScore(100 / sharedCriteria.length, 1)]; + } + return [ + key, + roundScore((rawMergedWeights[key] / totalSharedWeight) * 100, 1), + ]; + }) + ) as LeaderboardCriteriaWeights; + + const devices = scoredEntries.map(({ scoped, scored, rawOffers }) => { + const { + inStockOffers, + plausibleInStockOffers, + excludedUnavailableCount, + excludedBaitCount, + } = getPlausibleInStockMerchantOffers(rawOffers); + const plausiblePrices = plausibleInStockOffers.map((o) => + Math.round(parseFiniteDecimalInput(o.price_current)) + ); + const verifiedMinPrice = + plausiblePrices.length > 0 ? Math.min(...plausiblePrices) : null; + const verifiedMaxPrice = + plausiblePrices.length > 0 ? Math.max(...plausiblePrices) : null; + + // Blend unrounded userScore5 (or combinedScore5 when unrated by buyers) so rounding happens once (#1531 D3). + const unroundedBaseOverall5 = + scored.userScore5 > 0 + ? scored.userScore5 + : scored.combinedScore5 > 0 + ? scored.combinedScore5 + : null; + const weightedCriteria5 = + sharedCriteria.length > 0 + ? weightedCriteriaScore5( + scored.rankCriteria, + appliedWeightsPct, + sharedCriteria + ) + : null; + const useCaseScore5 = + unroundedBaseOverall5 != null && weightedCriteria5 != null + ? roundScore(unroundedBaseOverall5 * 0.35 + weightedCriteria5 * 0.65, 2) + : unroundedBaseOverall5 != null + ? roundScore(unroundedBaseOverall5, 2) + : weightedCriteria5; + const href = getMasterProductHref(scoped); + const { observedAt, freshnessSource } = resolveProductObservedAt( + scoped, + snapshotAt + ); + + return { + slug: sanitizeMcpPublicText(scoped.slug, 120), + name: sanitizeMcpPublicText(scoped.name, 240), + brand: sanitizeMcpPublicText(scoped.brand, 80), + category: lockedCategory, + verified_min_price_vnd: verifiedMinPrice, + verified_max_price_vnd: verifiedMaxPrice, + in_stock_offer_count: plausibleInStockOffers.length, + excluded_unavailable_offer_count: excludedUnavailableCount, + excluded_bait_offer_count: excludedBaitCount, + sale_state: saleStateOfMaster( + scoped, + listingCountForSaleState(rawOffers.length, inStockOffers.length) + ), + bayesian_rating_5: productRatingScore5(scoped), + expert_rating_10: scored.expertScore10, + criteria_scores_5: scored.criteria, + use_case_score_5: useCaseScore5, + use_case_score_10: + useCaseScore5 != null + ? roundScore(displayedScore5(useCaseScore5) * 2, 1) + : null, + authentic_review_count: scored.authenticReviewCount, + filtered_noise_review_count: scored.filteredNoiseReviewCount, + key_specs: scoped.key_specs ?? {}, + specifications: scoped.specifications ?? {}, + deal_radar: radarExportFields( + computeProductRadarSignal(scoped, plausibleInStockOffers) + ), + canonical_citation_url: buildCanonicalRateUrl(href), + observed_at: observedAt, + price_observed_at: observedAt, + freshness_source: freshnessSource, + }; + }); + + const scoredDevicesOnly = devices.filter((d) => d.use_case_score_5 !== null); + const rankedByUseCase = [...scoredDevicesOnly].sort((a, b) => { + const scoreA = a.use_case_score_5 ?? -1; + const scoreB = b.use_case_score_5 ?? -1; + if (scoreB !== scoreA) return scoreB - scoreA; + const priceA = a.verified_min_price_vnd ?? Number.MAX_SAFE_INTEGER; + const priceB = b.verified_min_price_vnd ?? Number.MAX_SAFE_INTEGER; + return priceA - priceB; + }); + + const compareSlugsParam = devices + .map((d) => encodeURIComponent(d.slug)) + .join(','); + const compareCitationUrl = buildCanonicalRateUrl( + `/compare?cat=${lockedCategory}&slugs=${compareSlugsParam}` + ); + + return buildToolCallResult({ + ok: true, + tool: 'compare_devices_by_use_case', + locked_category: lockedCategory, + persona: rawArgs.persona, + applied_weights_pct: appliedWeightsPct, + weights_fallback_applied: weightsFallbackApplied, + compared_criteria: sharedCriteria, + recommended_slug_for_use_case: rankedByUseCase[0]?.slug ?? null, + deduplicated_slugs: deduplicatedSlugs, + excluded_cross_category_slugs: excludedCrossCategorySlugs, + not_found_slugs: notFoundSlugs, + canonical_citation_url: compareCitationUrl, + observed_at: snapshotAt, + devices, + }); +} + +async function executeAuditListingUrl( + rawArgs: z.infer, + readers: McpDataReaders +): Promise { + const snapshotAt = (readers.nowIso ?? DEFAULT_MCP_READERS.nowIso!)(); + // Canonicalize tracking query params / fragments BEFORE cache lookup so + // affiliate parameters (?sp_atk=, ?utm_*, ?fbclid=) never bypass withRateDataCache. + const canonicalListingUrl = canonicalizeProductUrl(rawArgs.url); + const lookupTarget = canonicalListingUrl || rawArgs.url; + const inspection = + await readers.getCachedInspectProductOrShopUrl(lookupTarget); + + const masterProduct = inspection.masterProduct + ? applyCategorySpecTemplate( + getMasterProductCategorySlug(inspection.masterProduct), + inspection.masterProduct + ) + : null; + const queryPrice = rawArgs.observedPriceVnd ?? null; + const queryOriginalPrice = rawArgs.observedOriginalPriceVnd ?? null; + + const { observedPrice, observedOriginalPrice } = resolveInspectObservedPrices( + { + queryPrice, + queryOriginalPrice, + matchedOfferPriceCurrent: inspection.matchedOffer?.price_current, + matchedOfferPriceOriginal: inspection.matchedOffer?.price_original, + masterMinPrice: masterProduct?.min_price, + maxVnd: MAX_VALID_VND_PRICE, + } + ); + + const gatekeeper = detectAccessoryOrJunk({ + title: + inspection.matchedOffer?.title || masterProduct?.name || lookupTarget, + url: lookupTarget, + price: observedPrice > 0 ? observedPrice : null, + }); + + const rawMatchedPrice = parseFiniteDecimalInput( + inspection.matchedOffer?.price_current + ); + const matchedOfferHasPositivePrice = + Number.isFinite(rawMatchedPrice) && + rawMatchedPrice > 0 && + rawMatchedPrice <= MAX_VALID_VND_PRICE; + + const priceVerdict = evaluateExtensionPriceVerdict({ + isAccessory: gatekeeper.isAccessory, + accessoryReason: gatekeeper.reason, + accessoryMessage: gatekeeper.message, + isAmbiguousVariant: false, + observedPrice: observedPrice > 0 ? observedPrice : null, + observedOriginalPrice: + observedOriginalPrice > 0 ? observedOriginalPrice : null, + offers: inspection.allOffers, + observedOfferId: + inspection.matchedType === 'product_listing' || + (queryPrice === null && matchedOfferHasPositivePrice) + ? (inspection.matchedOffer?.id ?? null) + : null, + hasLiveObservedPrice: typeof queryPrice === 'number' && queryPrice > 0, + priceHistory: inspection.priceHistory, + }); + + const { + plausibleInStockOffers, + excludedUnavailableCount, + excludedBaitCount, + } = getPlausibleInStockMerchantOffers(inspection.allOffers ?? []); + const radarSignal = masterProduct + ? radarExportFields( + computeProductRadarSignal(masterProduct, plausibleInStockOffers) + ) + : null; + + const inspectCitationUrl = buildCanonicalRateUrl( + `/inspect?q=${encodeURIComponent(lookupTarget)}` + ); + const primaryCitationUrl = masterProduct + ? buildCanonicalRateUrl(getMasterProductHref(masterProduct)) + : buildSafeMerchantCitationUrl( + inspection.merchantProfile?.id, + inspectCitationUrl + ); + + const { observedAt: productObservedAt } = resolveProductObservedAt( + masterProduct, + snapshotAt + ); + + const matchedOfferPublic = inspection.matchedOffer + ? withPublicOfferReviewRisk(inspection.matchedOffer) + : null; + const merchantProfilePublic = inspection.merchantProfile + ? withPublicReviewRisk(inspection.merchantProfile) + : null; + + const matchedOfferPriceCurrent = matchedOfferPublic + ? toBoundedPositiveVndOrNull(matchedOfferPublic.price_current) + : null; + const rawMatchedOfferOrig = matchedOfferPublic + ? parseFiniteDecimalInput(matchedOfferPublic.price_original) + : Number.NaN; + const matchedOfferPriceOriginal = + matchedOfferPriceCurrent !== null + ? normalizeOfferOriginalPrice( + matchedOfferPriceCurrent, + Number.isFinite(rawMatchedOfferOrig) ? rawMatchedOfferOrig : 0 + ) + : null; + + const topCompetingOffers = [...plausibleInStockOffers] + .sort( + (a, b) => + parseFiniteDecimalInput(a.price_current) - + parseFiniteDecimalInput(b.price_current) + ) + .slice(0, 5) + .map((offer) => { + const pub = withPublicOfferReviewRisk(offer); + return { + id: sanitizeMcpPublicText(pub.id, 128), + platform: sanitizeMcpPublicText( + pub.merchant?.platform || pub.platform || 'shopee', + 32 + ).toLowerCase(), + title: sanitizeMcpPublicText(pub.title, 240), + price_current_vnd: Math.round( + parseFiniteDecimalInput(pub.price_current) + ), + merchant_name: sanitizeMcpPublicText(pub.merchant?.name, 160), + is_official_mall: Boolean(pub.merchant?.is_official), + merchant_risk_score: pub.merchant?.risk_score ?? null, + dosafe_risk_score: pub.merchant?.dosafe_risk_score ?? null, + review_risk_score: pub.merchant?.review_risk_score ?? null, + offer_url: sanitizeExternalOfferUrl(pub.url), + canonical_citation_url: primaryCitationUrl, + observed_at: productObservedAt, + price_observed_at: productObservedAt, + }; + }); + + const suggestions = (inspection.suggestions ?? []).slice(0, 5).map((s) => { + const cat = getMasterProductCategorySlug(s); + const scoped = applyCategorySpecTemplate(cat, s); + const { observedAt } = resolveProductObservedAt(scoped, snapshotAt); + return { + slug: sanitizeMcpPublicText(scoped.slug, 120), + name: sanitizeMcpPublicText(scoped.name, 240), + brand: sanitizeMcpPublicText(scoped.brand, 80), + category: cat, + canonical_citation_url: buildCanonicalRateUrl( + getMasterProductHref(scoped) + ), + observed_at: observedAt, + }; + }); + + return buildToolCallResult({ + ok: true, + tool: 'audit_listing_url', + matched_type: inspection.matchedType, + detected_platform: inspection.parsedUrl?.platform ?? null, + canonical_listing_url: canonicalListingUrl, + canonical_citation_url: primaryCitationUrl, + inspect_citation_url: inspectCitationUrl, + observed_at: productObservedAt, + price_observed_at: productObservedAt, + gatekeeper: { + is_accessory_or_part: gatekeeper.isAccessory, + reason: gatekeeper.reason ?? null, + }, + price_verdict: priceVerdict, + deal_radar: radarSignal, + matched_product: masterProduct + ? { + slug: sanitizeMcpPublicText(masterProduct.slug, 120), + name: sanitizeMcpPublicText(masterProduct.name, 240), + brand: sanitizeMcpPublicText(masterProduct.brand, 80), + category: getMasterProductCategorySlug(masterProduct), + bayesian_rating_5: productRatingScore5(masterProduct), + expert_rating_10: resolveExpertRating10(masterProduct), + canonical_citation_url: buildCanonicalRateUrl( + getMasterProductHref(masterProduct) + ), + observed_at: productObservedAt, + } + : null, + matched_offer: matchedOfferPublic + ? { + id: sanitizeMcpPublicText(matchedOfferPublic.id, 128), + platform: sanitizeMcpPublicText( + matchedOfferPublic.platform, + 32 + ).toLowerCase(), + title: sanitizeMcpPublicText(matchedOfferPublic.title, 280), + price_current_vnd: matchedOfferPriceCurrent, + price_original_vnd: matchedOfferPriceOriginal, + availability: matchedOfferPublic.availability ?? null, + is_unavailable: isOfferUnavailable(matchedOfferPublic), + canonical_citation_url: primaryCitationUrl, + price_observed_at: productObservedAt, + observed_at: productObservedAt, + } + : null, + merchant_risk_summary: merchantProfilePublic + ? { + id: sanitizeMcpPublicText(merchantProfilePublic.id, 128), + name: sanitizeMcpPublicText(merchantProfilePublic.name, 160), + platform: sanitizeMcpPublicText( + merchantProfilePublic.platform, + 32 + ).toLowerCase(), + is_official_mall: Boolean(merchantProfilePublic.is_official), + risk_score: merchantProfilePublic.risk_score ?? null, + dosafe_risk_score: merchantProfilePublic.dosafe_risk_score ?? null, + review_risk_score: merchantProfilePublic.review_risk_score ?? null, + canonical_citation_url: buildSafeMerchantCitationUrl( + merchantProfilePublic.id, + inspectCitationUrl + ), + observed_at: snapshotAt, + } + : matchedOfferPublic?.merchant + ? { + id: sanitizeMcpPublicText(matchedOfferPublic.merchant.id, 128), + name: sanitizeMcpPublicText(matchedOfferPublic.merchant.name, 160), + platform: sanitizeMcpPublicText( + matchedOfferPublic.merchant.platform, + 32 + ).toLowerCase(), + is_official_mall: Boolean(matchedOfferPublic.merchant.is_official), + risk_score: matchedOfferPublic.merchant.risk_score ?? null, + dosafe_risk_score: + matchedOfferPublic.merchant.dosafe_risk_score ?? null, + review_risk_score: + matchedOfferPublic.merchant.review_risk_score ?? null, + canonical_citation_url: buildSafeMerchantCitationUrl( + matchedOfferPublic.merchant.id, + inspectCitationUrl + ), + observed_at: snapshotAt, + } + : null, + excluded_unavailable_offer_count: excludedUnavailableCount, + excluded_bait_offer_count: excludedBaitCount, + top_competing_offers: topCompetingOffers, + suggestions, + }); +} + +async function executeGetGenuineDeals( + rawArgs: z.infer, + readers: McpDataReaders +): Promise { + const snapshotAt = (readers.nowIso ?? DEFAULT_MCP_READERS.nowIso!)(); + const limit = Math.min(rawArgs.limit, MAX_MCP_RESULT_ITEMS); + + const radar = await readers.getCrossPlatformDealRadar({ + categorySlug: rawArgs.category, + platform: rawArgs.platform, + limit: 30, + }); + + const radarObservedAt = + resolveValidIsoTimestamp(radar.generatedAt) ?? snapshotAt; + + const filteredDeals = (radar.genuineDeals ?? []) + .filter((deal) => { + if (rawArgs.officialOnly && !deal.isOfficialMall) return false; + if ( + rawArgs.maxBudgetVnd !== undefined && + deal.priceCurrent > rawArgs.maxBudgetVnd + ) { + return false; + } + return true; + }) + .slice(0, limit) + .map((deal) => ({ + id: sanitizeMcpPublicText(deal.id, 128), + verdict: deal.verdict, + product_slug: sanitizeMcpPublicText(deal.productSlug, 120), + product_name: sanitizeMcpPublicText(deal.productName, 240), + brand: sanitizeMcpPublicText(deal.brand, 80), + category: deal.categorySlug, + platform: sanitizeMcpPublicText(deal.platform, 32).toLowerCase(), + merchant_id: sanitizeMcpPublicText(deal.merchantId, 128), + merchant_name: sanitizeMcpPublicText(deal.merchantName, 160), + is_official_mall: Boolean(deal.isOfficialMall), + merchant_risk_score: deal.merchantRiskScore, + price_current_vnd: deal.priceCurrent, + price_original_vnd: deal.priceOriginal, + market_median_price_vnd: deal.marketMedianPrice, + market_min_price_vnd: deal.marketMinPrice, + market_max_price_vnd: deal.marketMaxPrice, + savings_vs_median_vnd: deal.savingsVsMedianVnd, + savings_vs_median_pct: deal.savingsVsMedianPct, + market_offer_count: deal.marketOfferCount, + jreviews_score_10: deal.jreviewsScore10, + offer_url: sanitizeExternalOfferUrl(deal.offerUrl), + canonical_citation_url: buildCanonicalRateUrl(deal.productHref), + price_observed_at: radarObservedAt, + observed_at: radarObservedAt, + })); + + return buildToolCallResult({ + ok: true, + tool: 'get_genuine_deals', + category_filter: rawArgs.category, + platform_filter: rawArgs.platform, + total_clusters_analyzed: radar.totalClustersAnalyzed, + total_offers_analyzed: radar.totalOffersAnalyzed, + total_merchants_analyzed: radar.totalMerchantsAnalyzed, + returned_count: filteredDeals.length, + max_limit: MAX_MCP_RESULT_ITEMS, + canonical_citation_url: buildCanonicalRateUrl('/deals'), + observed_at: radarObservedAt, + price_observed_at: radarObservedAt, + deals: filteredDeals, + }); +} + +class JsonPayloadGuardError extends Error { + public readonly rpcCode: number; + constructor(rpcCode: number, message: string) { + super(message); + this.name = 'JsonPayloadGuardError'; + this.rpcCode = rpcCode; + } +} + +function hasUnsafeNumericRpcIdToken(rawJsonText: string): boolean { + // Detect unquoted top-level numeric `"id": ` tokens that are fractional, + // exponential, or outside IEEE-754 safe integer precision BEFORE JSON.parse rounds them. + const idMatch = rawJsonText.match( + /"id"\s*:\s*(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)/ + ); + if (!idMatch) return false; + const literal = idMatch[1]!; + if (/[.eE]/.test(literal)) return true; + try { + const asBigInt = BigInt(literal); + return ( + asBigInt > BigInt(Number.MAX_SAFE_INTEGER) || + asBigInt < BigInt(Number.MIN_SAFE_INTEGER) + ); + } catch { + return true; + } +} + +function sanitizeJsonValueOrThrow(value: unknown, depth = 0): unknown { + if (depth > MAX_JSON_NESTING_DEPTH) { + throw new JsonPayloadGuardError( + -32600, + `Invalid Request: JSON nesting depth exceeds ${MAX_JSON_NESTING_DEPTH}` + ); + } + if (typeof value === 'string') { + return toWellFormedString(value); + } + if ( + value === null || + typeof value === 'number' || + typeof value === 'boolean' + ) { + return value; + } + if (Array.isArray(value)) { + if (value.length > MAX_JSON_ARRAY_ITEMS) { + throw new JsonPayloadGuardError( + -32600, + `Invalid Request: JSON array exceeds ${MAX_JSON_ARRAY_ITEMS} elements` + ); + } + return value.map((item) => sanitizeJsonValueOrThrow(item, depth + 1)); + } + if (typeof value === 'object') { + const ownKeys = Object.getOwnPropertyNames(value); + if (ownKeys.length > MAX_JSON_OBJECT_KEYS) { + throw new JsonPayloadGuardError( + -32600, + `Invalid Request: JSON object exceeds ${MAX_JSON_OBJECT_KEYS} keys` + ); + } + const out: Record = {}; + for (const rawKey of ownKeys) { + if (FORBIDDEN_OBJECT_KEYS.has(rawKey)) { + throw new JsonPayloadGuardError( + -32600, + `Invalid Request: forbidden prototype key "${rawKey}"` + ); + } + const cleanKey = toWellFormedString(rawKey); + if (FORBIDDEN_OBJECT_KEYS.has(cleanKey)) { + throw new JsonPayloadGuardError( + -32600, + `Invalid Request: forbidden prototype key "${cleanKey}"` + ); + } + const rawVal = (value as Record)[rawKey]; + out[cleanKey] = sanitizeJsonValueOrThrow(rawVal, depth + 1); + } + return out; + } + return null; +} + +type ReadMcpBodyOutcome = + | { kind: 'too_large' } + | { kind: 'invalid_content_length' } + | { kind: 'parse_error'; message: string } + | { kind: 'guard_error'; rpcCode: number; message: string } + | { kind: 'ok'; value: unknown; unsafeNumericId: boolean }; + +async function readBoundedMcpJsonBody( + request: Request, + maxBytes = MAX_MCP_BODY_BYTES +): Promise { + const rawContentLength = request.headers.get('content-length'); + if (rawContentLength !== null) { + const trimmed = rawContentLength.trim(); + if (!/^\d+$/.test(trimmed)) { + return { kind: 'invalid_content_length' }; + } + const declared = Number(trimmed); + if (!Number.isSafeInteger(declared)) { + return { kind: 'invalid_content_length' }; + } + if (declared > maxBytes) { + return { kind: 'too_large' }; + } + } + + if (!request.body) { + return { kind: 'parse_error', message: 'Parse error: empty request body' }; + } + + let reader: ReadableStreamDefaultReader; + try { + reader = request.body.getReader(); + } catch { + return { + kind: 'parse_error', + message: 'Parse error: unreadable request body stream', + }; + } + + const chunks: Uint8Array[] = []; + let size = 0; + try { + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + size += value.byteLength; + if (size > maxBytes) { + await reader.cancel().catch(() => undefined); + return { kind: 'too_large' }; + } + chunks.push(value); + } + } catch { + await reader.cancel().catch(() => undefined); + return { + kind: 'parse_error', + message: 'Parse error: unreadable or aborted request body', + }; + } + + if (size === 0) { + return { kind: 'parse_error', message: 'Parse error: empty request body' }; + } + + const bytes = new Uint8Array(size); + let offset = 0; + for (const chunk of chunks) { + bytes.set(chunk, offset); + offset += chunk.byteLength; + } + + let decodedText: string; + try { + decodedText = new TextDecoder('utf-8', { + fatal: true, + ignoreBOM: true, + }).decode(bytes); + } catch { + return { + kind: 'parse_error', + message: 'Parse error: request body must be valid UTF-8 JSON', + }; + } + + let rawParsed: unknown; + try { + rawParsed = JSON.parse(decodedText); + } catch { + return { kind: 'parse_error', message: 'Parse error: malformed JSON body' }; + } + + if (Array.isArray(rawParsed)) { + return { + kind: 'guard_error', + rpcCode: -32600, + message: + 'Invalid Request: JSON-RPC batch arrays are not supported on this stateless MCP endpoint; send one JSON-RPC 2.0 object per POST.', + }; + } + + try { + const cleanValue = sanitizeJsonValueOrThrow(rawParsed, 0); + return { + kind: 'ok', + value: cleanValue, + unsafeNumericId: hasUnsafeNumericRpcIdToken(decodedText), + }; + } catch (err) { + if (err instanceof JsonPayloadGuardError) { + return { + kind: 'guard_error', + rpcCode: err.rpcCode, + message: err.message, + }; + } + return { + kind: 'parse_error', + message: 'Parse error: invalid JSON payload', + }; + } +} + +function mcpResponseHeaders( + protocolVersion: string = MCP_LATEST_PROTOCOL_VERSION, + extra?: Record +): Record { + return { + ...MCP_CORS_HEADERS, + 'Cache-Control': 'no-store', + 'MCP-Protocol-Version': protocolVersion, + ...extra, + }; +} + +function jsonRpcErrorResponse( + httpStatus: number, + id: string | number | null, + code: number, + message: string, + data?: Record, + extraHeaders?: Record, + protocolVersion: string = MCP_LATEST_PROTOCOL_VERSION +): NextResponse { + return NextResponse.json( + { + jsonrpc: '2.0', + id, + error: { + code, + message: sanitizeMcpErrorMessage(message, 'MCP request error'), + ...(data ? { data: deepSanitizeWellFormed(data) } : {}), + }, + }, + { + status: httpStatus, + headers: mcpResponseHeaders(protocolVersion, extraHeaders), + } + ); +} + +function jsonRpcResultResponse( + id: string | number, + result: Record, + protocolVersion: string = MCP_LATEST_PROTOCOL_VERSION +): NextResponse { + return NextResponse.json( + { + jsonrpc: '2.0', + id, + result: deepSanitizeWellFormed(result), + }, + { + status: 200, + headers: mcpResponseHeaders(protocolVersion), + } + ); +} + +function isValidJsonContentType(rawHeader: string | null): boolean { + if (typeof rawHeader !== 'string') return false; + const parts = rawHeader.split(';').map((s) => s.trim()); + const mediaType = (parts[0] ?? '').toLowerCase(); + if (mediaType !== 'application/json') return false; + for (const param of parts.slice(1)) { + const eqIdx = param.indexOf('='); + if (eqIdx === -1) continue; + const k = param.slice(0, eqIdx).trim().toLowerCase(); + const v = param + .slice(eqIdx + 1) + .trim() + .replace(/^"|"$/g, '') + .toLowerCase(); + if (k === 'charset' && v !== 'utf-8' && v !== 'utf8') { + return false; + } + } + return true; +} + +function acceptsJsonResponse(acceptHeader: string | null): boolean { + if (acceptHeader === null || !acceptHeader.trim()) return true; + for (const entry of acceptHeader.split(',')) { + const segments = entry.split(';').map((s) => s.trim()); + const mediaRange = (segments[0] ?? '').toLowerCase(); + if ( + mediaRange !== 'application/json' && + mediaRange !== 'application/*' && + mediaRange !== '*/*' + ) { + continue; + } + let qZero = false; + for (const param of segments.slice(1)) { + const eqIdx = param.indexOf('='); + if (eqIdx === -1) continue; + const k = param.slice(0, eqIdx).trim().toLowerCase(); + const v = param.slice(eqIdx + 1).trim(); + if (k === 'q' && /^0(?:\.0{1,3})?$/.test(v)) { + qZero = true; + break; + } + } + if (!qZero) return true; + } + return false; +} + +function isPlainRecord(value: unknown): value is Record { + return Boolean(value && typeof value === 'object' && !Array.isArray(value)); +} + +function extractValidRpcId( + rawId: unknown, + unsafeNumericId = false +): { + valid: boolean; + id: string | number | null; +} { + if (typeof rawId === 'string') { + if ( + rawId.length >= 1 && + rawId.length <= MAX_RPC_ID_LENGTH && + !/\p{Cc}/u.test(rawId) + ) { + return { valid: true, id: rawId }; + } + return { valid: false, id: null }; + } + if (typeof rawId === 'number') { + if (!unsafeNumericId && Number.isSafeInteger(rawId)) { + return { valid: true, id: Object.is(rawId, -0) ? 0 : rawId }; + } + return { valid: false, id: null }; + } + return { valid: false, id: null }; +} + +const InitializeParamsSchema = z + .object({ + protocolVersion: z.string().trim().min(1).max(64).optional(), + capabilities: z.record(z.string(), z.unknown()).optional(), + clientInfo: z + .object({ + name: z.string().max(128).optional(), + version: z.string().max(64).optional(), + }) + .optional(), + }) + .passthrough(); + +export interface HandleMcpRequestOptions { + readers?: Partial; + rateLimiter?: BoundedSlidingWindowRateLimiter; + auditUrlRateLimiter?: BoundedSlidingWindowRateLimiter; +} + +export function buildMcpMethodNotAllowedResponse(): NextResponse { + return jsonRpcErrorResponse( + 405, + null, + -32600, + 'Method Not Allowed: /api/mcp is a stateless Streamable HTTP MCP endpoint. Send JSON-RPC 2.0 requests via POST.', + undefined, + { Allow: 'POST, OPTIONS' } + ); +} + +export function buildMcpCorsPreflightResponse(): NextResponse { + return new NextResponse(null, { + status: 204, + headers: mcpResponseHeaders(MCP_LATEST_PROTOCOL_VERSION, { + Allow: 'POST, OPTIONS', + }), + }); +} + +export async function handleMcpHttpPost( + request: Request, + options?: HandleMcpRequestOptions +): Promise { + try { + const limiter = options?.rateLimiter ?? mcpRateLimiter; + const auditLimiter = options?.auditUrlRateLimiter ?? inspectRateLimiter; + const clientKey = extractClientRateLimitKey(request.headers); + + const rawHeaderVersion = request.headers + .get('mcp-protocol-version') + ?.trim(); + if ( + rawHeaderVersion && + (rawHeaderVersion.length > 64 || /[\s\p{Cc}]/u.test(rawHeaderVersion)) + ) { + return jsonRpcErrorResponse( + 400, + null, + -32600, + 'Invalid Request: malformed MCP-Protocol-Version header' + ); + } + const headerVersionSupported = Boolean( + rawHeaderVersion && + (SUPPORTED_MCP_PROTOCOL_VERSIONS as readonly string[]).includes( + rawHeaderVersion + ) + ); + const activeProtocolVersion = headerVersionSupported + ? rawHeaderVersion! + : MCP_LATEST_PROTOCOL_VERSION; + + if (!limiter.allow(clientKey)) { + return jsonRpcErrorResponse( + 429, + null, + -32029, + `Rate limit exceeded. Maximum ${MCP_RATE_LIMIT_MAX_REQUESTS} MCP requests per minute.`, + { + code: 'RATE_LIMIT_EXCEEDED', + retryAfterSeconds: MCP_RETRY_AFTER_SECONDS, + }, + { 'Retry-After': String(MCP_RETRY_AFTER_SECONDS) }, + activeProtocolVersion + ); + } + + if (!isValidJsonContentType(request.headers.get('content-type'))) { + return jsonRpcErrorResponse( + 415, + null, + -32600, + 'Unsupported Media Type: Content-Type must be application/json (UTF-8)', + undefined, + undefined, + activeProtocolVersion + ); + } + + if (!acceptsJsonResponse(request.headers.get('accept'))) { + return jsonRpcErrorResponse( + 406, + null, + -32600, + 'Not Acceptable: client must accept application/json', + undefined, + undefined, + activeProtocolVersion + ); + } + + const bodyOutcome = await readBoundedMcpJsonBody( + request, + MAX_MCP_BODY_BYTES + ); + if (bodyOutcome.kind === 'too_large') { + return jsonRpcErrorResponse( + 413, + null, + -32600, + `Request body exceeds ${MAX_MCP_BODY_BYTES} bytes limit`, + { code: 'PAYLOAD_TOO_LARGE', maxBytes: MAX_MCP_BODY_BYTES }, + undefined, + activeProtocolVersion + ); + } + if (bodyOutcome.kind === 'invalid_content_length') { + return jsonRpcErrorResponse( + 400, + null, + -32600, + 'Invalid Request: malformed Content-Length header', + undefined, + undefined, + activeProtocolVersion + ); + } + if (bodyOutcome.kind === 'parse_error') { + return jsonRpcErrorResponse( + 400, + null, + -32700, + bodyOutcome.message, + undefined, + undefined, + activeProtocolVersion + ); + } + if (bodyOutcome.kind === 'guard_error') { + return jsonRpcErrorResponse( + 400, + null, + bodyOutcome.rpcCode, + bodyOutcome.message, + undefined, + undefined, + activeProtocolVersion + ); + } + + const envelope = bodyOutcome.value; + if (!isPlainRecord(envelope)) { + return jsonRpcErrorResponse( + 400, + null, + -32600, + 'Invalid Request: JSON-RPC 2.0 message must be a JSON object', + undefined, + undefined, + activeProtocolVersion + ); + } + + const jsonrpcVersion = Object.hasOwn(envelope, 'jsonrpc') + ? envelope.jsonrpc + : undefined; + const rawMethod = Object.hasOwn(envelope, 'method') + ? envelope.method + : undefined; + const hasId = Object.hasOwn(envelope, 'id'); + const rawId = hasId ? envelope.id : undefined; + const parsedId = hasId + ? extractValidRpcId(rawId, bodyOutcome.unsafeNumericId) + : { valid: false, id: null }; + + if ( + jsonrpcVersion !== '2.0' || + typeof rawMethod !== 'string' || + !rawMethod.trim() || + rawMethod.length > 128 || + /\p{Cc}/u.test(rawMethod) + ) { + return jsonRpcErrorResponse( + 400, + parsedId.valid ? parsedId.id : null, + -32600, + 'Invalid Request: expected jsonrpc "2.0" and a valid method name', + undefined, + undefined, + activeProtocolVersion + ); + } + + const method = rawMethod.trim(); + + // Enforce supported MCP-Protocol-Version header only on post-initialize calls, + // allowing newer clients sending MCP-Protocol-Version on initialize to negotiate down. + if ( + method !== 'initialize' && + rawHeaderVersion && + !headerVersionSupported + ) { + return jsonRpcErrorResponse( + 400, + parsedId.valid ? parsedId.id : null, + -32600, + `Unsupported MCP-Protocol-Version header. Supported versions: ${SUPPORTED_MCP_PROTOCOL_VERSIONS.join(', ')}` + ); + } + + const hasParams = Object.hasOwn(envelope, 'params'); + const rawParams = hasParams ? envelope.params : undefined; + + // JSON-RPC 2.0 notifications omit `id`. + if (!hasId) { + if ( + method === 'notifications/initialized' || + method.startsWith('notifications/') + ) { + if (rawParams !== undefined && !isPlainRecord(rawParams)) { + return jsonRpcErrorResponse( + 400, + null, + -32602, + 'Invalid params: notification params must be an object when provided', + undefined, + undefined, + activeProtocolVersion + ); + } + return new NextResponse(null, { + status: 202, + headers: mcpResponseHeaders(activeProtocolVersion), + }); + } + return jsonRpcErrorResponse( + 400, + null, + -32600, + 'Invalid Request: id is required for JSON-RPC request methods', + undefined, + undefined, + activeProtocolVersion + ); + } + + if (!parsedId.valid || parsedId.id === null) { + return jsonRpcErrorResponse( + 400, + null, + -32600, + 'Invalid Request: id must be a non-empty string (<= 256 chars) or safe integer', + undefined, + undefined, + activeProtocolVersion + ); + } + + const requestId = parsedId.id; + if (rawParams !== undefined && !isPlainRecord(rawParams)) { + return jsonRpcErrorResponse( + 200, + requestId, + -32602, + 'Invalid params: params must be a JSON object when provided', + undefined, + undefined, + activeProtocolVersion + ); + } + + const readers: McpDataReaders = { + ...DEFAULT_MCP_READERS, + ...(options?.readers ?? {}), + }; + + if (method === 'initialize') { + const parsedInit = InitializeParamsSchema.safeParse(rawParams ?? {}); + if (!parsedInit.success) { + return jsonRpcErrorResponse( + 200, + requestId, + -32602, + 'Invalid params for initialize' + ); + } + const requestedVersion = parsedInit.data.protocolVersion; + const negotiatedVersion = + requestedVersion && + (SUPPORTED_MCP_PROTOCOL_VERSIONS as readonly string[]).includes( + requestedVersion + ) + ? requestedVersion + : MCP_LATEST_PROTOCOL_VERSION; + + return jsonRpcResultResponse( + requestId, + { + protocolVersion: negotiatedVersion, + capabilities: { + tools: { + listChanged: false, + }, + }, + serverInfo: MCP_SERVER_INFO, + instructions: MCP_SERVER_INSTRUCTIONS, + }, + negotiatedVersion + ); + } + + if (method === 'notifications/initialized') { + return jsonRpcResultResponse(requestId, {}, activeProtocolVersion); + } + + if (method === 'ping') { + return jsonRpcResultResponse(requestId, {}, activeProtocolVersion); + } + + if (method === 'tools/list') { + if ( + rawParams && + Object.hasOwn(rawParams, 'cursor') && + rawParams.cursor != null + ) { + return jsonRpcErrorResponse( + 200, + requestId, + -32602, + 'Invalid params: unknown pagination cursor', + undefined, + undefined, + activeProtocolVersion + ); + } + return jsonRpcResultResponse( + requestId, + { + tools: MCP_TOOL_DEFINITIONS, + }, + activeProtocolVersion + ); + } + + if (method === 'tools/call') { + if (!rawParams) { + return jsonRpcErrorResponse( + 200, + requestId, + -32602, + 'Invalid params: tools/call requires params object with tool name', + undefined, + undefined, + activeProtocolVersion + ); + } + const toolName = Object.hasOwn(rawParams, 'name') + ? rawParams.name + : undefined; + const rawToolArgs = Object.hasOwn(rawParams, 'arguments') + ? rawParams.arguments + : {}; + if (typeof toolName !== 'string' || !toolName.trim()) { + return jsonRpcErrorResponse( + 200, + requestId, + -32602, + 'Invalid params: tool name must be a non-empty string', + undefined, + undefined, + activeProtocolVersion + ); + } + if (rawToolArgs !== undefined && !isPlainRecord(rawToolArgs)) { + return jsonRpcErrorResponse( + 200, + requestId, + -32602, + 'Invalid params: tool arguments must be a JSON object', + undefined, + undefined, + activeProtocolVersion + ); + } + const safeToolArgs = rawToolArgs ?? {}; + + try { + switch (toolName) { + case 'search_verified_catalog': { + const parsed = + SearchVerifiedCatalogInputSchema.safeParse(safeToolArgs); + if (!parsed.success) { + return jsonRpcErrorResponse( + 200, + requestId, + -32602, + formatZodIssuesForMcp(parsed.error.issues), + undefined, + undefined, + activeProtocolVersion + ); + } + const result = await executeSearchVerifiedCatalog( + parsed.data, + readers + ); + return jsonRpcResultResponse( + requestId, + result as unknown as Record, + activeProtocolVersion + ); + } + + case 'get_22_store_offers_and_price_truth': { + const parsed = + GetStoreOffersAndPriceTruthInputSchema.safeParse(safeToolArgs); + if (!parsed.success) { + return jsonRpcErrorResponse( + 200, + requestId, + -32602, + formatZodIssuesForMcp(parsed.error.issues), + undefined, + undefined, + activeProtocolVersion + ); + } + const result = await executeGetStoreOffersAndPriceTruth( + parsed.data, + readers + ); + return jsonRpcResultResponse( + requestId, + result as unknown as Record, + activeProtocolVersion + ); + } + + case 'compare_devices_by_use_case': { + const parsed = + CompareDevicesByUseCaseInputSchema.safeParse(safeToolArgs); + if (!parsed.success) { + return jsonRpcErrorResponse( + 200, + requestId, + -32602, + formatZodIssuesForMcp(parsed.error.issues), + undefined, + undefined, + activeProtocolVersion + ); + } + const result = await executeCompareDevicesByUseCase( + parsed.data, + readers + ); + return jsonRpcResultResponse( + requestId, + result as unknown as Record, + activeProtocolVersion + ); + } + + case 'audit_listing_url': { + const parsed = AuditListingUrlInputSchema.safeParse(safeToolArgs); + if (!parsed.success) { + return jsonRpcErrorResponse( + 200, + requestId, + -32602, + formatZodIssuesForMcp(parsed.error.issues), + undefined, + undefined, + activeProtocolVersion + ); + } + if (!auditLimiter.allow(clientKey)) { + return jsonRpcErrorResponse( + 429, + requestId, + -32029, + 'Rate limit exceeded. Maximum 30 listing URL audits per minute.', + { + code: 'RATE_LIMIT_EXCEEDED', + retryAfterSeconds: MCP_RETRY_AFTER_SECONDS, + }, + { 'Retry-After': String(MCP_RETRY_AFTER_SECONDS) }, + activeProtocolVersion + ); + } + const result = await executeAuditListingUrl(parsed.data, readers); + return jsonRpcResultResponse( + requestId, + result as unknown as Record, + activeProtocolVersion + ); + } + + case 'get_genuine_deals': { + const parsed = GetGenuineDealsInputSchema.safeParse(safeToolArgs); + if (!parsed.success) { + return jsonRpcErrorResponse( + 200, + requestId, + -32602, + formatZodIssuesForMcp(parsed.error.issues), + undefined, + undefined, + activeProtocolVersion + ); + } + const result = await executeGetGenuineDeals(parsed.data, readers); + return jsonRpcResultResponse( + requestId, + result as unknown as Record, + activeProtocolVersion + ); + } + + default: + return jsonRpcErrorResponse( + 200, + requestId, + -32602, + `Unknown MCP tool: ${sanitizeMcpPublicText(toolName, 80)}`, + undefined, + undefined, + activeProtocolVersion + ); + } + } catch { + const snapshotAt = (readers.nowIso ?? DEFAULT_MCP_READERS.nowIso!)(); + const safeErrorResult = buildToolCallResult( + { + ok: false, + error: + 'Temporary service error while reading verified catalog data. Please retry shortly.', + canonical_citation_url: CANONICAL_RATE_ORIGIN, + observed_at: snapshotAt, + }, + true + ); + return jsonRpcResultResponse( + requestId, + safeErrorResult as unknown as Record, + activeProtocolVersion + ); + } + } + + return jsonRpcErrorResponse( + 200, + requestId, + -32601, + `Method not found: ${sanitizeMcpPublicText(method, 80)}`, + undefined, + undefined, + activeProtocolVersion + ); + } catch { + return jsonRpcErrorResponse(500, null, -32603, 'Internal MCP server error'); + } +} + +export function buildRateWellKnownMcpDescriptor(): Record { + return { + mcpVersion: MCP_LATEST_PROTOCOL_VERSION, + supportedProtocolVersions: [...SUPPORTED_MCP_PROTOCOL_VERSIONS], + name: 'io.github.dos/rate-vn', + serverInfo: MCP_SERVER_INFO, + description: + 'Stateless read-only Streamable HTTP Model Context Protocol (MCP) server for Rate.vn: verified tech prices across 22 Vietnamese retail platforms, 10-group standardized hardware specs, historical fake-discount audits, DOSafe scam risk, and 6-axis Review Trust Model v2 scores.', + transport: 'streamable-http', + url: `${CANONICAL_RATE_ORIGIN}/api/mcp`, + endpoints: { + mcp: `${CANONICAL_RATE_ORIGIN}/api/mcp`, + transport: 'streamable-http', + }, + remotes: [ + { + type: 'streamable-http', + transport: 'streamable-http', + url: `${CANONICAL_RATE_ORIGIN}/api/mcp`, + }, + ], + documentationUrl: `${CANONICAL_RATE_ORIGIN}/developers#mcp`, + llmsTxtUrl: `${CANONICAL_RATE_ORIGIN}/llms.txt`, + openApiUrl: `${CANONICAL_RATE_ORIGIN}/api/v1/rate/openapi.json`, + repositoryUrl: 'https://github.com/DOS/Rate', + authentication: { + type: 'none', + readOnly: true, + rateLimit: { + requestsPerMinute: MCP_RATE_LIMIT_MAX_REQUESTS, + inspectRequestsPerMinute: 30, + maxBodyBytes: MAX_MCP_BODY_BYTES, + maxItemsPerCall: MAX_MCP_RESULT_ITEMS, + }, + }, + citationPolicy: { + requireCanonicalCitationUrl: true, + requireFreshnessTimestamp: true, + canonicalOrigin: CANONICAL_RATE_ORIGIN, + }, + capabilities: { + tools: { + listChanged: false, + }, + }, + tools: MCP_TOOL_DEFINITIONS.map((tool) => ({ + name: tool.name, + title: tool.title, + description: tool.description, + readOnly: true, + })), + }; +} + +export function buildRateLlmsTxt(): string { + return [ + '# Rate.vn - Verified Tech Price Truth & 6-Axis Review Trust Platform', + '', + '> Rate.vn is an open-core Vietnamese consumer tech comparison and anti-fake-discount platform covering 22 retail platforms across 5 hardware categories (smartphones, tablets, laptops, smartwatches, earbuds), backed by standardized 10-group specifications, historical price medians, DOSafe scam risk intelligence, and the 6-axis Review Trust Model v2.', + '', + '## Model Context Protocol (MCP) Server', + '', + '- Endpoint (`POST` JSON-RPC 2.0, stateless Streamable HTTP): https://rate.vn/api/mcp', + '- Discovery Descriptor: https://rate.vn/.well-known/mcp.json', + '- Supported MCP Protocol Versions: `2025-06-18`, `2025-03-26`, `2024-11-05`', + '- Access & Limits: Public read-only, no API key required, `Content-Type: application/json`, body `<= 16384` bytes, up to `10` items per tool call, per-IP sliding-window rate limiting (`429` with `Retry-After`).', + '- Mandatory Citation Rule: Every tool item includes `canonical_citation_url` (`https://rate.vn/...`) and freshness timestamps (`observed_at` / `price_observed_at`). AI agents MUST link `canonical_citation_url` and state when the price was observed.', + '', + '### Read-Only MCP Tools (`POST /api/mcp`)', + '', + '1. `search_verified_catalog`: Search normalized devices across `smartphones`, `tablets`, `laptops`, `smartwatches`, and `earbuds` with brand, VND price floor/ceiling, and rating sort (`limit <= 10`). Excludes sold-out and implausibly low bait-price listings.', + '2. `get_22_store_offers_and_price_truth`: Fetch verified in-stock offers across all 22 Vietnamese retail platforms, historical floor/median price truth, Deal Radar fake-sale flags, Bayesian rating (`k = 3`, prior `4.2`), and 6-axis Review Trust Model v2 summary for a product slug (`limit <= 10`).', + '3. `compare_devices_by_use_case`: Compare 2 to 4 same-category product slugs side-by-side across 10-group hardware specs, verified floor prices, and 5-criterion JReviews scores (`screen`, `performance`, `camera`, `battery`, `value`) with optional persona or custom weight overrides.', + '4. `audit_listing_url`: Inspect a marketplace product URL across the 22 supported Vietnamese stores and return catalog match, 5-level fake-discount verdict, accessory gatekeeper status, and DOSafe + AI review seller risk scores.', + '5. `get_genuine_deals`: List verified below-median and cross-platform floor deals (`limit <= 10`, optional category/platform/budget filter) with fake strikethrough markups and high-risk sellers filtered out.', + '', + '## 22 Tracked Vietnamese Retail Platforms', + '', + '- Marketplaces: `shopee`, `lazada`, `tiki`, `tiktok`', + '- Authorized Tech & Electronics Chains: `cellphones`, `tgdd`, `dienmayxanh`, `topzone`, `fptshop`, `hoangha`, `didongviet`, `phongvu`, `gearvn`, `nguyenkim`, `shopdunk`, `hacom`, `clickbuy`, `viettelstore`, `pico`, `mediamart`, `memoryzone`, `anphatpc`', + '', + '## Methodology & Data Integrity', + '', + '- **5 Canonical Categories**: [Smartphones](https://rate.vn/smartphones), [Tablets](https://rate.vn/tablets), [Laptops](https://rate.vn/laptops), [Smartwatches](https://rate.vn/smartwatches), [Earbuds](https://rate.vn/earbuds)', + '- **10-Group Specification Schema (`specifications` JSON keys)**: `availability`, `design`, `display`, `hardware`, `battery`, `camera` (PhoneArena per-lens split), `connectivity`, `cellular`, `multimedia`, `regulatory`.', + '- **Price Truth & Anti-Fake-Sale Engine**: Compares live selling prices against recorded historical medians rather than seller-declared strikethrough prices; excludes sold-out/discontinued offers and implausibly low bait/accessory listings from market floors.', + '- **6-Axis Review Trust Model v2 & Bayesian Rating**: Evaluates `authenticity`, `independence`, `depth`, `reviewer`, `context`, and `community` axes to filter coin-farming spam, duplicate paid seeding, competitor sabotage, and review bombing (`weight = 0`), then computes helpfulness-weighted Bayesian ratings (`k = 3`, prior `4.2`) alongside DOSafe seller scam risk.', + '', + '## REST API v1 & Developer Documentation', + '', + '- [Developer Portal & Interactive Playground](https://rate.vn/developers): Live REST API v1 playground, 10-group schema docs, and MCP quick-connect snippets.', + '- [OpenAPI 3.1.0 Specification](https://rate.vn/api/v1/rate/openapi.json): Full machine-readable specification for `/api/v1/rate/*` endpoints (`/products`, `/products/{slug}`, `/compare`, `/versus`, `/deals`, `/inspect`, `/lookup`, `/leaderboard`, `/merchants`, `/stats`).', + '- [Deal Hub](https://rate.vn/deals): Cross-platform genuine deals and inflated list-price warnings.', + '- [URL & Fake-Discount Inspector](https://rate.vn/inspect): Verify any listing URL across the 22 supported Vietnamese stores.', + '- [Category Leaderboard](https://rate.vn/leaderboard): JReviews dual-rating rankings across all 5 tech categories.', + '- [Open-Core Source Repository](https://github.com/DOS/Rate): Public normalization, scoring, and API verification code.', + '', + ].join('\n'); +} diff --git a/packages/shared-data/src/__tests__/shared-data.test.ts b/packages/shared-data/src/__tests__/shared-data.test.ts index d16d7139..a0e0ab6b 100644 --- a/packages/shared-data/src/__tests__/shared-data.test.ts +++ b/packages/shared-data/src/__tests__/shared-data.test.ts @@ -3312,6 +3312,108 @@ function testReviewValue(): void { assert.equal(rules.reviewRatingWeight(1.4, imported.completeness), 1.4); } +function testRatingUseCasePresets(): void { + assert.deepEqual(rules.RATING_DEVICE_CATEGORIES, [ + 'smartphones', + 'tablets', + 'laptops', + 'smartwatches', + 'earbuds', + ]); + for (const id of rules.RATING_USE_CASE_PRESET_IDS) { + assert.equal(rules.isUseCasePresetId(id), true, id); + } + for (const bad of ['__proto__', 'constructor', 'toString', '', null, 42]) { + assert.equal(rules.isUseCasePresetId(bad), false, String(bad)); + } + + for (const slug of rules.RATING_DEVICE_CATEGORIES) { + const criteria = rules.getRatingCriteria(slug); + const validKeys = new Set(criteria.map((c) => c.key)); + const presets = rules.getRatingUseCasePresets(slug); + assert.ok(presets.length >= 5, `${slug} must define at least 5 presets`); + assert.equal(presets[0]?.id, 'default', `${slug} first preset is default`); + assert.equal( + new Set(presets.map((p) => p.id)).size, + presets.length, + `${slug} preset ids must be unique` + ); + + // Default preset matches getRatingCriteria weights exactly. + for (const c of criteria) { + assert.equal( + presets[0]!.weights[c.key], + c.weight, + `${slug}:default:${c.key} must match official criterion weight` + ); + } + + for (const preset of presets) { + for (const [loc, text] of Object.entries(preset.label)) { + assert.ok(text.trim(), `${slug}:${preset.id}:${loc} must be non-empty`); + assert.doesNotMatch( + text, + /[\u2013\u2014]/, + `${slug}:${preset.id}:${loc} must not contain en/em dashes` + ); + } + const entries = Object.entries(preset.weights); + assert.equal( + entries.length, + criteria.length, + `${slug}:${preset.id} must specify weights for all category criteria` + ); + let sum = 0; + for (const [key, w] of entries) { + assert.ok( + validKeys.has(key), + `${slug}:${preset.id} contains unknown criterion ${key}` + ); + assert.ok( + typeof w === 'number' && Number.isInteger(w) && w >= 0 && w <= 100, + `${slug}:${preset.id}:${key} weight must be integer 0..100` + ); + sum += w; + } + assert.equal(sum, 100, `${slug}:${preset.id} weights must sum to 100`); + } + } + + // Prototype and unknown category guards fall back to smartphones safely. + for (const fallbackSlug of [ + '__proto__', + 'constructor', + 'toString', + 'unknown-cat', + '', + null, + undefined, + ]) { + assert.deepEqual( + rules.getRatingUseCasePresets(fallbackSlug), + rules.getRatingUseCasePresets('smartphones'), + `fallback for ${String(fallbackSlug)}` + ); + } + assert.deepEqual( + rules.getRatingUseCasePresets(' LAPTOPS\u0000 '), + rules.getRatingUseCasePresets('laptops') + ); + const gamingPhone = rules.getRatingUseCasePresets('smartphones')[1]!; + assert.equal( + rules.getRatingUseCasePresetLabel(gamingPhone, 'vi'), + 'Cày game & pin trâu' + ); + assert.equal( + rules.getRatingUseCasePresetLabel(gamingPhone, 'en-US'), + 'Gaming & battery' + ); + assert.equal( + rules.getRatingUseCasePresetLabel(gamingPhone, 'cs-CZ'), + 'Hraní her a výdrž' + ); +} + function main(): void { console.log('🧪 Running @repo/shared-data unit tests...'); testVersionAndZeroStrapiExports(); @@ -3348,6 +3450,10 @@ function main(): void { console.log( ' ✅ [11/11] Rating criteria and review form rules (DOS/Rate#1542) verified' ); + testRatingUseCasePresets(); + console.log( + ' ✅ [12/15] RTINGS-style category use-case presets (DOS/Rate#1864) verified' + ); testProductPoints(); console.log(' ✅ [12/12] Product pros and cons (DOS/Rate#1546) verified'); testReviewDepth(); diff --git a/packages/shared-data/src/rules/rating-criteria.ts b/packages/shared-data/src/rules/rating-criteria.ts index a024965c..008fb2ef 100644 --- a/packages/shared-data/src/rules/rating-criteria.ts +++ b/packages/shared-data/src/rules/rating-criteria.ts @@ -448,3 +448,418 @@ export function mapLegacyCriteriaRatings( } return out; } + +const DEVICE_CATEGORIES = [ + 'smartphones', + 'tablets', + 'laptops', + 'smartwatches', + 'earbuds', +] as const; + +export type DeviceRatingCategorySlug = (typeof DEVICE_CATEGORIES)[number]; + +export const RATING_DEVICE_CATEGORIES: readonly DeviceRatingCategorySlug[] = + DEVICE_CATEGORIES; + +const USE_CASE_PRESET_IDS = [ + 'default', + 'gaming', + 'camera', + 'endurance', + 'value', + 'media', + 'study_work', + 'office', + 'creator', + 'fitness', + 'smart_daily', + 'audiophile', + 'commute_anc', + 'calls_work', +] as const; + +export type UseCasePresetId = (typeof USE_CASE_PRESET_IDS)[number]; + +export const RATING_USE_CASE_PRESET_IDS: readonly UseCasePresetId[] = + USE_CASE_PRESET_IDS; + +const KNOWN_USE_CASE_PRESET_ID_SET = new Set( + RATING_USE_CASE_PRESET_IDS +); + +export function isUseCasePresetId(key: unknown): key is UseCasePresetId { + const candidate = key; + return ( + typeof candidate === 'string' && KNOWN_USE_CASE_PRESET_ID_SET.has(candidate) + ); +} + +export interface RatingUseCasePreset { + readonly id: UseCasePresetId; + readonly label: { + readonly vi: string; + readonly en: string; + readonly cs: string; + }; + /** Share of each category criterion in percent; a preset's weights sum to 100. */ + readonly weights: Readonly>>; +} + +const p = ( + id: UseCasePresetId, + vi: string, + en: string, + cs: string, + weights: Readonly>> +): RatingUseCasePreset => ({ + id, + label: { vi, en, cs }, + weights, +}); + +function defaultPresetWeights( + categorySlug: string +): Readonly>> { + const out: Partial> = {}; + for (const criterion of getRatingCriteria(categorySlug)) { + out[criterion.key] = criterion.weight; + } + return out; +} + +const RATING_USE_CASE_PRESETS: Readonly< + Record +> = { + smartphones: [ + p( + 'default', + 'Cân bằng mặc định', + 'Balanced default', + 'Vyvážený výchozí', + defaultPresetWeights('smartphones') + ), + p( + 'gaming', + 'Cày game & pin trâu', + 'Gaming & battery', + 'Hraní her a výdrž', + { + performance: 40, + battery: 25, + display: 15, + value: 10, + camera: 5, + design: 5, + } + ), + p( + 'camera', + 'Nhiếp ảnh & quay vlog', + 'Camera & creator', + 'Fotoaparát a vlog', + { + camera: 45, + display: 20, + battery: 15, + performance: 10, + design: 5, + value: 5, + } + ), + p( + 'endurance', + 'Bền bỉ & thực dụng', + 'Endurance & durability', + 'Výdrž a odolnost', + { + battery: 35, + design: 25, + value: 20, + performance: 10, + display: 5, + camera: 5, + } + ), + p('value', 'Đáng tiền nhất (P/P)', 'Value-first', 'Nejlepší cena / výkon', { + value: 40, + performance: 20, + battery: 15, + display: 10, + camera: 10, + design: 5, + }), + ], + tablets: [ + p( + 'default', + 'Cân bằng mặc định', + 'Balanced default', + 'Vyvážený výchozí', + defaultPresetWeights('tablets') + ), + p( + 'media', + 'Xem phim & giải trí', + 'Media & entertainment', + 'Filmy a zábava', + { + display: 35, + sound: 25, + battery: 20, + performance: 5, + software: 5, + design: 5, + value: 5, + } + ), + p( + 'study_work', + 'Học tập & ghi chú', + 'Study & productivity', + 'Studium a poznámky', + { + software: 25, + display: 20, + battery: 20, + performance: 15, + design: 10, + sound: 5, + value: 5, + } + ), + p( + 'gaming', + 'Chơi game & đa nhiệm', + 'Gaming & multitasking', + 'Hraní her a výkon', + { + performance: 40, + display: 25, + battery: 15, + sound: 5, + software: 5, + design: 5, + value: 5, + } + ), + p('value', 'Đáng tiền nhất (P/P)', 'Value-first', 'Nejlepší cena / výkon', { + value: 40, + display: 15, + performance: 15, + battery: 15, + sound: 5, + software: 5, + design: 5, + }), + ], + laptops: [ + p( + 'default', + 'Cân bằng mặc định', + 'Balanced default', + 'Vyvážený výchozí', + defaultPresetWeights('laptops') + ), + p( + 'office', + 'Văn phòng & di động', + 'Office & portability', + 'Kancelář a mobilita', + { + battery: 30, + keyboard: 20, + design: 20, + display: 10, + performance: 10, + thermals: 5, + value: 5, + } + ), + p( + 'creator', + 'Lập trình & đồ họa nặng', + 'Coding & creator', + 'Programování a grafika', + { + performance: 35, + display: 25, + thermals: 15, + keyboard: 10, + battery: 5, + design: 5, + value: 5, + } + ), + p( + 'gaming', + 'Gaming & tản nhiệt', + 'Gaming & thermals', + 'Hraní her a chlazení', + { + performance: 40, + thermals: 25, + display: 15, + keyboard: 5, + battery: 5, + design: 5, + value: 5, + } + ), + p('value', 'Đáng tiền nhất (P/P)', 'Value-first', 'Nejlepší cena / výkon', { + value: 40, + performance: 20, + battery: 15, + display: 10, + keyboard: 5, + thermals: 5, + design: 5, + }), + ], + smartwatches: [ + p( + 'default', + 'Cân bằng mặc định', + 'Balanced default', + 'Vyvážený výchozí', + defaultPresetWeights('smartwatches') + ), + p('fitness', 'Thể thao & sức khỏe', 'Fitness & health', 'Sport a zdraví', { + health: 45, + battery: 25, + design: 10, + display: 10, + apps: 5, + value: 5, + }), + p( + 'endurance', + 'Pin dài ngày & đi phượt', + 'Multi-day endurance', + 'Vícedenní výdrž', + { + battery: 45, + design: 20, + health: 15, + display: 10, + apps: 5, + value: 5, + } + ), + p( + 'smart_daily', + 'Đeo hằng ngày & tiện ích', + 'Smart apps & daily wear', + 'Chytré funkce a nošení', + { + apps: 30, + design: 25, + display: 20, + health: 10, + battery: 10, + value: 5, + } + ), + p('value', 'Đáng tiền nhất (P/P)', 'Value-first', 'Nejlepší cena / výkon', { + value: 40, + health: 20, + battery: 15, + design: 10, + apps: 10, + display: 5, + }), + ], + earbuds: [ + p( + 'default', + 'Cân bằng mặc định', + 'Balanced default', + 'Vyvážený výchozí', + defaultPresetWeights('earbuds') + ), + p( + 'audiophile', + 'Nghe nhạc chuyên sâu', + 'Audiophile sound', + 'Audiofilský poslech', + { + sound: 50, + comfort: 20, + anc: 10, + battery: 10, + calls: 5, + value: 5, + } + ), + p( + 'commute_anc', + 'Đi làm & chống ồn ANC', + 'ANC & commute', + 'Cestování a ANC', + { + anc: 40, + comfort: 25, + battery: 15, + sound: 10, + calls: 5, + value: 5, + } + ), + p( + 'calls_work', + 'Họp online & đàm thoại', + 'Meetings & calls', + 'Schůzky a hovory', + { + calls: 40, + comfort: 25, + battery: 15, + anc: 10, + sound: 5, + value: 5, + } + ), + p('value', 'Đáng tiền nhất (P/P)', 'Value-first', 'Nejlepší cena / výkon', { + value: 40, + sound: 25, + battery: 15, + anc: 10, + comfort: 5, + calls: 5, + }), + ], + services: [ + p( + 'default', + 'Cân bằng mặc định', + 'Balanced default', + 'Vyvážený výchozí', + defaultPresetWeights('services') + ), + ], +}; + +/** + * Curated RTINGS-style use-case presets for a category (DOS/Rate#1864). + * Unknown or null categories fall back to `smartphones`, matching `getRatingCriteria`. + */ +export function getRatingUseCasePresets( + categorySlug: string | null | undefined +): readonly RatingUseCasePreset[] { + const raw = categorySlug; + const normalized = + typeof raw === 'string' + ? raw.replace(LOCALE_CONTROL_CHARS_RE, '').trim().toLowerCase() + : ''; + return ( + ownValue(RATING_USE_CASE_PRESETS, normalized) ?? + RATING_USE_CASE_PRESETS.smartphones! + ); +} + +export function getRatingUseCasePresetLabel( + preset: Pick, + locale: string | null | undefined +): string { + return getRatingCriterionLabel(preset, locale); +}