From b36a93ea9e4c5cf9aac38c1372554eac8c6aced5 Mon Sep 17 00:00:00 2001 From: JOY <5027251+JOY@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:42:26 +0700 Subject: [PATCH 1/3] feat(shared): add 12 Wave 1-3 retail platforms across monorepo --- apps/extension/CHROMEWEBSTORE.md | 20 +- apps/extension/manifest.json | 42 +- apps/extension/src/_locales/cs/messages.json | 14 +- apps/extension/src/_locales/en/messages.json | 14 +- apps/extension/src/_locales/vi/messages.json | 14 +- .../src/background/service-worker.ts | 86 +- .../src/extractors/ecommerce-detector.ts | 319 +++++++- apps/extension/src/security-guards.ts | 12 + apps/extension/src/test-extension-pipeline.ts | 762 +++++++++++++++++- apps/extension/src/types.ts | 14 +- .../__tests__/shopee-to-supabase.test.ts | 129 +++ apps/importer/src/shopee/types.ts | 14 +- apps/web/e2e/deals-copy.spec.ts | 6 +- apps/web/locales/cs.json | 60 +- apps/web/locales/en.json | 60 +- apps/web/locales/vi.json | 60 +- apps/web/src/app/api/v1/rate/deals/route.ts | 14 +- .../app/api/v1/rate/extension/ingest/route.ts | 12 + .../app/api/v1/rate/extension/lookup/route.ts | 2 +- .../components/deals/DealFinderWorkspace.tsx | 2 +- .../components/home/HeroSearchInspector.tsx | 4 +- .../merchants/MerchantDirectoryExplorer.tsx | 12 + .../watchlist/WatchlistWorkspace.tsx | 21 +- apps/web/src/lib/rate-api.ts | 53 ++ apps/web/src/lib/rate-domain-core.ts | 393 +++++++-- .../__tests__/core-rate-architecture.test.ts | 222 ++++- apps/web/src/server/rate/api-handler.ts | 14 +- apps/web/src/server/rate/extension.ts | 242 +++++- apps/web/src/server/rate/openapi.ts | 6 +- .../src/__tests__/shared-data.test.ts | 28 +- .../src/rules/extension-observation.ts | 7 + .../shared-data/src/schemas/specs.schema.ts | 16 + 32 files changed, 2362 insertions(+), 312 deletions(-) diff --git a/apps/extension/CHROMEWEBSTORE.md b/apps/extension/CHROMEWEBSTORE.md index 22eac9290..b4eb50c53 100644 --- a/apps/extension/CHROMEWEBSTORE.md +++ b/apps/extension/CHROMEWEBSTORE.md @@ -1,6 +1,6 @@ # Chrome Web Store Listing & Compliance - Rate.vn Browser Extension (MV3) -- **Last Updated:** 2026-11-19 +- **Last Updated:** 2026-11-22 - **Current Version:** 2.0.0 - **Category:** Shopping @@ -14,11 +14,11 @@ Rate.vn - So Sánh Giá, Lịch Sử Giá & Lọc Đánh Giá Ảo AI ### Short Summary (<= 132 characters) -Xem lịch sử giá 90 ngày, phát hiện giảm giá ảo, tìm nơi bán rẻ hơn, lọc đánh giá ảo bằng AI trên 10 sàn và chuỗi bán lẻ Việt Nam. +Xem lịch sử giá 90 ngày, phát hiện giảm giá ảo, tìm nơi bán rẻ hơn, lọc đánh giá ảo bằng AI trên 22 sàn và chuỗi bán lẻ Việt Nam. ### Detailed Description -Rate.vn giúp người tiêu dùng mua sắm đồ công nghệ minh bạch và tiết kiệm hơn ngay khi đang xem sản phẩm trên Shopee, Lazada, Tiki, TikTok Shop, CellphoneS, Thế Giới Di Động, FPT Shop, Hoàng Hà Mobile, Di Động Việt và Phong Vũ: +Rate.vn giúp người tiêu dùng mua sắm đồ công nghệ minh bạch và tiết kiệm hơn ngay khi đang xem sản phẩm trên Shopee, Lazada, Tiki, TikTok Shop, CellphoneS, Thế Giới Di Động, Điện Máy Xanh, TopZone, FPT Shop, Hoàng Hà Mobile, Di Động Việt, Phong Vũ, GearVN, Nguyễn Kim, ShopDunk, HACOM, Clickbuy, Viettel Store, Pico, MediaMart, MemoryZone và An Phát Computer: - Phát hiện Giảm Giá Ảo: Tự động đối chiếu mức giá hiện tại và mức giá gạch ngang với lịch sử giá đã xác minh để nhận diện khuyến mãi thật hay nâng giá gốc rồi giảm ảo. - So Sánh Giá Đa Sàn Tức Thì: Hiển thị ngay các gian hàng chính hãng khác đang bán cùng mẫu điện thoại, máy tính bảng, laptop với mức giá thấp hơn. @@ -32,18 +32,18 @@ Rate.vn giúp người tiêu dùng mua sắm đồ công nghệ minh bạch và This table lists exactly what `manifest.json` requests; `test-extension-pipeline.ts` fails when the two disagree (DOS/Rate#1231). -| Permission / Host Permission | Plain-English Justification | -| :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `storage` | Saves the user's preferred Rate.vn server endpoint, a temporary product lookup cache for the active session, and the user's explicit opt-in preference for contributing product price signals. | -| `sidePanel` | Displays the price history chart, cross-merchant price comparison table and AI review authenticity breakdown beside the shopping page when the user clicks the extension badge or floating pill. | -| `https://shopee.vn/*`, `https://*.lazada.vn/*`, `https://tiki.vn/*`, `https://www.tiktok.com/*`, `https://shop.tiktok.com/*`, `https://cellphones.com.vn/*`, `https://thegioididong.com/*`, `https://*.thegioididong.com/*`, `https://topzone.vn/*`, `https://*.topzone.vn/*`, `https://dienmayxanh.com/*`, `https://*.dienmayxanh.com/*`, `https://fptshop.com.vn/*`, `https://hoanghamobile.com/*`, `https://didongviet.vn/*`, `https://phongvu.vn/*` | Runs the content script on the 10 supported Vietnamese stores (including Thế Giới Di Động's sister storefronts `topzone.vn` and `dienmayxanh.com`). It reads the public product title, selected variant, listed price, original price and rating of a product page to show the floating price-check badge. The script loads on every page of these sites because they navigate in-page, but it reads and sends nothing on pages it does not recognise as a product page. On `www.tiktok.com` it loads only on product page paths (`/view/product/`, `/@shop/product/`, `/shop/.../pdp/`), not on the video feed or video pages (DOS/Rate#1601). A product page reached by in-page navigation from the feed gets the badge after a reload; `shop.tiktok.com` serves only shop pages (DOS/Rate#1232). | -| `https://rate.vn/*`, `https://www.rate.vn/*` | Fetches verified price history, cross-merchant offers and review authenticity scores from the Rate.vn API, and sends the opt-in crowd signal. | +| Permission / Host Permission | Plain-English Justification | +| :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `storage` | Saves the user's preferred Rate.vn server endpoint, a temporary product lookup cache for the active session, and the user's explicit opt-in preference for contributing product price signals. | +| `sidePanel` | Displays the price history chart, cross-merchant price comparison table and AI review authenticity breakdown beside the shopping page when the user clicks the extension badge or floating pill. | +| `https://shopee.vn/*`, `https://*.lazada.vn/*`, `https://tiki.vn/*`, `https://www.tiktok.com/*`, `https://shop.tiktok.com/*`, `https://cellphones.com.vn/*`, `https://thegioididong.com/*`, `https://*.thegioididong.com/*`, `https://topzone.vn/*`, `https://*.topzone.vn/*`, `https://dienmayxanh.com/*`, `https://*.dienmayxanh.com/*`, `https://fptshop.com.vn/*`, `https://hoanghamobile.com/*`, `https://didongviet.vn/*`, `https://phongvu.vn/*`, `https://gearvn.com/*`, `https://*.gearvn.com/*`, `https://nguyenkim.com/*`, `https://*.nguyenkim.com/*`, `https://shopdunk.com/*`, `https://*.shopdunk.com/*`, `https://hacom.vn/*`, `https://*.hacom.vn/*`, `https://clickbuy.com.vn/*`, `https://*.clickbuy.com.vn/*`, `https://viettelstore.vn/*`, `https://*.viettelstore.vn/*`, `https://pico.vn/*`, `https://*.pico.vn/*`, `https://mediamart.vn/*`, `https://*.mediamart.vn/*`, `https://memoryzone.com.vn/*`, `https://*.memoryzone.com.vn/*`, `https://anphatpc.com.vn/*`, `https://*.anphatpc.com.vn/*` | Runs the content script on the 22 supported Vietnamese stores. It reads the public product title, selected variant, listed price, original price and rating of a product page to show the floating price-check badge. The script loads on every page of these sites because they navigate in-page, but it reads and sends nothing on pages it does not recognise as a product page. On `www.tiktok.com` it loads only on product page paths (`/view/product/`, `/@shop/product/`, `/shop/.../pdp/`), not on the video feed or video pages (DOS/Rate#1601). A product page reached by in-page navigation from the feed gets the badge after a reload; `shop.tiktok.com` serves only shop pages (DOS/Rate#1232). | +| `https://rate.vn/*`, `https://www.rate.vn/*` | Fetches verified price history, cross-merchant offers and review authenticity scores from the Rate.vn API, and sends the opt-in crowd signal. | --- ## 3. Privacy & User Data Disclosure -1. **Where it runs:** the content script loads on the 10 supported stores listed above (`shopee.vn`, `lazada.vn`, `tiki.vn`, TikTok Shop product pages on `www.tiktok.com` and `shop.tiktok.com`, `cellphones.com.vn`, `thegioididong.com` and its sister storefronts `topzone.vn` and `dienmayxanh.com`, `fptshop.com.vn`, `hoanghamobile.com`, `didongviet.vn`, `phongvu.vn`). It acts only on pages it recognises as a product page. The extension itself never opens or fetches pages the user did not open, never works around a store's bot checks and never solves captchas. +1. **Where it runs:** the content script loads on the 22 supported stores listed above (`shopee.vn`, `lazada.vn`, `tiki.vn`, TikTok Shop product pages on `www.tiktok.com` and `shop.tiktok.com`, `cellphones.com.vn`, `thegioididong.com`, `topzone.vn`, `dienmayxanh.com`, `fptshop.com.vn`, `hoanghamobile.com`, `didongviet.vn`, `phongvu.vn`, `gearvn.com`, `nguyenkim.com`, `shopdunk.com`, `hacom.vn`, `clickbuy.com.vn`, `viettelstore.vn`, `pico.vn`, `mediamart.vn`, `memoryzone.com.vn`, `anphatpc.com.vn`). It acts only on pages it recognises as a product page. The extension itself never opens or fetches pages the user did not open, never works around a store's bot checks and never solves captchas. 2. **Lookup (on by default, no opt-in):** on a recognised product page the extension sends `GET /api/v1/rate/extension/lookup` with the store, the product URL with query parameters and tracking tokens (`utm_*`, `sp_atk`, `xptdk`, `fbclid`, `gclid`) stripped locally, the product title, the store's item id and shop id, the selected variant, the listed price and the original price. The request is read-only and carries no account, name, email or cookies. 3. **Opt-in observation (off by default):** only when the user chooses "Có" / "Yes" on the consent page opened once at first install, or turns on "Đóng góp phát hiện sản phẩm mới (chỉ khi bạn bật)" (English: "Help find new products (only when you turn it on)") in the Side Panel, the extension sends an ExtensionObservation v1 to `POST /api/v1/rate/extension/observation`: the store, the cleaned URL (no query), the item and shop ids, the variant id (SKU), the selected variant, the price, the original price, the stock status and quantity, the time the user saw the price and the extension version, with how the page was read (DOS/Rate#1606). It carries a random submitter id for the install, obtained once from `POST /api/v1/rate/extension/submitter`. No title, no ratings, no account data. The toggle's label and the consent page list these same fields; a test ties them to the payload. Observations go to a quarantine, stored with the time received and a salted hash of the network range (never the IP) to tell independent senders apart; the hash is deleted after 28 days and observations after 180 days. Rate.vn's servers may re-check the listing on the store. They never change public prices directly. Turning the opt-in off calls `DELETE /api/v1/rate/extension/submitter`, which deletes the id and every observation sent with it; the extension keeps retrying that erasure until the server confirms it. Uninstalling without turning it off leaves the observations to the 180-day purge. An opt-in given to the older crowd signal is not taken as consent to this: after the update it is off and the consent page asks again. Closing the consent page keeps the opt-in off, and updates or reloads do not open it again (DOS/Rate#1603). 4. **Stored in the browser only:** the server address, the opt-in choice and, while the user contributes, the submitter id (`chrome.storage.local`), and a session-only cache of the products viewed in each tab, the latest side panel search, their lookup results and a lookup wait time after a rate limit (`chrome.storage.session`). diff --git a/apps/extension/manifest.json b/apps/extension/manifest.json index 788ff6ab1..1ea7e241a 100644 --- a/apps/extension/manifest.json +++ b/apps/extension/manifest.json @@ -43,6 +43,26 @@ "https://hoanghamobile.com/*", "https://didongviet.vn/*", "https://phongvu.vn/*", + "https://gearvn.com/*", + "https://*.gearvn.com/*", + "https://nguyenkim.com/*", + "https://*.nguyenkim.com/*", + "https://shopdunk.com/*", + "https://*.shopdunk.com/*", + "https://hacom.vn/*", + "https://*.hacom.vn/*", + "https://clickbuy.com.vn/*", + "https://*.clickbuy.com.vn/*", + "https://viettelstore.vn/*", + "https://*.viettelstore.vn/*", + "https://pico.vn/*", + "https://*.pico.vn/*", + "https://mediamart.vn/*", + "https://*.mediamart.vn/*", + "https://memoryzone.com.vn/*", + "https://*.memoryzone.com.vn/*", + "https://anphatpc.com.vn/*", + "https://*.anphatpc.com.vn/*", "https://rate.vn/*", "https://www.rate.vn/*" ], @@ -66,7 +86,27 @@ "https://fptshop.com.vn/*", "https://hoanghamobile.com/*", "https://didongviet.vn/*", - "https://phongvu.vn/*" + "https://phongvu.vn/*", + "https://gearvn.com/*", + "https://*.gearvn.com/*", + "https://nguyenkim.com/*", + "https://*.nguyenkim.com/*", + "https://shopdunk.com/*", + "https://*.shopdunk.com/*", + "https://hacom.vn/*", + "https://*.hacom.vn/*", + "https://clickbuy.com.vn/*", + "https://*.clickbuy.com.vn/*", + "https://viettelstore.vn/*", + "https://*.viettelstore.vn/*", + "https://pico.vn/*", + "https://*.pico.vn/*", + "https://mediamart.vn/*", + "https://*.mediamart.vn/*", + "https://memoryzone.com.vn/*", + "https://*.memoryzone.com.vn/*", + "https://anphatpc.com.vn/*", + "https://*.anphatpc.com.vn/*" ], "exclude_matches": ["https://www.tiktok.com/@*/video/*"], "js": ["content/content-script.js"], diff --git a/apps/extension/src/_locales/cs/messages.json b/apps/extension/src/_locales/cs/messages.json index 4500f7aec..67767eb1e 100644 --- a/apps/extension/src/_locales/cs/messages.json +++ b/apps/extension/src/_locales/cs/messages.json @@ -3,7 +3,7 @@ "message": "Rate.vn - Porovnání cen, historie cen a AI filtr falešných recenzí" }, "extDescription": { - "message": "Historie cen za 90 dní, odhalení falešných slev, levnější prodejci a AI filtr falešných recenzí v 10 vietnamských obchodech." + "message": "Historie cen za 90 dní, odhalení falešných slev, levnější prodejci a AI filtr falešných recenzí ve 22 vietnamských obchodech." }, "actionTitle": { "message": "Otevřít panel cen a důvěryhodnosti Rate.vn" @@ -276,7 +276,7 @@ "message": "Body historie cen se stále sbírají." }, "radarDealsTitle": { - "message": "Skutečné slevy pod mediánem (10 obchodů)" + "message": "Skutečné slevy pod mediánem (22 obchodů)" }, "radarSavings": { "message": "Ušetříte $AMOUNT$ (-$PCT$ %)", @@ -335,7 +335,7 @@ "message": "nedostatek dat" }, "merchantDirTitle": { - "message": "Důvěryhodnost prodejců v 10 obchodech ($COUNT$)", + "message": "Důvěryhodnost prodejců ve 22 obchodech ($COUNT$)", "placeholders": { "count": { "content": "$1" @@ -398,10 +398,10 @@ } }, "noProductStores": { - "message": "Shopee, Lazada, Tiki, TikTok Shop, CellphoneS, Thế Giới Di Động, FPT Shop, Hoàng Hà Mobile, Di Động Việt" + "message": "Shopee, Lazada, Tiki, TikTok Shop, CellphoneS, Thế Giới Di Động, Điện Máy Xanh, TopZone, FPT Shop, Hoàng Hà Mobile, Di Động Việt, Phong Vũ, GearVN, Nguyễn Kim, ShopDunk, HACOM, Clickbuy, Viettel Store, Pico, MediaMart, MemoryZone" }, "noProductLastStore": { - "message": "Phong Vũ" + "message": "An Phát Computer" }, "variantPickerTitle": { "message": "Zvolte prohlíženou variantu úložiště" @@ -514,7 +514,7 @@ } }, "radarPillSpread": { - "message": "Rozdíl v 10 obchodech $PCT$ %", + "message": "Rozdíl ve 22 obchodech $PCT$ %", "placeholders": { "pct": { "content": "$1" @@ -673,7 +673,7 @@ "message": "Rate.vn je připraveno" }, "onboardingLookup": { - "message": "Na stránkách produktů 10 podporovaných obchodů rozšíření posílá Rate.vn obchod, URL bez parametrů, název, ID produktu a obchodu, variantu, cenu a původní cenu, aby vyhledalo historii cen. Účet není potřeba." + "message": "Na stránkách produktů 22 podporovaných obchodů rozšíření posílá Rate.vn obchod, URL bez parametrů, název, ID produktu a obchodu, variantu, cenu a původní cenu, aby vyhledalo historii cen. Účet není potřeba." }, "onboardingQuestion": { "message": "Chcete přispívat nabídkami, které si prohlížíte?" diff --git a/apps/extension/src/_locales/en/messages.json b/apps/extension/src/_locales/en/messages.json index 6331dae3e..48b43c973 100644 --- a/apps/extension/src/_locales/en/messages.json +++ b/apps/extension/src/_locales/en/messages.json @@ -3,7 +3,7 @@ "message": "Rate.vn - Price Comparison, Price History & AI Fake Review Filter" }, "extDescription": { - "message": "Check 90-day price history, spot fake discounts, find cheaper sellers and filter fake reviews with AI on 10 Vietnamese stores." + "message": "Check 90-day price history, spot fake discounts, find cheaper sellers and filter fake reviews with AI on 22 Vietnamese stores." }, "actionTitle": { "message": "Open the Rate.vn price and trust panel" @@ -276,7 +276,7 @@ "message": "Still collecting price history points." }, "radarDealsTitle": { - "message": "Genuine deals below the median (10 stores)" + "message": "Genuine deals below the median (22 stores)" }, "radarSavings": { "message": "Save $AMOUNT$ (-$PCT$%)", @@ -335,7 +335,7 @@ "message": "not enough data" }, "merchantDirTitle": { - "message": "Seller trust across 10 stores ($COUNT$)", + "message": "Seller trust across 22 stores ($COUNT$)", "placeholders": { "count": { "content": "$1" @@ -398,10 +398,10 @@ } }, "noProductStores": { - "message": "Shopee, Lazada, Tiki, TikTok Shop, CellphoneS, Thế Giới Di Động, FPT Shop, Hoàng Hà Mobile, Di Động Việt" + "message": "Shopee, Lazada, Tiki, TikTok Shop, CellphoneS, Thế Giới Di Động, Điện Máy Xanh, TopZone, FPT Shop, Hoàng Hà Mobile, Di Động Việt, Phong Vũ, GearVN, Nguyễn Kim, ShopDunk, HACOM, Clickbuy, Viettel Store, Pico, MediaMart, MemoryZone" }, "noProductLastStore": { - "message": "Phong Vũ" + "message": "An Phát Computer" }, "variantPickerTitle": { "message": "Choose the Storage Variant You Are Viewing" @@ -514,7 +514,7 @@ } }, "radarPillSpread": { - "message": "10-store gap $PCT$%", + "message": "22-store gap $PCT$%", "placeholders": { "pct": { "content": "$1" @@ -673,7 +673,7 @@ "message": "Rate.vn is ready" }, "onboardingLookup": { - "message": "On product pages of the 10 supported stores, the extension sends Rate.vn the store, the URL without parameters, the title, the item and shop ids, the variant, the price and the original price to look up price history. No account needed." + "message": "On product pages of the 22 supported stores, the extension sends Rate.vn the store, the URL without parameters, the title, the item and shop ids, the variant, the price and the original price to look up price history. No account needed." }, "onboardingQuestion": { "message": "Would you like to contribute the listings you view?" diff --git a/apps/extension/src/_locales/vi/messages.json b/apps/extension/src/_locales/vi/messages.json index 423ff3266..c10479e47 100644 --- a/apps/extension/src/_locales/vi/messages.json +++ b/apps/extension/src/_locales/vi/messages.json @@ -3,7 +3,7 @@ "message": "Rate.vn - So Sánh Giá, Lịch Sử Giá & Lọc Đánh Giá Ảo AI" }, "extDescription": { - "message": "Xem lịch sử giá 90 ngày, phát hiện giảm giá ảo, tìm nơi bán rẻ hơn, lọc đánh giá ảo bằng AI trên 10 sàn và chuỗi bán lẻ Việt Nam." + "message": "Xem lịch sử giá 90 ngày, phát hiện giảm giá ảo, tìm nơi bán rẻ hơn, lọc đánh giá ảo bằng AI trên 22 sàn và chuỗi bán lẻ Việt Nam." }, "actionTitle": { "message": "Mở bảng phân tích giá & độ tin cậy Rate.vn" @@ -276,7 +276,7 @@ "message": "Đang tích lũy thêm các mốc thời gian lịch sử giá." }, "radarDealsTitle": { - "message": "Deal thật dưới giá trung vị (10 sàn)" + "message": "Deal thật dưới giá trung vị (22 sàn)" }, "radarSavings": { "message": "Tiết kiệm $AMOUNT$ (-$PCT$%)", @@ -335,7 +335,7 @@ "message": "chưa đủ dữ liệu" }, "merchantDirTitle": { - "message": "Độ tin cậy gian hàng trên 10 sàn ($COUNT$)", + "message": "Độ tin cậy gian hàng trên 22 sàn ($COUNT$)", "placeholders": { "count": { "content": "$1" @@ -398,10 +398,10 @@ } }, "noProductStores": { - "message": "Shopee, Lazada, Tiki, TikTok Shop, CellphoneS, Thế Giới Di Động, FPT Shop, Hoàng Hà Mobile, Di Động Việt" + "message": "Shopee, Lazada, Tiki, TikTok Shop, CellphoneS, Thế Giới Di Động, Điện Máy Xanh, TopZone, FPT Shop, Hoàng Hà Mobile, Di Động Việt, Phong Vũ, GearVN, Nguyễn Kim, ShopDunk, HACOM, Clickbuy, Viettel Store, Pico, MediaMart, MemoryZone" }, "noProductLastStore": { - "message": "Phong Vũ" + "message": "An Phát Computer" }, "variantPickerTitle": { "message": "Chọn Phiên Bản Bộ Nhớ Đang Xem" @@ -514,7 +514,7 @@ } }, "radarPillSpread": { - "message": "Lệch 10 sàn $PCT$%", + "message": "Lệch 22 sàn $PCT$%", "placeholders": { "pct": { "content": "$1" @@ -673,7 +673,7 @@ "message": "Rate.vn đã sẵn sàng" }, "onboardingLookup": { - "message": "Trên trang sản phẩm của 10 sàn được hỗ trợ, tiện ích gửi cho Rate.vn sàn, URL đã bỏ tham số, tên, mã sản phẩm và mã gian hàng, phiên bản, giá bán và giá gốc để tra lịch sử giá. Không cần tài khoản." + "message": "Trên trang sản phẩm của 22 sàn được hỗ trợ, tiện ích gửi cho Rate.vn sàn, URL đã bỏ tham số, tên, mã sản phẩm và mã gian hàng, phiên bản, giá bán và giá gốc để tra lịch sử giá. Không cần tài khoản." }, "onboardingQuestion": { "message": "Bạn có muốn đóng góp các tin bán bạn xem không?" diff --git a/apps/extension/src/background/service-worker.ts b/apps/extension/src/background/service-worker.ts index 029c94ecb..efa228357 100644 --- a/apps/extension/src/background/service-worker.ts +++ b/apps/extension/src/background/service-worker.ts @@ -1,8 +1,5 @@ import { RATE_API_V1_ENDPOINTS } from '@repo/shared-data'; -import { - EXTENSION_MARKETPLACES, - isExtensionMarketplaceHost, -} from '@repo/shared-data/rules'; +import { EXTENSION_MARKETPLACES } from '@repo/shared-data/rules'; import type { ExtensionLookupData, ExtensionSettings, @@ -153,18 +150,12 @@ async function fetchExtensionLookup( ); } -const SUPPORTED_CROWD_PLATFORMS = new Set([ - 'shopee', - 'lazada', - 'tiki', - 'tiktok', - 'cellphones', - 'tgdd', - 'fptshop', - 'hoangha', - 'didongviet', - 'phongvu', -]); +// Opt-in ExtensionObservation v1 quarantine remains restricted to the 10 +// SQL-checked marketplaces (`EXTENSION_MARKETPLACES`) until a coordinated +// `DOS-Me` PostgreSQL migration widens `rate.extension_observations` (#1850). +const SUPPORTED_CROWD_PLATFORMS: ReadonlySet = new Set( + EXTENSION_MARKETPLACES +); const QUICK_QUERY_BARE_MARKETPLACE_DOMAINS = [ 'shopee.vn', @@ -179,6 +170,16 @@ const QUICK_QUERY_BARE_MARKETPLACE_DOMAINS = [ 'hoanghamobile.com', 'didongviet.vn', 'phongvu.vn', + 'gearvn.com', + 'nguyenkim.com', + 'shopdunk.com', + 'hacom.vn', + 'clickbuy.com.vn', + 'viettelstore.vn', + 'pico.vn', + 'mediamart.vn', + 'memoryzone.com.vn', + 'anphatpc.com.vn', ] as const; function normalizeQuickQueryBareMarketplaceUrl( @@ -231,6 +232,53 @@ interface VerifiedMarketplaceUrl { origin: string; } +/** + * Exact store hosts permitted by `manifest.json` `host_permissions` across all + * 22 supported Vietnamese stores. A leading `.` allows valid `[a-z0-9-]+` + * subdomains as well as the bare base domain. + */ +const ALLOWED_EXTENSION_STORE_HOSTS: Readonly< + Record +> = { + shopee: ['shopee.vn'], + lazada: ['lazada.vn', '.lazada.vn'], + tiki: ['tiki.vn'], + tiktok: ['www.tiktok.com', 'shop.tiktok.com'], + cellphones: ['cellphones.com.vn'], + tgdd: ['thegioididong.com', '.thegioididong.com'], + dienmayxanh: ['dienmayxanh.com', '.dienmayxanh.com'], + topzone: ['topzone.vn', '.topzone.vn'], + fptshop: ['fptshop.com.vn'], + hoangha: ['hoanghamobile.com'], + didongviet: ['didongviet.vn'], + phongvu: ['phongvu.vn'], + gearvn: ['gearvn.com', '.gearvn.com'], + nguyenkim: ['nguyenkim.com', '.nguyenkim.com'], + shopdunk: ['shopdunk.com', '.shopdunk.com'], + hacom: ['hacom.vn', '.hacom.vn'], + clickbuy: ['clickbuy.com.vn', '.clickbuy.com.vn'], + viettelstore: ['viettelstore.vn', '.viettelstore.vn'], + pico: ['pico.vn', '.pico.vn'], + mediamart: ['mediamart.vn', '.mediamart.vn'], + memoryzone: ['memoryzone.com.vn', '.memoryzone.com.vn'], + anphatpc: ['anphatpc.com.vn', '.anphatpc.com.vn'], +}; + +function isAllowedExtensionStoreHost( + platform: SupportedEcommercePlatform, + host: string +): boolean { + const h = host.toLowerCase(); + return ALLOWED_EXTENSION_STORE_HOSTS[platform].some((allowed) => { + if (!allowed.startsWith('.')) return h === allowed; + if (h === allowed.slice(1)) return true; + if (!h.endsWith(allowed)) return false; + return /^(?:[a-z0-9-]+\.)+$/.test( + h.slice(0, h.length - allowed.length + 1) + ); + }); +} + function resolvePositiveIntId(value: unknown): number | undefined { return typeof value === 'number' && Number.isInteger(value) && value > 0 ? value @@ -264,8 +312,10 @@ function resolveMarketplaceFromHttpsUrl( ) { return null; } - for (const marketplace of EXTENSION_MARKETPLACES) { - if (isExtensionMarketplaceHost(marketplace, host)) { + for (const marketplace of Object.keys( + ALLOWED_EXTENSION_STORE_HOSTS + ) as SupportedEcommercePlatform[]) { + if (isAllowedExtensionStoreHost(marketplace, host)) { return { marketplace, origin: parsed.origin.toLowerCase() }; } } diff --git a/apps/extension/src/extractors/ecommerce-detector.ts b/apps/extension/src/extractors/ecommerce-detector.ts index fc06bf6c1..6ac5514d5 100644 --- a/apps/extension/src/extractors/ecommerce-detector.ts +++ b/apps/extension/src/extractors/ecommerce-detector.ts @@ -77,64 +77,186 @@ export function detectEcommercePlatform( if (isDomainOrSubdomain(host, 'tiki.vn')) return 'tiki'; if (isDomainOrSubdomain(host, 'tiktok.com')) return 'tiktok'; if (isDomainOrSubdomain(host, 'cellphones.com.vn')) return 'cellphones'; - if ( - isDomainOrSubdomain(host, 'thegioididong.com') || - isDomainOrSubdomain(host, 'topzone.vn') || - isDomainOrSubdomain(host, 'dienmayxanh.com') - ) { - return 'tgdd'; - } + if (isDomainOrSubdomain(host, 'thegioididong.com')) return 'tgdd'; + if (isDomainOrSubdomain(host, 'dienmayxanh.com')) return 'dienmayxanh'; + if (isDomainOrSubdomain(host, 'topzone.vn')) return 'topzone'; if (isDomainOrSubdomain(host, 'fptshop.com.vn')) return 'fptshop'; if (isDomainOrSubdomain(host, 'hoanghamobile.com')) return 'hoangha'; if (isDomainOrSubdomain(host, 'didongviet.vn')) return 'didongviet'; if (isDomainOrSubdomain(host, 'phongvu.vn')) return 'phongvu'; + if (isDomainOrSubdomain(host, 'gearvn.com')) return 'gearvn'; + if (isDomainOrSubdomain(host, 'nguyenkim.com')) return 'nguyenkim'; + if (isDomainOrSubdomain(host, 'shopdunk.com')) return 'shopdunk'; + if (isDomainOrSubdomain(host, 'hacom.vn')) return 'hacom'; + if (isDomainOrSubdomain(host, 'clickbuy.com.vn')) return 'clickbuy'; + if (isDomainOrSubdomain(host, 'viettelstore.vn')) return 'viettelstore'; + if (isDomainOrSubdomain(host, 'pico.vn')) return 'pico'; + if (isDomainOrSubdomain(host, 'mediamart.vn')) return 'mediamart'; + if (isDomainOrSubdomain(host, 'memoryzone.com.vn')) return 'memoryzone'; + if (isDomainOrSubdomain(host, 'anphatpc.com.vn')) return 'anphatpc'; return null; } const RETAIL_NON_PRODUCT_FIRST_SEGMENTS = new Set([ 'tin-tuc', + 'tin-khuyen-mai', + 'cong-nghe', 'sforum', 'dchannel', 'hoi-dap', + 'huong-dan', 'khuyen-mai', + 'hot-deal', 'tra-gop', + 'thu-cu-doi-moi', 'bao-hanh', + 'tra-bao-hanh', + 'tra-cuu-bao-hanh', + 'chinh-sach', + 'lien-he', + 'gioi-thieu', + 've-chung-toi', + 'tuyen-dung', + 'so-sanh', + 'so-sanh-san-pham', + 'compare', + 'cua-hang', + 'showroom', + 'sieu-thi', 'he-thong-cua-hang', 'he-thong-sieu-thi', + 'he-thong-showroom', + 'he-thong-trung-tam', + 'trung-tam-bao-hanh', 'catalogsearch', 'tim-kiem', + 'ket-qua-tim-kiem', + 'tim', 'search', + 'filter', 'cart', 'gio-hang', + 'checkout', + 'thanh-toan', 'account', + 'tai-khoan', + 'taikhoan', 'login', + 'dang-nhap', + 'register', + 'dang-ky', + 'logout', + 'dang-xuat', + 'auth', + 'captcha', + 'challenge', 'blog', + 'blogs', 'news', 'event', + 'su-kien', 'landing', 'collection', + 'collections', + 'pages', + 'page', + 'policies', + 'tag', + 'tags', + 'brand', + 'thuong-hieu', + 'buildpc', + 'xay-dung-cau-hinh', + 'sua-chua', + 'dich-vu', + 'may-cu', + 'hang-cu', + 'may-cu-gia-re', + 'likenew', + 'like-new', + 'outlet', + 'xa-kho', + 'ajax', + 'api', + 'media', + 'static', + 'assets', + 'cdn-cgi', 'c', + 'danh-muc', ]); +const RETAIL_AUTH_OR_NON_PRODUCT_SLUG_REGEX = + /^(?:chinh-sach-|quy-che-|huong-dan-|dieu-khoan-|gioi-thieu(?:-|$)|ve-chung-toi(?:-|$)|tin-khuyen-mai(?:-|$)|tin-tuc-|khuyen-mai-|sua-chua(?:-|$)|dich-vu(?:-|$)|tra-bao-hanh(?:-|$)|tra-cuu-bao-hanh(?:-|$)|he-thong-(?:cua-hang|sieu-thi|showroom|trung-tam)(?:-|$)|ket-qua-tim-kiem$|so-sanh(?:-san-pham)?$|buildpc$|xay-dung-cau-hinh$)/i; + +const RETAIL_AUTH_SEGMENT_REGEX = + /^(?:login|register|account|tai-khoan|taikhoan|dang-nhap|dang-ky|logout|dang-xuat|auth|captcha|challenge)$/i; + +const RETAIL_STATIC_ASSET_EXT_REGEX = + /\.(?:js|mjs|cjs|json|css|xml|txt|pdf|zip|rar|7z|png|jpe?g|webp|avif|svg|gif|ico|woff2?|ttf|eot|map|mp[34]|webm|aspx|ashx|axd|php)$/i; + +const ANPHAT_DESK_PHONE_SLUG_REGEX = + /^(?:dien-thoai-(?:huu-tuyen|ip|ban|de-ban|khong-day|keo-dai|hoi-nghi)|tong-dai-ip)(?:-|$)/i; + const RETAIL_CATEGORY_ROOT_SLUGS = new Set([ 'dtdd', + 'mtb', 'dien-thoai', 'dien-thoai-di-dong', + 'dien-thoai-thong-minh', 'mobile', 'smartphones', 'laptop', 'laptops', + 'laptop-gaming', + 'laptop-gaming-do-hoa', + 'laptop-van-phong', + 'laptop-tablet-mobile', 'may-tinh-xach-tay', + 'may-tinh-xach-tay-laptop', 'may-tinh-bang', + 'may-tinh-bang-tablet', 'tablet', 'tablets', + 'dong-ho', 'dong-ho-thong-minh', 'smartwatch', 'smartwatches', 'tai-nghe', + 'tai-nghe-bluetooth', + 'tai-nghe-nhet-tai', + 'tai-nghe-chup-tai', + 'tai-nghe-gaming', + 'am-thanh', + 'thiet-bi-am-thanh', + 'loa', 'earbuds', 'phu-kien', + 'phu-kien-di-dong', + 'linh-kien', + 'linh-kien-may-tinh', + 'man-hinh', + 'man-hinh-may-tinh', + 'pc', + 'pc-gaming', + 'pc-van-phong-do-hoa', + 'may-tinh-de-ban', + 'gaming-gear', + 'tivi', + 'tu-lanh', + 'may-giat', + 'may-lanh', + 'gia-dung', + 'dien-gia-dung', + 'dien-may', + 'sim-so', + 'san-pham', + 'products', + 'product', 'apple', + 'apple-iphone', + 'apple-ipad', + 'apple-watch', 'iphone', 'ipad', 'macbook', @@ -183,6 +305,15 @@ const RETAIL_BRAND_LISTING_SLUGS = new Set([ 'anker', 'baseus', 'ugreen', + 'logitech', + 'razer', + 'corsair', + 'hyperx', + 'steelseries', + 'bose', + 'sennheiser', + 'gigabyte', + 'tcl', 'mac', ]); @@ -193,6 +324,133 @@ const ACCESSORY_SLUG_PREFIX = const isSeriesListingSlug = (slug: string) => /-series$/.test(slug) && !ACCESSORY_SLUG_PREFIX.test(slug); +function extractValidRetailItemSlug( + retailPlatform: SupportedEcommercePlatform, + segments: readonly string[] +): string | null { + if (segments.length === 0) return null; + + for (const seg of segments) { + const strippedSeg = seg + .toLowerCase() + .replace(/\.(?:html|htm|aspx|ashx|axd|php)$/i, ''); + if ( + RETAIL_AUTH_SEGMENT_REGEX.test(strippedSeg) || + RETAIL_AUTH_SEGMENT_REGEX.test(seg) + ) { + return null; + } + } + + const firstRawLower = segments[0]!.toLowerCase(); + const firstSegLower = firstRawLower.replace(/\.html?$/i, ''); + const lastRaw = segments[segments.length - 1]!; + if (RETAIL_STATIC_ASSET_EXT_REGEX.test(lastRaw)) { + return null; + } + if ( + (retailPlatform === 'nguyenkim' || retailPlatform === 'pico') && + /\.(?:c|b)$/i.test(lastRaw) + ) { + return null; + } + + const isCollectionProductPath = + segments.length === 4 && + firstSegLower === 'collections' && + segments[2]!.toLowerCase() === 'products'; + + if (retailPlatform === 'gearvn') { + if ( + !(segments.length === 2 && firstSegLower === 'products') && + !isCollectionProductPath + ) { + return null; + } + } else if (retailPlatform === 'memoryzone') { + if ( + segments.length !== 1 && + !(segments.length === 2 && firstSegLower === 'products') && + !isCollectionProductPath + ) { + return null; + } + } else if (retailPlatform === 'mediamart') { + if (segments.length !== 2) return null; + } else if ( + retailPlatform === 'tgdd' || + retailPlatform === 'dienmayxanh' || + retailPlatform === 'topzone' + ) { + if (segments.length < 2) return null; + } else if (retailPlatform === 'cellphones') { + // CellphoneS product pages sit at the root ("/iphone-16-pro-max.html"); + // deeper paths are category listings (DOS/Rate#1246). + if (segments.length > 1) return null; + } else if ( + retailPlatform === 'nguyenkim' || + retailPlatform === 'shopdunk' || + retailPlatform === 'hacom' || + retailPlatform === 'clickbuy' || + retailPlatform === 'pico' + ) { + if ( + segments.length !== 1 && + !( + segments.length === 2 && + (firstSegLower === 'products' || firstSegLower === 'san-pham') + ) + ) { + return null; + } + } else if (retailPlatform === 'viettelstore') { + if (segments.length > 2) return null; + } else if (retailPlatform === 'anphatpc') { + const hasHtmlExt = /\.html?$/i.test(lastRaw); + const isDirectRoutePrefix = + segments.length === 2 && + (firstSegLower === 'products' || firstSegLower === 'san-pham'); + if (!hasHtmlExt && !isDirectRoutePrefix) return null; + if (firstRawLower.startsWith('ajax') || firstRawLower.endsWith('.php')) { + return null; + } + if (segments.some((s) => /_dm\d+$/i.test(s.replace(/\.html?$/i, '')))) { + return null; + } + } + + if ( + !isCollectionProductPath && + RETAIL_NON_PRODUCT_FIRST_SEGMENTS.has(firstSegLower) + ) { + return null; + } + + const lastSeg = lastRaw.replace(/\.html?$/i, '') || null; + const lastSegLower = (lastSeg || '').toLowerCase(); + if ( + !lastSeg || + lastSeg.length < 2 || + lastSeg.length > 120 || + !/^[a-z0-9][a-z0-9._-]*[a-z0-9]$/i.test(lastSegLower) || + lastSegLower.includes('..') || + /^(?:0+|null|undefined|nan|infinity|-infinity|true|false|default|index|home|trang-chu|404|page-not-found|error)$/i.test( + lastSegLower + ) || + RETAIL_NON_PRODUCT_FIRST_SEGMENTS.has(lastSegLower) || + RETAIL_CATEGORY_ROOT_SLUGS.has(lastSegLower) || + RETAIL_BRAND_LISTING_SLUGS.has(lastSegLower) || + RETAIL_AUTH_OR_NON_PRODUCT_SLUG_REGEX.test(lastSegLower) || + isSeriesListingSlug(lastSegLower) || + (retailPlatform === 'anphatpc' && + ANPHAT_DESK_PHONE_SLUG_REGEX.test(lastSegLower)) + ) { + return null; + } + + return lastSeg; +} + export function extractIdsFromUrl( platform: SupportedEcommercePlatform, canonicalUrl: string @@ -265,7 +523,7 @@ export function extractIdsFromUrl( }; } - // For CellphoneS / TGDD / FPT Shop / Hoàng Hà / Di Động Việt / Phong Vũ, validate pathname segments + // Validate pathname segments across all 18 Vietnamese retail chains let pathname = canonicalUrl; try { pathname = new URL(canonicalUrl).pathname; @@ -276,32 +534,8 @@ export function extractIdsFromUrl( .split('/') .map((s) => s.trim()) .filter(Boolean); - const firstSegLower = (segments[0] || '') - .replace(/\.html?$/i, '') - .toLowerCase(); - const lastSegment = - segments[segments.length - 1]?.replace(/\.html?$/i, '') || null; - const lastSegLower = (lastSegment || '').toLowerCase(); - const isValidItemSlug = - Boolean(lastSegment) && - lastSegment!.length >= 2 && - lastSegment!.length <= 120 && - /^[a-zA-Z0-9_.-]+$/.test(lastSegment!) && - /[a-zA-Z0-9]/.test(lastSegment!) && - !lastSegment!.startsWith('.') && - !lastSegment!.endsWith('.') && - !lastSegment!.includes('..') && - !RETAIL_NON_PRODUCT_FIRST_SEGMENTS.has(firstSegLower) && - !RETAIL_NON_PRODUCT_FIRST_SEGMENTS.has(lastSegLower) && - !(segments.length === 1 && RETAIL_CATEGORY_ROOT_SLUGS.has(firstSegLower)) && - !RETAIL_BRAND_LISTING_SLUGS.has(lastSegLower) && - !isSeriesListingSlug(lastSegLower) && - !(platform === 'tgdd' && segments.length < 2) && - // CellphoneS product pages sit at the root ("/iphone-16-pro-max.html"); - // deeper paths are category listings (DOS/Rate#1246). - !(platform === 'cellphones' && segments.length > 1); return { - externalItemId: isValidItemSlug ? lastSegment : null, + externalItemId: extractValidRetailItemSlug(platform, segments), externalShopId: null, }; } @@ -789,7 +1023,7 @@ export function cleanExtractedProductTitle(rawTitle: string): string { const withoutPlatformSuffix = stripLoneSurrogates(rawTitle) .replace(/\p{Cc}+/gu, ' ') .replace( - /\s*(?:\||[-–—])\s*(?:Shopee(?:\s*Việt\s*Nam|\s*VN)?|Lazada(?:\s*Việt\s*Nam|\s*VN)?|Tiki(?:\.vn)?|TikTok\s*Shop|CellphoneS(?:\.com\.vn)?|Thế\s*Giới\s*Di\s*Động|Thegioididong(?:\.com)?|TopZone(?:\.vn)?|Điện\s*Máy\s*Xanh|FPT\s*Shop|Fptshop(?:\.com\.vn)?|Hoàng\s*Hà\s*Mobile|HoangHaMobile(?:\.com)?|Di\s*Động\s*Việt|Didongviet(?:\.vn)?|Phong\s*Vũ|Phongvu(?:\.vn)?).*$/i, + /\s*(?:\||[-\u2013\u2014])\s*(?:Shopee(?:\s*Việt\s*Nam|\s*VN)?|Lazada(?:\s*Việt\s*Nam|\s*VN)?|Tiki(?:\.vn)?|TikTok\s*Shop|CellphoneS(?:\.com\.vn)?|Thế\s*Giới\s*Di\s*Động|Thegioididong(?:\.com)?|TopZone(?:\.vn)?|Điện\s*Máy\s*Xanh|Dienmayxanh(?:\.com)?|FPT\s*Shop|Fptshop(?:\.com\.vn)?|Hoàng\s*Hà\s*Mobile|HoangHaMobile(?:\.com)?|Di\s*Động\s*Việt|Didongviet(?:\.vn)?|Phong\s*Vũ|Phongvu(?:\.vn)?|GearVN(?:\.com)?|Nguy\u1ec5n\s*Kim|Nguyenkim(?:\.com)?|ShopDunk(?:\.com)?|HACOM(?:\.vn)?|Hanoicomputer(?:\.vn)?|Clickbuy(?:\.com\.vn)?|Viettel\s*Store|Viettelstore(?:\.vn)?|Si\u00eau\s*th\u1ecb\s*\u0111i\u1ec7n\s*m\u00e1y\s*Pico|Pico(?:\.vn)?|Media\s*Mart|Mediamart(?:\.vn)?|MemoryZone(?:\.com\.vn)?|An\s*Ph\u00e1t(?:\s*Computer|\s*PC)?|Anphatpc(?:\.com\.vn)?).*$/i, '' ) .replace(/\s+/g, ' ') @@ -1065,6 +1299,14 @@ export function extractProductSignalFromDom( '[data-testid="pdp-product-price"]', '.pdp-price_type_normal', '.product-price__current-price', + '.product-price .pro-price', + '.product_info_price_value-final', + '.overview .prices .actual-price', + '.pdp-price-online', + '.product-detail-price .price-sale', + '.cb-pbox__now:not([hidden])', + '.wrap-price .new-price', + '.special-price .price', '.tpt---sale-price', '.box-price-present', ]; @@ -1084,6 +1326,15 @@ export function extractProductSignalFromDom( '.ZA5sW5', '.pdp-price_type_deleted', '.product-price__original-price', + '.product-price .pro-price-del', + '.product_info_price_value-real', + '.overview .old-product-price', + '.pdp-price-old', + '.product-detail-price .price-old', + '.cb-pbox__old:not([hidden])', + '.wrap-price .old-price', + '.product-price-regular', + '.old-price .price', '.tpt---price-through', '.box-price-old', 'del', diff --git a/apps/extension/src/security-guards.ts b/apps/extension/src/security-guards.ts index d28bf39ee..e47a79402 100644 --- a/apps/extension/src/security-guards.ts +++ b/apps/extension/src/security-guards.ts @@ -31,10 +31,22 @@ const ALLOWED_EXTENSION_PLATFORMS: ReadonlySet = 'tiktok', 'cellphones', 'tgdd', + 'dienmayxanh', + 'topzone', 'fptshop', 'hoangha', 'didongviet', 'phongvu', + 'gearvn', + 'nguyenkim', + 'shopdunk', + 'hacom', + 'clickbuy', + 'viettelstore', + 'pico', + 'mediamart', + 'memoryzone', + 'anphatpc', ]); export const ALLOWED_API_BASE_ORIGINS = [ diff --git a/apps/extension/src/test-extension-pipeline.ts b/apps/extension/src/test-extension-pipeline.ts index 90a82646e..4f8bac4e7 100644 --- a/apps/extension/src/test-extension-pipeline.ts +++ b/apps/extension/src/test-extension-pipeline.ts @@ -134,7 +134,7 @@ async function runTests() { ); assert.equal( detectEcommercePlatform('https://www.topzone.vn/iphone/iphone-16-pro-max'), - 'tgdd' + 'topzone' ); assert.equal( detectEcommercePlatform('https://www.google.com/search?q=shopee.vn'), @@ -158,7 +158,23 @@ async function runTests() { ); assert.equal( detectPlatformFromInput(null, 'https://www.dienmayxanh.com/dtdd/iphone-16'), - 'tgdd' + 'dienmayxanh' + ); + assert.equal( + detectPlatformFromInput( + 'tgdd', + 'https://www.dienmayxanh.com/dtdd/iphone-16' + ), + 'dienmayxanh', + 'Legacy tgdd platform hint upgrades to dienmayxanh when rawUrl is dienmayxanh.com' + ); + assert.equal( + detectPlatformFromInput( + 'tgdd', + 'https://www.topzone.vn/iphone/iphone-16-pro-max' + ), + 'topzone', + 'Legacy tgdd platform hint upgrades to topzone when rawUrl is topzone.vn' ); assert.deepEqual( parseEcommerceUrlOrQuery( @@ -190,7 +206,7 @@ async function runTests() { ), { isUrl: true, - platform: 'tgdd', + platform: 'topzone', platformShopId: null, platformItemId: 'iphone-16-pro-max-256gb', internalSlug: null, @@ -247,10 +263,10 @@ async function runTests() { null, 'parseEcommerceUrlOrQuery must reject spoofed domains' ); - assert.equal(Object.keys(EXTENSION_CAPABILITY_MATRIX).length, 10); + assert.equal(Object.keys(EXTENSION_CAPABILITY_MATRIX).length, 22); assert.equal(parseVndPriceText('28.990.000₫ - 34.990.000₫'), 28990000); console.log( - ' ✅ [1/6] URL Canonicalization & 10-Platform ID Extraction passed' + ' ✅ [1/6] URL Canonicalization & 22-Platform ID Extraction passed' ); // 2. Gatekeeper Layer 0: Accessory & Spare Part Rejection @@ -440,6 +456,35 @@ async function runTests() { assert.equal(EXTENSION_CAPABILITY_MATRIX.hoangha.crowdVerifyQueue, true); assert.equal(EXTENSION_CAPABILITY_MATRIX.didongviet.crowdVerifyQueue, true); assert.equal(EXTENSION_CAPABILITY_MATRIX.phongvu.crowdVerifyQueue, true); + for (const wavePlatform of [ + 'dienmayxanh', + 'topzone', + 'gearvn', + 'nguyenkim', + 'shopdunk', + 'hacom', + 'clickbuy', + 'viettelstore', + 'pico', + 'mediamart', + 'memoryzone', + 'anphatpc', + ] as const) { + assert.equal(EXTENSION_CAPABILITY_MATRIX[wavePlatform].lookup, true); + assert.equal( + EXTENSION_CAPABILITY_MATRIX[wavePlatform].exactItemMatch, + true + ); + assert.equal( + EXTENSION_CAPABILITY_MATRIX[wavePlatform].crossCatalogMatch, + true + ); + assert.equal( + EXTENSION_CAPABILITY_MATRIX[wavePlatform].crowdVerifyQueue, + false, + `${wavePlatform} crowdVerifyQueue must remain false until DOS-Me SQL migration` + ); + } assert.equal(EXTENSION_CAPABILITY_MATRIX.tiktok.lookup, true); assert.equal(EXTENSION_CAPABILITY_MATRIX.hoangha.lookup, true); assert.equal(DEFAULT_API_BASE_URL, 'https://rate.vn'); @@ -580,19 +625,93 @@ async function runTests() { ); } - for (const url of [ - 'https://thegioididong.com/dtdd/iphone-16-pro-max', - 'https://www.thegioididong.com/dtdd/iphone-16-pro-max', - 'https://topzone.vn/iphone/iphone-16-pro-max', - 'https://www.topzone.vn/iphone/iphone-16-pro-max', - 'https://dienmayxanh.com/dtdd/iphone-16-pro-max', - 'https://www.dienmayxanh.com/dtdd/iphone-16-pro-max', - ]) { + for (const [url, expectedPlatform, expectedItemId] of [ + [ + 'https://thegioididong.com/dtdd/iphone-16-pro-max', + 'tgdd', + 'iphone-16-pro-max', + ], + [ + 'https://www.thegioididong.com/dtdd/iphone-16-pro-max', + 'tgdd', + 'iphone-16-pro-max', + ], + [ + 'https://topzone.vn/iphone/iphone-16-pro-max', + 'topzone', + 'iphone-16-pro-max', + ], + [ + 'https://www.topzone.vn/iphone/iphone-16-pro-max', + 'topzone', + 'iphone-16-pro-max', + ], + [ + 'https://dienmayxanh.com/dtdd/iphone-16-pro-max', + 'dienmayxanh', + 'iphone-16-pro-max', + ], + [ + 'https://www.dienmayxanh.com/dtdd/iphone-16-pro-max', + 'dienmayxanh', + 'iphone-16-pro-max', + ], + [ + 'https://gearvn.com/products/laptop-gaming-asus-rog-strix', + 'gearvn', + 'laptop-gaming-asus-rog-strix', + ], + [ + 'https://www.nguyenkim.com/dien-thoai-iphone-16-pro-max.html', + 'nguyenkim', + 'dien-thoai-iphone-16-pro-max', + ], + [ + 'https://shopdunk.com/iphone-16-pro-max', + 'shopdunk', + 'iphone-16-pro-max', + ], + [ + 'https://hacom.vn/laptop-apple-macbook-air-m3', + 'hacom', + 'laptop-apple-macbook-air-m3', + ], + [ + 'https://clickbuy.com.vn/apple-iphone-16-pro-max.html', + 'clickbuy', + 'apple-iphone-16-pro-max', + ], + [ + 'https://viettelstore.vn/dien-thoai/iphone-16-pro-max-pid341099.html', + 'viettelstore', + 'iphone-16-pro-max-pid341099', + ], + [ + 'https://pico.vn/39871-dien-thoai-apple-iphone-16-pro-max', + 'pico', + '39871-dien-thoai-apple-iphone-16-pro-max', + ], + [ + 'https://mediamart.vn/smartphones/apple-iphone-16-pro-max', + 'mediamart', + 'apple-iphone-16-pro-max', + ], + [ + 'https://memoryzone.com.vn/products/macbook-pro-14-m4', + 'memoryzone', + 'macbook-pro-14-m4', + ], + [ + 'https://www.anphatpc.com.vn/laptop-apple-macbook-air-m3_id49201.html', + 'anphatpc', + 'laptop-apple-macbook-air-m3_id49201', + ], + ] as const) { assert.ok(injectedOn(url), `content script must run on ${url}`); - assert.equal(detectEcommercePlatform(url), 'tgdd', url); + assert.equal(detectEcommercePlatform(url), expectedPlatform, url); assert.equal( - extractIdsFromUrl('tgdd', url).externalItemId, - 'iphone-16-pro-max', + extractIdsFromUrl(expectedPlatform, url).externalItemId, + expectedItemId, url ); assert.ok( @@ -607,6 +726,26 @@ async function runTests() { 'https://*.topzone.vn/*', 'https://dienmayxanh.com/*', 'https://*.dienmayxanh.com/*', + 'https://gearvn.com/*', + 'https://*.gearvn.com/*', + 'https://nguyenkim.com/*', + 'https://*.nguyenkim.com/*', + 'https://shopdunk.com/*', + 'https://*.shopdunk.com/*', + 'https://hacom.vn/*', + 'https://*.hacom.vn/*', + 'https://clickbuy.com.vn/*', + 'https://*.clickbuy.com.vn/*', + 'https://viettelstore.vn/*', + 'https://*.viettelstore.vn/*', + 'https://pico.vn/*', + 'https://*.pico.vn/*', + 'https://mediamart.vn/*', + 'https://*.mediamart.vn/*', + 'https://memoryzone.com.vn/*', + 'https://*.memoryzone.com.vn/*', + 'https://anphatpc.com.vn/*', + 'https://*.anphatpc.com.vn/*', ]) { assert.ok(matches.includes(pattern), `matches missing ${pattern}`); assert.ok(hosts.includes(pattern), `host_permissions missing ${pattern}`); @@ -615,6 +754,16 @@ async function runTests() { 'https://eviltopzone.vn/iphone/iphone-16-pro-max', 'https://evildienmayxanh.com/dtdd/iphone-16-pro-max', 'https://evilthegioididong.com/dtdd/iphone-16-pro-max', + 'https://evilgearvn.com/products/iphone-16-pro-max', + 'https://evilnguyenkim.com/iphone-16-pro-max.html', + 'https://evilshopdunk.com/iphone-16-pro-max', + 'https://evilhacom.vn/iphone-16-pro-max', + 'https://evilclickbuy.com.vn/iphone-16-pro-max.html', + 'https://evilviettelstore.vn/dien-thoai/iphone-16-pro-max.html', + 'https://evilpico.vn/iphone-16-pro-max', + 'https://evilmediamart.vn/smartphones/iphone-16-pro-max', + 'https://evilmemoryzone.com.vn/products/iphone-16-pro-max', + 'https://evilanphatpc.com.vn/iphone-16-pro-max.html', ]) { assert.ok( !injectedOn(lookalikeUrl), @@ -1697,8 +1846,8 @@ async function runTests() { assert.equal( detectEcommercePlatform('https://www.dienmayxanh.com/dtdd/iphone-16e'), - 'tgdd', - 'detectEcommercePlatform must map dienmayxanh.com to tgdd' + 'dienmayxanh', + 'detectEcommercePlatform must map dienmayxanh.com to dienmayxanh' ); assert.deepEqual( extractIdsFromUrl( @@ -8397,17 +8546,17 @@ async function runTests() { ['tiki.vn/sp-p777888.html', 'tiki', '777888'], ['tiktok.com/@apple/product/999111', 'tiktok', '999111'], ['thegioididong.com/dtdd/iphone-16-pro', 'tgdd', 'iphone-16-pro'], - ['topzone.vn/iphone/iphone-16-pro', 'tgdd', 'iphone-16-pro'], + ['topzone.vn/iphone/iphone-16-pro', 'topzone', 'iphone-16-pro'], [ 'www.topzone.vn/iphone/iphone-16-pro?utm_source=fb#specs', - 'tgdd', + 'topzone', 'iphone-16-pro', 'https://www.topzone.vn/iphone/iphone-16-pro', ], - ['dienmayxanh.com/dtdd/iphone-16-pro', 'tgdd', 'iphone-16-pro'], + ['dienmayxanh.com/dtdd/iphone-16-pro', 'dienmayxanh', 'iphone-16-pro'], [ '//www.dienmayxanh.com/dtdd/iphone-16-pro', - 'tgdd', + 'dienmayxanh', 'iphone-16-pro', 'https://www.dienmayxanh.com/dtdd/iphone-16-pro', ], @@ -8428,6 +8577,52 @@ async function runTests() { 'phongvu', 'apple-iphone-16-pro--s2502001', ], + [ + 'gearvn.com/products/laptop-asus-rog-strix', + 'gearvn', + 'laptop-asus-rog-strix', + ], + [ + 'www.nguyenkim.com/dien-thoai-iphone-16-pro.html', + 'nguyenkim', + 'dien-thoai-iphone-16-pro', + ], + ['shopdunk.com/iphone-16-pro', 'shopdunk', 'iphone-16-pro'], + [ + 'hacom.vn/laptop-apple-macbook-air-m3', + 'hacom', + 'laptop-apple-macbook-air-m3', + ], + [ + 'clickbuy.com.vn/apple-iphone-16-pro.html', + 'clickbuy', + 'apple-iphone-16-pro', + ], + [ + 'viettelstore.vn/dien-thoai/iphone-16-pro-pid341098.html', + 'viettelstore', + 'iphone-16-pro-pid341098', + ], + [ + 'pico.vn/39870-dien-thoai-iphone-16-pro', + 'pico', + '39870-dien-thoai-iphone-16-pro', + ], + [ + 'mediamart.vn/smartphones/iphone-16-pro', + 'mediamart', + 'iphone-16-pro', + ], + [ + 'memoryzone.com.vn/products/macbook-pro-14-m4', + 'memoryzone', + 'macbook-pro-14-m4', + ], + [ + 'www.anphatpc.com.vn/laptop-apple-macbook-air-m3_id49201.html', + 'anphatpc', + 'laptop-apple-macbook-air-m3_id49201', + ], ]; for (const [ bareUrl, @@ -11751,6 +11946,529 @@ async function runTests() { } } } + // --- DOS/Rate#1850: 12 Wave 1-3 retail platforms across detector, lookup & SQL boundary --- + { + const { cleanExtractedProductTitle, extractProductSignalFromDom } = + await import('./extractors/ecommerce-detector.js'); + const { buildCandidateExternalItemIds } = + await import('../../web/src/server/rate/extension.js'); + + // 1. Positive PDP detection & ID extraction across all 12 Wave 1-3 platforms + for (const [url, expectedPlatform, expectedId] of [ + [ + 'https://www.dienmayxanh.com/dtdd/iphone-16-pro-max', + 'dienmayxanh', + 'iphone-16-pro-max', + ], + [ + 'https://www.topzone.vn/iphone/iphone-16-pro-max', + 'topzone', + 'iphone-16-pro-max', + ], + [ + 'https://gearvn.com/products/laptop-gaming-asus-rog-strix', + 'gearvn', + 'laptop-gaming-asus-rog-strix', + ], + [ + 'https://gearvn.com/collections/laptop-gaming/products/asus-tuf-a15', + 'gearvn', + 'asus-tuf-a15', + ], + [ + 'https://www.nguyenkim.com/dien-thoai-iphone-16-pro-max.html', + 'nguyenkim', + 'dien-thoai-iphone-16-pro-max', + ], + [ + 'https://shopdunk.com/iphone-16-pro-max', + 'shopdunk', + 'iphone-16-pro-max', + ], + [ + 'https://hacom.vn/laptop-apple-macbook-air-m3', + 'hacom', + 'laptop-apple-macbook-air-m3', + ], + [ + 'https://clickbuy.com.vn/apple-iphone-16-pro-max.html', + 'clickbuy', + 'apple-iphone-16-pro-max', + ], + [ + 'https://viettelstore.vn/dien-thoai/iphone-16-pro-max-pid341099.html', + 'viettelstore', + 'iphone-16-pro-max-pid341099', + ], + [ + 'https://pico.vn/39871-dien-thoai-apple-iphone-16-pro-max', + 'pico', + '39871-dien-thoai-apple-iphone-16-pro-max', + ], + [ + 'https://mediamart.vn/smartphones/apple-iphone-16-pro-max', + 'mediamart', + 'apple-iphone-16-pro-max', + ], + [ + 'https://memoryzone.com.vn/products/macbook-pro-14-m4', + 'memoryzone', + 'macbook-pro-14-m4', + ], + [ + 'https://memoryzone.com.vn/ssd-samsung-990-pro-1tb', + 'memoryzone', + 'ssd-samsung-990-pro-1tb', + ], + [ + 'https://www.anphatpc.com.vn/laptop-apple-macbook-air-m3_id49201.html', + 'anphatpc', + 'laptop-apple-macbook-air-m3_id49201', + ], + ] as const) { + assert.equal(detectEcommercePlatform(url), expectedPlatform, url); + assert.deepEqual( + extractIdsFromUrl(expectedPlatform, url), + { externalItemId: expectedId, externalShopId: null }, + url + ); + } + + // 2. Non-product category, brand, auth, policy, static-asset, and desk-phone rejections + for (const [platform, badUrl] of [ + ['dienmayxanh', 'https://www.dienmayxanh.com/dtdd'], + ['topzone', 'https://www.topzone.vn/iphone'], + ['gearvn', 'https://gearvn.com/collections/laptop-gaming'], + ['gearvn', 'https://gearvn.com/pages/chinh-sach-bao-hanh'], + ['nguyenkim', 'https://www.nguyenkim.com/dien-thoai-di-dong.c'], + ['nguyenkim', 'https://www.nguyenkim.com/apple.b'], + ['shopdunk', 'https://shopdunk.com/iphone'], + ['shopdunk', 'https://shopdunk.com/iphone-16-series'], + ['hacom', 'https://hacom.vn/buildpc'], + ['hacom', 'https://hacom.vn/chinh-sach-bao-hanh'], + ['clickbuy', 'https://clickbuy.com.vn/sua-chua'], + ['viettelstore', 'https://viettelstore.vn/dien-thoai'], + ['viettelstore', 'https://viettelstore.vn/tin-tuc/iphone-16-ra-mat'], + ['pico', 'https://pico.vn/dien-thoai.c'], + ['mediamart', 'https://mediamart.vn/smartphones'], + ['memoryzone', 'https://memoryzone.com.vn/collections/ssd'], + [ + 'anphatpc', + 'https://www.anphatpc.com.vn/may-tinh-xach-tay-laptop_dm1013.html', + ], + [ + 'anphatpc', + 'https://www.anphatpc.com.vn/dien-thoai-ban-panasonic-kx-ts500_id1234.html', + ], + ['anphatpc', 'https://www.anphatpc.com.vn/laptop-asus-without-html-ext'], + ] as const) { + assert.equal( + extractIdsFromUrl(platform, badUrl).externalItemId, + null, + `must reject non-product URL ${badUrl}` + ); + } + + // 3. Title suffix cleaning across Wave 1-3 chains + for (const [rawTitle, expectedClean] of [ + ['Laptop ASUS ROG Strix G16 | GearVN.com', 'Laptop ASUS ROG Strix G16'], + ['iPhone 16 Pro Max 256GB - Nguyễn Kim', 'iPhone 16 Pro Max 256GB'], + ['iPhone 16 Pro Max 256GB | ShopDunk.com', 'iPhone 16 Pro Max 256GB'], + ['MacBook Air M3 13 inch | HACOM', 'MacBook Air M3 13 inch'], + [ + 'Samsung Galaxy S25 Ultra - Clickbuy.com.vn', + 'Samsung Galaxy S25 Ultra', + ], + ['iPhone 16 Pro 128GB | Viettel Store', 'iPhone 16 Pro 128GB'], + ['iPhone 16 Pro Max - Siêu thị điện máy Pico', 'iPhone 16 Pro Max'], + ['iPhone 16 Pro Max 256GB | MediaMart', 'iPhone 16 Pro Max 256GB'], + ['MacBook Pro 14 M4 - MemoryZone', 'MacBook Pro 14 M4'], + ['Laptop MacBook Air M3 | An Phát Computer', 'Laptop MacBook Air M3'], + ] as const) { + assert.equal( + cleanExtractedProductTitle(rawTitle), + expectedClean, + rawTitle + ); + } + + // 4. DOM extraction with MediaMart .product-price-regular strikethrough original price + const mediamartDoc = { + title: 'Apple iPhone 16 Pro Max 256GB | MediaMart', + querySelectorAll: (sel: string) => + sel === 'script[type="application/ld+json"]' + ? [ + { + textContent: JSON.stringify({ + '@type': 'Product', + name: 'Apple iPhone 16 Pro Max 256GB | MediaMart', + offers: { + '@type': 'Offer', + price: '29990000', + availability: 'https://schema.org/InStock', + }, + }), + }, + ] + : [], + querySelector: (sel: string) => + sel === '.product-price-regular' + ? { textContent: '34.990.000₫' } + : null, + } as unknown as Document; + const mediamartSignal = extractProductSignalFromDom( + mediamartDoc, + 'https://mediamart.vn/smartphones/apple-iphone-16-pro-max?utm_source=zalo' + ); + assert.ok(mediamartSignal); + assert.equal(mediamartSignal.platform, 'mediamart'); + assert.equal( + mediamartSignal.canonicalUrl, + 'https://mediamart.vn/smartphones/apple-iphone-16-pro-max' + ); + assert.equal(mediamartSignal.externalItemId, 'apple-iphone-16-pro-max'); + assert.equal(mediamartSignal.price, 29_990_000); + assert.equal(mediamartSignal.originalPrice, 34_990_000); + + // 5. Server lookup candidate item ID prefixes across all 12 Wave 1-3 platforms + const dmxIds = buildCandidateExternalItemIds({ + platform: 'dienmayxanh', + externalId: 'iphone-16-pro-max', + }); + assert.ok( + dmxIds.includes('dmx-iphone-16-pro-max') && + dmxIds.includes('tgdd-iphone-16-pro-max') + ); + const tzIds = buildCandidateExternalItemIds({ + platform: 'topzone', + externalId: 'iphone-16-pro-max', + }); + assert.ok( + tzIds.includes('tz-iphone-16-pro-max') && + tzIds.includes('tgdd-iphone-16-pro-max') + ); + assert.ok( + buildCandidateExternalItemIds({ + platform: 'anphatpc', + externalId: 'laptop_id49201', + }).includes('ap-laptop_5fid49201') + ); + assert.ok( + buildCandidateExternalItemIds({ + platform: 'nguyenkim', + externalId: 'iphone_16', + }).includes('nk-iphone_5f16') + ); + + // 6. Service-worker sender validation & DOS-Me SQL boundary (crowd observation skipped for Wave 1-3) + const g1850 = globalThis as Record; + const savedChrome1850 = Object.getOwnPropertyDescriptor(g1850, 'chrome'); + const savedFetch1850 = Object.getOwnPropertyDescriptor(g1850, 'fetch'); + try { + const local1850 = new Map([ + ['apiBaseUrl', 'https://rate.vn'], + ['crowdContributeOptIn', true], + ['crowdConsentVersion', 2], + ]); + const session1850 = new Map(); + const swFetchCalls1850: string[] = []; + let swHandler1850: + | (( + msg: Record, + sender: Record, + sendResponse: (res: unknown) => void + ) => boolean | void) + | null = null; + + Object.defineProperty(g1850, 'chrome', { + configurable: true, + writable: true, + value: { + runtime: { + id: 'rate-ext-1850', + getManifest: () => ({ version: '2.0.0' }), + getURL: (p: string) => `chrome-extension://rate-ext-1850/${p}`, + onInstalled: { addListener: () => {} }, + onStartup: { addListener: () => {} }, + onMessage: { + addListener: (cb: typeof swHandler1850) => { + swHandler1850 = cb; + }, + }, + }, + storage: { + local: { + get: async (keys?: string | string[]) => { + const list = Array.isArray(keys) + ? keys + : typeof keys === 'string' + ? [keys] + : [...local1850.keys()]; + return Object.fromEntries( + list + .filter((k) => local1850.has(k)) + .map((k) => [k, local1850.get(k)]) + ); + }, + set: async (items: Record) => { + for (const [k, v] of Object.entries(items)) local1850.set(k, v); + }, + remove: async (keys: string | string[]) => { + for (const k of Array.isArray(keys) ? keys : [keys]) { + local1850.delete(k); + } + }, + }, + session: { + get: async (keys?: string | string[]) => { + const list = Array.isArray(keys) + ? keys + : typeof keys === 'string' + ? [keys] + : [...session1850.keys()]; + return Object.fromEntries( + list + .filter((k) => session1850.has(k)) + .map((k) => [k, session1850.get(k)]) + ); + }, + set: async (items: Record) => { + for (const [k, v] of Object.entries(items)) + session1850.set(k, v); + }, + remove: async (keys: string | string[]) => { + for (const k of Array.isArray(keys) ? keys : [keys]) { + session1850.delete(k); + } + }, + }, + }, + sidePanel: { + setPanelBehavior: async () => {}, + open: async () => {}, + }, + action: { + setBadgeText: async () => {}, + setBadgeBackgroundColor: async () => {}, + }, + tabs: { + query: async () => [{ id: 88, active: true }], + create: async () => ({ id: 89 }), + }, + }, + }); + Object.defineProperty(g1850, 'fetch', { + configurable: true, + writable: true, + value: async (input: string | URL) => { + const href = String(input); + swFetchCalls1850.push(href); + if (href.includes('/api/v1/rate/extension/submitter')) { + return new Response( + JSON.stringify({ + ok: true, + submitterId: '11111111-1111-4111-8111-111111111111', + }), + { status: 200, headers: { 'Content-Type': 'application/json' } } + ); + } + if (href.includes('/api/v1/rate/extension/observation')) { + return new Response(JSON.stringify({ ok: true }), { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }); + } + return new Response( + JSON.stringify({ + ok: true, + data: { + matchStatus: 'exact_listing', + platform: 'gearvn', + canonicalUrl: 'https://gearvn.com/products/asus-rog-strix', + detectedStorageGb: 512, + isAccessoryOrPart: false, + accessoryReason: null, + variantCandidates: [], + priceAssessment: { + verdict: 'genuine_deal', + badgeLabel: 'Giá Tốt Thực Sự', + explanation: 'Giá tốt', + observedPrice: 28_990_000, + observedOriginalPrice: 32_990_000, + claimedDiscountPct: 12, + vsMarketMedianPct: -6, + marketMinPrice: 28_990_000, + marketMedianPrice: 30_990_000, + marketMaxPrice: 32_990_000, + historicalMinPrice: 28_990_000, + historicalMaxPrice: 33_990_000, + cheaperOfferCount: 0, + maxSavingsAmount: 0, + }, + masterProduct: null, + matchedOffer: null, + topCheaperOffers: [], + allOffers: [], + merchantProfile: null, + reviewSummary: null, + priceHistory: null, + compareUrl: null, + productDetailUrl: null, + }, + }), + { status: 200, headers: { 'Content-Type': 'application/json' } } + ); + }, + }); + + await import( + new URL('./background/service-worker.js?case=1850sw', import.meta.url) + .href + ); + const callSw1850 = ( + msg: Record, + sender: Record + ) => + new Promise>((resolve) => { + const asyncReply = swHandler1850!(msg, sender, (r) => + resolve(r as Record) + ); + if (asyncReply === false) { + // sendResponse already called synchronously + } + }); + + for (const [platform, pageUrl, itemId] of [ + [ + 'dienmayxanh', + 'https://www.dienmayxanh.com/dtdd/iphone-16-pro-max', + 'iphone-16-pro-max', + ], + [ + 'topzone', + 'https://www.topzone.vn/iphone/iphone-16-pro-max', + 'iphone-16-pro-max', + ], + [ + 'gearvn', + 'https://gearvn.com/products/asus-rog-strix', + 'asus-rog-strix', + ], + [ + 'nguyenkim', + 'https://www.nguyenkim.com/iphone-16-pro-max.html', + 'iphone-16-pro-max', + ], + [ + 'shopdunk', + 'https://shopdunk.com/iphone-16-pro-max', + 'iphone-16-pro-max', + ], + ['hacom', 'https://hacom.vn/macbook-air-m3', 'macbook-air-m3'], + [ + 'clickbuy', + 'https://clickbuy.com.vn/iphone-16-pro-max.html', + 'iphone-16-pro-max', + ], + [ + 'viettelstore', + 'https://viettelstore.vn/dien-thoai/iphone-16-pro-max.html', + 'iphone-16-pro-max', + ], + [ + 'pico', + 'https://pico.vn/39871-iphone-16-pro-max', + '39871-iphone-16-pro-max', + ], + [ + 'mediamart', + 'https://mediamart.vn/smartphones/iphone-16-pro-max', + 'iphone-16-pro-max', + ], + [ + 'memoryzone', + 'https://memoryzone.com.vn/products/macbook-pro-14-m4', + 'macbook-pro-14-m4', + ], + [ + 'anphatpc', + 'https://www.anphatpc.com.vn/macbook-air-m3_id49201.html', + 'macbook-air-m3_id49201', + ], + ] as const) { + const res = await callSw1850( + { + type: 'RATE_PRODUCT_DETECTED', + signal: { + platform, + canonicalUrl: pageUrl, + externalItemId: itemId, + externalShopId: null, + title: 'iPhone 16 Pro Max 256GB', + selectedVariant: '256GB', + price: 28_990_000, + originalPrice: 32_990_000, + ratingStar: 4.9, + ratingCount: 25, + }, + }, + { + id: 'rate-ext-1850', + tab: { id: 88, windowId: 1, active: true }, + url: pageUrl, + } + ); + assert.equal( + res.ok, + true, + `Wave 1-3 lookup must succeed for ${platform}` + ); + } + await new Promise((r) => setTimeout(r, 30)); + assert.equal( + swFetchCalls1850.some( + (u) => u.includes('/submitter') || u.includes('/observation') + ), + false, + 'Wave 1-3 detections must NOT hit extension observation endpoints before DOS-Me SQL migration' + ); + + // Cross-store sender spoofing on Wave 1-3 origins must be rejected + const spoofRes = await callSw1850( + { + type: 'RATE_PRODUCT_DETECTED', + signal: { + platform: 'gearvn', + canonicalUrl: 'https://gearvn.com/products/asus-rog-strix', + externalItemId: 'asus-rog-strix', + externalShopId: null, + title: 'ASUS ROG Strix', + selectedVariant: null, + price: 28_990_000, + originalPrice: null, + ratingStar: null, + ratingCount: null, + }, + }, + { + id: 'rate-ext-1850', + tab: { id: 88, windowId: 1, active: true }, + url: 'https://shopdunk.com/iphone-16-pro-max', + } + ); + assert.equal(spoofRes.ok, false, 'cross-store sender spoofing must fail'); + } finally { + if (savedChrome1850) + Object.defineProperty(g1850, 'chrome', savedChrome1850); + else delete g1850.chrome; + if (savedFetch1850) Object.defineProperty(g1850, 'fetch', savedFetch1850); + else delete g1850.fetch; + } + + console.log( + ' ✅ [Wave 1-3 12 retail platforms across detector, lookup & SQL boundary (#1850)] Verified' + ); + } console.log('🎉 All Rate Browser Extension MV3 v2 tests passed!'); } diff --git a/apps/extension/src/types.ts b/apps/extension/src/types.ts index 6daaa903e..5244b2f7e 100644 --- a/apps/extension/src/types.ts +++ b/apps/extension/src/types.ts @@ -5,10 +5,22 @@ export type SupportedEcommercePlatform = | 'tiktok' | 'cellphones' | 'tgdd' + | 'dienmayxanh' + | 'topzone' | 'fptshop' | 'hoangha' | 'didongviet' - | 'phongvu'; + | 'phongvu' + | 'gearvn' + | 'nguyenkim' + | 'shopdunk' + | 'hacom' + | 'clickbuy' + | 'viettelstore' + | 'pico' + | 'mediamart' + | 'memoryzone' + | 'anphatpc'; export type ExtensionPriceVerdict = | 'genuine_deal' diff --git a/apps/importer/src/shopee/__tests__/shopee-to-supabase.test.ts b/apps/importer/src/shopee/__tests__/shopee-to-supabase.test.ts index 02e165d1f..7ff2b8d76 100644 --- a/apps/importer/src/shopee/__tests__/shopee-to-supabase.test.ts +++ b/apps/importer/src/shopee/__tests__/shopee-to-supabase.test.ts @@ -1092,6 +1092,135 @@ async function runTests() { console.log( ' ✅ [8/8] DOS/Rate#879 platformReviewIdFor, review videos/profileUrl & spec group bounds passed' ); + + // 9. DOS/Rate#1850: All 12 Wave 1-3 retail platforms ingest cleanly with canonical shopId and itemId prefixes + const wave1To3Fixtures = [ + { + platform: 'dienmayxanh' as const, + shopId: 'dmx-mwg-vn', + shopName: 'Điện Máy Xanh', + itemId: 'dmx-iphone-16-pro-max-256gb', + url: 'https://www.dienmayxanh.com/dtdd/iphone-16-pro-max-256gb', + title: 'Điện thoại iPhone 16 Pro Max 256GB Chính hãng VN/A', + }, + { + platform: 'topzone' as const, + shopId: 'tz-mwg-vn', + shopName: 'TopZone', + itemId: 'tz-iphone-16-pro-max-256gb', + url: 'https://www.topzone.vn/iphone/iphone-16-pro-max-256gb', + title: 'iPhone 16 Pro Max 256GB Chính hãng VN/A', + }, + { + platform: 'gearvn' as const, + shopId: 'gearvn-retail-vn', + shopName: 'GearVN', + itemId: 'gearvn-laptop-apple-macbook-air-m3-13-inch-256gb', + url: 'https://gearvn.com/products/laptop-apple-macbook-air-m3-13-inch-256gb', + title: 'Laptop Apple MacBook Air M3 13 inch 16GB 256GB Chính hãng', + }, + { + platform: 'nguyenkim' as const, + shopId: 'nguyenkim-vn', + shopName: 'Nguyễn Kim', + itemId: 'nk-dien-thoai-iphone-16-pro-max-256gb', + url: 'https://www.nguyenkim.com/dien-thoai-iphone-16-pro-max-256gb.html', + title: 'Điện thoại iPhone 16 Pro Max 256GB Chính hãng', + }, + { + platform: 'shopdunk' as const, + shopId: 'shopdunk-vn', + shopName: 'ShopDunk', + itemId: 'shopdunk-iphone-16-pro-max-256gb', + url: 'https://shopdunk.com/iphone-16-pro-max-256gb', + title: 'iPhone 16 Pro Max 256GB Chính hãng VN/A', + }, + { + platform: 'hacom' as const, + shopId: 'hacom-vn', + shopName: 'HACOM', + itemId: 'hacom-laptop-apple-macbook-air-m3-256gb', + url: 'https://hacom.vn/laptop-apple-macbook-air-m3-256gb', + title: 'Laptop Apple MacBook Air M3 13 inch 16GB 256GB', + }, + { + platform: 'clickbuy' as const, + shopId: 'cb-retail-vn', + shopName: 'Clickbuy', + itemId: 'cb-iphone-16-pro-max-256gb', + url: 'https://clickbuy.com.vn/iphone-16-pro-max-256gb', + title: 'iPhone 16 Pro Max 256GB Chính hãng VN/A', + }, + { + platform: 'viettelstore' as const, + shopId: 'vts-retail-vn', + shopName: 'Viettel Store', + itemId: 'vts-iphone-16-pro-max-256gb-pid341920', + url: 'https://viettelstore.vn/dien-thoai/iphone-16-pro-max-256gb-pid341920.html', + title: 'iPhone 16 Pro Max 256GB Chính hãng', + }, + { + platform: 'pico' as const, + shopId: 'pico-vn', + shopName: 'Pico', + itemId: 'pico-iphone-16-pro-max-256gb', + url: 'https://pico.vn/iphone-16-pro-max-256gb.html', + title: 'Điện thoại Apple iPhone 16 Pro Max 256GB', + }, + { + platform: 'mediamart' as const, + shopId: 'mediamart-vn', + shopName: 'MediaMart', + itemId: 'mm-dien-thoai-apple-iphone-16-pro-max-256gb', + url: 'https://mediamart.vn/smartphones/dien-thoai-apple-iphone-16-pro-max-256gb', + title: 'Điện thoại Apple iPhone 16 Pro Max 256GB', + }, + { + platform: 'memoryzone' as const, + shopId: 'memoryzone-vn', + shopName: 'MemoryZone', + itemId: 'mz-laptop-apple-macbook-air-m3-256gb', + url: 'https://memoryzone.com.vn/products/laptop-apple-macbook-air-m3-256gb', + title: 'Laptop Apple MacBook Air M3 13 inch 16GB 256GB', + }, + { + platform: 'anphatpc' as const, + shopId: 'anphatpc-vn', + shopName: 'An Phát Computer', + itemId: 'ap-laptop-apple-macbook-air-m3-256gb_5fid49201', + url: 'https://www.anphatpc.com.vn/laptop-apple-macbook-air-m3-256gb_id49201.html', + title: 'Laptop Apple MacBook Air M3 13 inch 16GB 256GB', + }, + ]; + for (const fx of wave1To3Fixtures) { + const { stub: waveStub, events: waveEvents } = createPipelineStubSupabase({ + hintRow: { id: 'master-wave-1850' }, + }); + const wavePipeline = new ShopeeIngestionPipeline({ + supabaseClient: waveStub, + apiKey: '', + }); + const waveRes = await wavePipeline.ingestProduct( + createBaseProduct({ + platform: fx.platform, + itemId: fx.itemId, + shopId: fx.shopId, + url: fx.url, + title: fx.title, + shop: { + shopId: fx.shopId, + name: fx.shopName, + isMall: true, + }, + }), + undefined, + { masterIdHint: 'master-wave-1850' } + ); + assert.equal(waveRes.platform, fx.platform); + assert.equal(waveEvents.productUpserts[0]?.platform, fx.platform); + assert.equal(waveEvents.productUpserts[0]?.platform_item_id, fx.itemId); + } + console.log(' ✅ [9/9] DOS/Rate#1850 Wave 1-3 12 retail platforms ingestion passed'); console.log('\n🎉 ALL SHOPEE INGESTION PIPELINE TESTS PASSED!'); } diff --git a/apps/importer/src/shopee/types.ts b/apps/importer/src/shopee/types.ts index 7fb2a5adf..dacd20cee 100644 --- a/apps/importer/src/shopee/types.ts +++ b/apps/importer/src/shopee/types.ts @@ -39,7 +39,19 @@ export type SupportedEcommercePlatform = | 'fptshop' | 'hoangha' | 'didongviet' - | 'phongvu'; + | 'phongvu' + | 'dienmayxanh' + | 'topzone' + | 'gearvn' + | 'nguyenkim' + | 'shopdunk' + | 'hacom' + | 'clickbuy' + | 'viettelstore' + | 'pico' + | 'mediamart' + | 'memoryzone' + | 'anphatpc'; /** * Reviewer metadata scraped alongside a review. What each platform exposes differs diff --git a/apps/web/e2e/deals-copy.spec.ts b/apps/web/e2e/deals-copy.spec.ts index 20380cdbb..3e711cb25 100644 --- a/apps/web/e2e/deals-copy.spec.ts +++ b/apps/web/e2e/deals-copy.spec.ts @@ -3,9 +3,9 @@ import { expect, test } from '@playwright/test'; // /deals reads in plain words in every locale: no "radar", "audit" or // "kèo thơm" labels, and sentence-case headings (DOS/Rate#659). const TITLES = { - vi: 'Deal đáng tiền nhất, đã lọc khuyến mãi ảo trên 10 sàn', - en: 'Best-value deals with fake sales filtered out (10 stores)', - cs: 'Nejvýhodnější nabídky bez falešných slev (10 obchodů)', + vi: 'Deal đáng tiền nhất, đã lọc khuyến mãi ảo trên 22 sàn', + en: 'Best-value deals with fake sales filtered out (22 stores)', + cs: 'Nejvýhodnější nabídky bez falešných slev (22 obchodů)', }; for (const [locale, title] of Object.entries(TITLES)) { diff --git a/apps/web/locales/cs.json b/apps/web/locales/cs.json index 80c2685aa..8d205bf79 100644 --- a/apps/web/locales/cs.json +++ b/apps/web/locales/cs.json @@ -178,7 +178,7 @@ "leadingDeltaNote": "(Náskok +{delta} b. v celkovém hodnocení)", "labScorePending": "Lab: nedostupné", "price60dStable": "Cena stabilní", - "radarRowTitle": "Cenový signál z 10 obchodů (pod mediánem, falešné slevy)", + "radarRowTitle": "Cenový signál z 22 obchodů (pod mediánem, falešné slevy)", "md1v1Heading": "Verdikt souboje 1v1: {nameA} vs {nameB}", "mdLeadingDevice": "Vedoucí zařízení", "mdScoreDelta": "Rozdíl {delta} b.", @@ -321,7 +321,7 @@ "addSameCategoryTitle": "Přidat {unit} ze stejné kategorie", "addCategorySlotTitle": "Přidat {category}", "remainingSlotsSub": "Volné pozice: {remaining}", - "radarRowMatrixTitle": "Cenový signál z 10 obchodů (nabídky pod mediánem a falešné slevy)", + "radarRowMatrixTitle": "Cenový signál z 22 obchodů (nabídky pod mediánem a falešné slevy)", "radarStableMedian": "Stabilní kolem tržního mediánu", "radarGenuineFloor": "Cenové dno napříč obchody (-{pct} % vs medián • {platform})", "radarBelowMedian": "Pod mediánem (-{pct} % • {platform})", @@ -335,7 +335,7 @@ "mdRowBatteryEnergy": "Baterie a energie", "csvColSpecGroup": "Skupina parametrů", "csvColTechCriterion": "Technické kritérium", - "csvRadarGroupTitle": "0. Cenový signál z 10 obchodů", + "csvRadarGroupTitle": "0. Cenový signál z 22 obchodů", "csvRadarVerdictRow": "Verdikt a cenová odchylka", "quickToggleLimitTitle": "Maximálně 4 zařízení v porovnávací tabulce", "quickToggleRemoveTitle": "Odebrat ze seznamu porovnání", @@ -677,12 +677,12 @@ "cloudSavedPartial": "Uloženo pouze {saved}/{total} upozornění do Rate Cloud{errorSuffix}. Ostatní zůstávají v prohlížeči.", "cloudSaveError": "Chyba připojení, upozornění se nepodařilo uložit do Rate Cloud.", "mdHeader": "### 🔔 Hlídané ceny na Rate.vn ({count, plural, one {# model} few {# modely} other {# modelů}})", - "mdTotalMin": "- **Celková hodnota portfolia (nejnižší cena z 10 platforem):** {price} ₫", + "mdTotalMin": "- **Celková hodnota portfolia (nejnižší cena z 22 platforem):** {price} ₫", "mdTotalTarget": "- **Celkový cílový rozpočet:** {price} ₫", "mdTotalSpread": "- **Celková úspora z rozdílů mezi platformami:** {price} ₫", "mdAvgRating": "- **Průměrné skóre JReviews v portfoliu:** ★ {rating}", "mdNoRating": "N/A", - "mdTableHead": "| Zařízení | Značka | Aktuální minimum | Cílová cena | Rozpětí 10 obchodů | Cenový signál | Stav | Nejlepší nabídka |", + "mdTableHead": "| Zařízení | Značka | Aktuální minimum | Cílová cena | Rozpětí 22 obchodů | Cenový signál | Stav | Nejlepší nabídka |", "mdSourcesCount": "{count, plural, one {# zdroj} few {# zdroje} other {# zdrojů}}", "mdStatusReached": "✅ Cíl dosažen", "mdStatusWatching": "⏳ Hlídáno", @@ -698,7 +698,7 @@ "compareSameCatBtn": "Porovnat {count} zařízení stejné kategorie", "kpiTotalMinLabel": "Hodnota portfolia (minimální ceny)", "kpiTotalTargetLabel": "Celkový cílový rozpočet", - "kpiSpreadSavingsLabel": "Úspora napříč 10 platformami", + "kpiSpreadSavingsLabel": "Úspora napříč 22 platformami", "kpiAvgRatingLabel": "Průměrné skóre JReviews", "kpiNoRating": "Zatím bez hodnocení", "cloudExplain": "Upozornění v Rate Cloud jsou propojena s přihlášeným účtem DOS ID a zasílána na e-mail při dosažení cílové ceny.", @@ -721,7 +721,7 @@ "radarGenuineBadge": "Minimum napříč obchody (-{pct} % oproti mediánu na {platform})", "radarBelowMedianBadge": "Pod mediánem (-{pct} % na {platform})", "radarFakeBadge": "{platform} umělé navýšení +{pct} %", - "radarSpreadBadge": "Rozpětí 10 platforem +{pct} % (rozdíl {vnd} ₫ mezi {cheapest} a {priciest})", + "radarSpreadBadge": "Rozpětí 22 platforem +{pct} % (rozdíl {vnd} ₫ mezi {cheapest} a {priciest})", "savedDateLabel": "Uloženo: {date}", "colCurrentLowest": "Aktuální nejnižší cena", "highestPriceSub": "Nejvyšší: {price} ₫", @@ -752,10 +752,10 @@ "sizeRequiredProductLink": "Otevřít stránku produktu" }, "deals": { - "metaTitle": "Výhodné nabídky ověřené v 10 obchodech | Rate.vn", - "metaDescription": "Najděte nejvýhodnější technologická zařízení podle rozpočtu a způsobu využití, ověřená porovnáním cen napříč obchody a filtrem falešných slev na 10 tržištích.", + "metaTitle": "Výhodné nabídky ověřené ve 22 obchodech | Rate.vn", + "metaDescription": "Najděte nejvýhodnější technologická zařízení podle rozpočtu a způsobu využití, ověřená porovnáním cen napříč obchody a filtrem falešných slev na 22 tržištích.", "pageEyebrow": "Ověřené slevy", - "pageTitle": "Nejvýhodnější nabídky bez falešných slev (10 obchodů)", + "pageTitle": "Nejvýhodnější nabídky bez falešných slev (22 obchodů)", "pageSubtitle": "Řadí zařízení podle poměru cena / skóre JReviews a úspor mezi oficiálními obchody. Podporuje export do Markdown, CSV a JSON.", "leaderboardBtn": "Žebříček JReviews", "inspectBtn": "Ověřit odkaz na falešnou slevu", @@ -770,7 +770,7 @@ "personaPhotography": "Fotoaparát a zvuk", "personaGaming": "Výkon a hraní her", "personaEndurance": "Výdrž baterie a nabíjení", - "radarMdHeader": "### 🔥 Ceny pod mediánem a falešné slevy v 10 obchodech - Rate.vn", + "radarMdHeader": "### 🔥 Ceny pod mediánem a falešné slevy ve 22 obchodech - Rate.vn", "radarMdMeta": "- **Kategorie:** {category} | **Analyzované klastry:** {clusters} ({offers, plural, one {# nabídka} few {# nabídky} other {# nabídek}})", "radarMdGenuineTitle": "#### 🟢 Pod mediánem napříč obchody", "radarMdGenuineTableHead": "| Zařízení | Obchod / prodejce | Aktuální cena | Medián nabídek | Skutečná úspora | Skóre JReviews |", @@ -784,7 +784,7 @@ "dealsMdUrlLine": "- **Zobrazit na Rate.vn:** {url}", "dealsMdTableHead": "| Pořadí | Zařízení | Značka | Skóre profilu | Skóre JReviews | Nejnižší cena | Úspora mezi obchody | Cenový signál |", "samePrice": "Stejná cena", - "filterBadge": "Nabídky ověřené v 10 obchodech", + "filterBadge": "Nabídky ověřené ve 22 obchodech", "showingCount": "Zobrazeno {visible} z {count} zařízení v rámci rozpočtu", "copiedMdBtn": "✓ Markdown zkopírován!", "copyMdBtn": "Kopírovat Markdown", @@ -795,7 +795,7 @@ "maxBudgetLabel": "Maximální rozpočet:", "maxBudgetAria": "Maximální rozpočet", "searchPlaceholder": "Rychlé hledání podle názvu modelu nebo značky (Apple, Samsung, Xiaomi, Sony...)", - "radarBannerBadge": "Ceny pod mediánem a upozornění na falešné slevy v 10 obchodech", + "radarBannerBadge": "Ceny pod mediánem a upozornění na falešné slevy ve 22 obchodech", "radarScannedSummary": "{offers, plural, one {Prohledána # nabídka} few {Prohledány # nabídky} other {Prohledáno # nabídek}} napříč {clusters, plural, one {# produktovým klastrem} other {# produktovými klastry}}", "copiedRadarMdBtn": "✓ Cenové signály zkopírovány", "copyRadarMdBtn": "Kopírovat cenové signály (Markdown)", @@ -815,7 +815,7 @@ "labNoScore": "Lab: N/A", "spreadSavingsBadge": "Úspora mezi platformami {amount} ₫", "costPerPointSub": "({cost} ₫ / bod JReviews)", - "audit10PlatformsLink": "Porovnat ceny v 10 obchodech →", + "audit10PlatformsLink": "Porovnat ceny ve 22 obchodech →", "radarBadgeGenuine": "🔥 Minimum napříč obchody (-{pct} %)", "radarBadgeBelowMedian": "✅ Pod mediánem (-{pct} %)", "radarBadgeFakeTrap": "🚨 Upozornění na falešnou slevu (+{pct} %)", @@ -850,12 +850,12 @@ "genuineDiscountBadge": "Uvedená cena odpovídá skutečné historii cen.", "implausiblyLowBadge": "Podezřele nízká cena", "implausiblyLowTitle": "Mnohem levnější než všechny ostatní obchody: může jít o padělek, příslušenství nebo návnadu. Před nákupem obchod pečlivě ověřte.", - "radarSectionBadge": "Cenové signály a rozdíly cen v 10 obchodech", - "openDealRadarLink": "Zobrazit nabídky z 10 obchodů →", + "radarSectionBadge": "Cenové signály a rozdíly cen ve 22 obchodech", + "openDealRadarLink": "Zobrazit nabídky z 22 obchodů →", "radarGenuinePill": "Nejnižší cena v obchodech: -{pct} % na {platform} ({price} ₫)", "radarBelowMedianPill": "Pod mediánem: -{pct} % na {platform} ({price} ₫)", "radarFakePill": "Falešná sleva: +{pct} % na {platform}", - "radarSpreadPill": "Rozdíl cen v 10 obchodech: +{pct} % ({vnd} ₫ mezi {cheapest} a {priciest})", + "radarSpreadPill": "Rozdíl cen ve 22 obchodech: +{pct} % ({vnd} ₫ mezi {cheapest} a {priciest})", "masterProductSection": "Nalezený produkt (10 skupin parametrů)", "userNoScore": "Kupující: bez skóre", "expertNoScore": "bez skóre", @@ -1007,7 +1007,7 @@ "profileRadarGenuineCount": "{count, plural, one {# nabídka} few {# nabídky} other {# nabídek}} pod mediánem", "profileRadarFakeCount": "{count} varování na falešnou slevu", "profileRadarZeroFake": "0 varování na falešnou slevu", - "openRadar10PlatformsBtn": "Slevy z 10 obchodů →", + "openRadar10PlatformsBtn": "Slevy z 22 obchodů →", "low60dAndMedian": "Tržní minimum: {min} ₫ • Medián: {median} ₫", "vsMedianBadge": "-{pct} % oproti mediánu", "inflatedOriginalPrice": "Uměle navýšená cena: {price} ₫", @@ -1141,7 +1141,7 @@ "noOffersYet": "K tomuto modelu zatím nejsou připojeny žádné nabídky e-shopů.", "competitorsBadge": "Produkty ze stejného segmentu ({category})", "competitorsTitle": "Alternativy pro {name}", - "dealHub10PlatformsBtn": "Slevy z 10 obchodů", + "dealHub10PlatformsBtn": "Slevy z 22 obchodů", "compareAllPeersBtn": "{count, plural, =2 {Porovnat oba modely} few {Porovnat všechny # modely} other {Porovnat všech # modelů}} →", "peerNoRating": "není", "cheaperByBadge": "O {amount} ₫ levnější", @@ -1340,7 +1340,7 @@ "compare10GroupsBtn": "Porovnat 10 skupin parametrů", "scoreDeltaLabel": "Rozdíl {delta} bodu", "view1v1ScoreBtn": "Zobrazit souboj 1v1", - "radarHomeBadge": "Cenové signály z 10 obchodů", + "radarHomeBadge": "Cenové signály z 22 obchodů", "radarHomeAnalyzed": "Automatické porovnání {offers, plural, one {# nabídky} other {# nabídek}} od {merchants, plural, one {# prodejce} other {# prodejců}} napříč {clusters, plural, one {# produktovým klastrem} other {# produktovými klastry}}", "radarHomeDealHubBtn": "Centrum slev", "radarHomeInspectBtn": "Ověřit odkaz na akci", @@ -1429,9 +1429,9 @@ "ep5Params": "q nebo url (odkaz Shopee/Lazada/Tiki nebo klíčové slovo)", "ep5Summary": "Analýza odkazu na produkt nebo obchod a automatické spárování s normalizovaným produktem a profilem důvěryhodnosti prodejce. Limit 30 požadavků za minutu na IP adresu (společný s /inspect); po jeho překročení přijde 429 s hlavičkou Retry-After.", "ep6Params": "q nebo url (URL nebo název modelu), price (viděná cena, volitelné), originalPrice (přeškrtnutá cena, volitelné)", - "ep6Summary": "Kontrola ceny a odkazu (/inspect): normalizuje URL na 10 tržištích a u prodejců, vyřazuje příslušenství a díly, porovná s mediánem ceny a vrátí 5stupňový verdikt. Limit 30 požadavků za minutu na IP adresu (společný s /lookup); po jeho překročení přijde 429 s hlavičkou Retry-After.", + "ep6Summary": "Kontrola ceny a odkazu (/inspect): normalizuje URL na 22 tržištích a u prodejců, vyřazuje příslušenství a díly, porovná s mediánem ceny a vrátí 5stupňový verdikt. Limit 30 požadavků za minutu na IP adresu (společný s /lookup); po jeho překročení přijde 429 s hlavičkou Retry-After.", "ep7Params": "url, title, price, originalPrice, skuText", - "ep7Summary": "Rychlý endpoint pro rozšíření prohlížeče Rate na 10 tržištích a u prodejců (Shopee, Lazada, Tiki, TikTok Shop, CellphoneS, TGDD, FPT Shop, Hoang Ha, Di Dong Viet, Phong Vu).", + "ep7Summary": "Rychlý endpoint pro rozšíření prohlížeče Rate na 22 tržištích a u prodejců (Shopee, Lazada, Tiki, TikTok Shop, CellphoneS, TGDD, Dien May Xanh, TopZone, FPT Shop, Hoang Ha, Di Dong Viet, Phong Vu, GearVN, Nguyen Kim, ShopDunk, HACOM, Clickbuy, Viettel Store, Pico, MediaMart, MemoryZone, An Phat).", "ep8Params": "Body JSON: { url, title, price, originalPrice?, platform?, selectedVariant?, userConsentOptIn: true }", "ep8Summary": "Přijímá anonymní signály o produktech z rozšíření prohlížeče se souhlasem uživatele: ověří strukturu, odstraní osobní identifikátory (PII) a zařadí je do fronty rate.crawl_jobs.", "ep9Params": "platform, officialOnly, min_trust, q, sort, limit", @@ -1513,7 +1513,7 @@ "pgPreset5Title": "Přímé srovnání (/versus)", "pgPreset5Desc": "Hodnotí dva modely stejné kategorie podle 5 kritérií (displej, výkon, fotoaparát, baterie, hodnota) s nastavitelnými vahami a cenovým rozdílem.", "pgPreset6Title": "Kontrola ceny a odkazu (/inspect)", - "pgPreset6Desc": "Kontrola libovolné URL nebo názvu modelu na 10 tržištích a u prodejců (Shopee, Lazada, Tiki, TikTok Shop, CellphoneS, TGDD, FPT Shop, Hoang Ha, Di Dong Viet, Phong Vu) s 5stupňovým verdiktem ceny.", + "pgPreset6Desc": "Kontrola libovolné URL nebo názvu modelu na 22 tržištích a u prodejců (Shopee, Lazada, Tiki, TikTok Shop, CellphoneS, TGDD, Dien May Xanh, TopZone, FPT Shop, Hoang Ha, Di Dong Viet, Phong Vu, GearVN, Nguyen Kim, ShopDunk, HACOM, Clickbuy, Viettel Store, Pico, MediaMart, MemoryZone, An Phat) s 5stupňovým verdiktem ceny.", "pgPreset7Title": "Vyhledávání pro rozšíření prohlížeče", "pgPreset7Desc": "Rychlý endpoint pro rozšíření prohlížeče Rate: normalizuje URL, vyřazuje příslušenství a díly a vrací 5stupňový verdikt ceny.", "pgPreset8Title": "Odeslání signálu o produktu (POST)", @@ -1524,8 +1524,8 @@ "pgPreset10Desc": "Hromadný dotaz na nejnižší aktuální ceny, historické mediány a stav skutečné/falešné slevy pro sledované produkty.", "pgPreset11Title": "Celkové statistiky platformy (/stats)", "pgPreset11Desc": "Vrací počet normalizovaných produktů, záznamů historie cen, podíl autentických recenzí a počty modelů podle kategorií.", - "pgPreset12Title": "Skutečné slevy a falešné výprodeje na 10 tržištích (/deals)", - "pgPreset12Desc": "Prochází ceny na 10 tržištích a hledá skutečně nízké ceny (genuineDeals) a nafouknuté původní ceny (fakeSaleTraps).", + "pgPreset12Title": "Skutečné slevy a falešné výprodeje na 22 tržištích (/deals)", + "pgPreset12Desc": "Prochází ceny na 22 tržištích a hledá skutečně nízké ceny (genuineDeals) a nafouknuté původní ceny (fakeSaleTraps).", "pgPreset13Title": "Specifikace OpenAPI 3.1.0 (/openapi.json)", "pgPreset13Desc": "Vrací specifikaci OpenAPI 3.1.0 ve formátu JSON pro endpointy Rate.vn REST API v1.", "authPublic": "Veřejný přístup (CORS)", @@ -1600,7 +1600,7 @@ "privacyS4Title": "4. Soukromé údaje prodejců", "privacyS4Desc": "Soukromé údaje prodejce (telefonní číslo, bankovní účet) jsou v polích, která veřejnost nemůže číst. Web i API mohou číst jen veřejná pole.", "privacyS5Title": "5. Rozšíření prohlížeče Rate.vn", - "privacyS5Desc": "Na stránkách produktů 10 podporovaných obchodů rozšíření posílá Rate.vn obchod, URL produktu bez parametrů, název produktu, ID položky a obchodu, zvolenou variantu, cenu a původní cenu, aby vyhledalo historii cen; toto vyhledávání je zapnuté ve výchozím stavu, jen čte a nepotřebuje účet. Text, který napíšete do vyhledávacího pole rozšíření, se také odešle k vyhledání. Jen když zvolíte \"Ano\" na stránce zobrazené při instalaci nebo zapnete \"Pomoc s hledáním nových produktů (jen když ji zapnete)\" v bočním panelu (ve výchozím stavu vypnuto), posílá také do fronty ke kontrole záznam o dané nabídce: obchod, URL bez parametrů, ID položky a obchodu, ID varianty (SKU), zvolenou variantu, cenu, původní cenu, stav a počet kusů skladem, čas, kdy jste cenu viděli, a verzi rozšíření, spolu s náhodným ID přispěvatele této instalace. Server jej ukládá s časem přijetí a s osoleným otiskem rozsahu vaší sítě (ne IP adresou), aby rozlišil nezávislé odesílatele; otisk se maže po 28 dnech a záznam po 180 dnech. Servery Rate.vn mohou nabídku v obchodě znovu ověřit a tato data sama veřejné ceny nemění. Vypnutím přispívání se ID přispěvatele i všechny odeslané záznamy smažou; pokud rozšíření odinstalujete bez vypnutí, smažou se po 180 dnech. Rozšíření neposílá účet, jméno, e-mail ani cookies, neotevírá stránky, které jste neotevřeli, a ve vašem prohlížeči ukládá jen adresu serveru, volbu opt-in, ID přispěvatele této instalace, dokud přispíváte, a mezipaměť platnou po dobu relace s produkty, které jste si prohlédli, vaším posledním hledáním, výsledky vyhledávání a dobou čekání na další vyhledání. Jako u každého webového požadavku server obdrží vaši IP adresu: kód Rate.vn ji používá v paměti pro limit požadavků za minutu a při přispívání k odvození výše uvedeného otisku rozsahu sítě; samotná IP adresa se nikdy neukládá a náš poskytovatel hostingu uchovává běžné přístupové záznamy po krátkou dobu.", + "privacyS5Desc": "Na stránkách produktů 22 podporovaných obchodů rozšíření posílá Rate.vn obchod, URL produktu bez parametrů, název produktu, ID položky a obchodu, zvolenou variantu, cenu a původní cenu, aby vyhledalo historii cen; toto vyhledávání je zapnuté ve výchozím stavu, jen čte a nepotřebuje účet. Text, který napíšete do vyhledávacího pole rozšíření, se také odešle k vyhledání. Jen když zvolíte \"Ano\" na stránce zobrazené při instalaci nebo zapnete \"Pomoc s hledáním nových produktů (jen když ji zapnete)\" v bočním panelu (ve výchozím stavu vypnuto), posílá také do fronty ke kontrole záznam o dané nabídce: obchod, URL bez parametrů, ID položky a obchodu, ID varianty (SKU), zvolenou variantu, cenu, původní cenu, stav a počet kusů skladem, čas, kdy jste cenu viděli, a verzi rozšíření, spolu s náhodným ID přispěvatele této instalace. Server jej ukládá s časem přijetí a s osoleným otiskem rozsahu vaší sítě (ne IP adresou), aby rozlišil nezávislé odesílatele; otisk se maže po 28 dnech a záznam po 180 dnech. Servery Rate.vn mohou nabídku v obchodě znovu ověřit a tato data sama veřejné ceny nemění. Vypnutím přispívání se ID přispěvatele i všechny odeslané záznamy smažou; pokud rozšíření odinstalujete bez vypnutí, smažou se po 180 dnech. Rozšíření neposílá účet, jméno, e-mail ani cookies, neotevírá stránky, které jste neotevřeli, a ve vašem prohlížeči ukládá jen adresu serveru, volbu opt-in, ID přispěvatele této instalace, dokud přispíváte, a mezipaměť platnou po dobu relace s produkty, které jste si prohlédli, vaším posledním hledáním, výsledky vyhledávání a dobou čekání na další vyhledání. Jako u každého webového požadavku server obdrží vaši IP adresu: kód Rate.vn ji používá v paměti pro limit požadavků za minutu a při přispívání k odvození výše uvedeného otisku rozsahu sítě; samotná IP adresa se nikdy neukládá a náš poskytovatel hostingu uchovává běžné přístupové záznamy po krátkou dobu.", "privacySide1Title": "Ověřte si otevřený kód", "privacySide1Desc": "Pravidla přístupu k datům a způsob ukládání hlasů jsou veřejné v repozitáři na GitHubu.", "privacySide1Btn": "Technická a API dokumentace", @@ -1634,7 +1634,7 @@ "contactSeoDesc": "Nahlaste falešné slevy nebo falešné recenze, nebo požádejte o přezkoumání důvěryhodnosti prodejce na Rate.vn.", "contactHeroBadge": "Kontakt a zpětná vazba", "contactHeroTitle": "Rychlá inspekce a nahlášení podezřelého obchodu", - "contactHeroDesc": "Vložte níže odkaz na produkt nebo obchod ze Shopee, Lazada, Tiki, TikTok Shop, CellphoneS, TGDD, FPT Shop, Hoang Ha, Di Dong Viet nebo Phong Vu a zobrazte historii cen, nebo odkaz pošlete Rate.vn ke kontrole.", + "contactHeroDesc": "Vložte níže odkaz na produkt nebo obchod ze 22 podporovaných obchodů (Shopee, Lazada, Tiki, TikTok Shop, CellphoneS, TGDD, Dien May Xanh, TopZone, FPT Shop, Hoang Ha, Di Dong Viet, Phong Vu, GearVN, Nguyen Kim, ShopDunk, HACOM, Clickbuy, Viettel Store, Pico, MediaMart, MemoryZone, An Phat) a zobrazte historii cen, nebo odkaz pošlete Rate.vn ke kontrole.", "contactCard1Title": "1. Nahlášení falešných slev a falešných recenzí", "contactCard1Desc": "Když uvidíte původní cenu navýšenou před výprodejem, vložte odkaz na produkt do kontroly na této stránce. Když uvidíte falešné účty opakující šablonové recenze, přihlaste se a u té recenze na stránce produktu klikněte na \"Nahlásit\".", "contactCard1Btn": "Přejít do katalogu produktů →", @@ -1673,7 +1673,7 @@ "quarantineOutcome": { "accepted": "Odkaz je ve frontě ke kontrole. Zadaná cena se nezveřejní přímo.", "noConsent": "Před odesláním zaškrtněte souhlas se sdílením.", - "invalidUrl": "Nejde o stránku produktu z jednoho z 10 podporovaných obchodů. Otevřete stránku produktu a zkopírujte odkaz znovu.", + "invalidUrl": "Nejde o stránku produktu z jednoho z 22 podporovaných obchodů. Otevřete stránku produktu a zkopírujte odkaz znovu.", "platformPending": "Rate.vn zatím nepřijímá odkazy z tohoto obchodu. Zkuste to prosím později.", "invalidPrice": "Aktuální cena není platná. Zadejte částku v dongech.", "accessory": "Vypadá to na příslušenství nebo díl. Rate.vn sleduje jen ceny zařízení.", @@ -1865,10 +1865,10 @@ "sortByPrefix": "Řazení: {label}", "radarBannerBadge": "Ceny pod mediánem a falešné slevy ({title})", "radarAnalyzedSub": "{count, plural, one {Zkontrolována # nabídka} few {Zkontrolovány # nabídky} other {Zkontrolováno # nabídek}}", - "viewAllRadarBtn": "Zobrazit všechny nabídky z 10 obchodů", + "viewAllRadarBtn": "Zobrazit všechny nabídky z 22 obchodů", "vsMedianBadge": "-{pct} % oproti mediánu", "fakeMarkupBadge": "Nadsazeno +{pct} %", - "spreadHeader": "Největší cenový rozptyl na 10 tržištích ({title}):", + "spreadHeader": "Největší cenový rozptyl na 22 tržištích ({title}):", "spreadSub": "Ušetřete miliony VND výběrem správného tržiště", "spreadDiffBadge": "Rozdíl +{pct} % ({amount} ₫)", "emptySyncingTitle": "Kategorie \"{title}\" čeká na synchronizaci normalizovaných dat", diff --git a/apps/web/locales/en.json b/apps/web/locales/en.json index 5a68f4942..dab328403 100644 --- a/apps/web/locales/en.json +++ b/apps/web/locales/en.json @@ -178,7 +178,7 @@ "leadingDeltaNote": "(+{delta} pts lead on overall stars)", "labScorePending": "Lab: pending", "price60dStable": "Price stable", - "radarRowTitle": "10-store price signal (below-median deals, fake sales)", + "radarRowTitle": "22-store price signal (below-median deals, fake sales)", "md1v1Heading": "1v1 verdict: {nameA} vs {nameB}", "mdLeadingDevice": "Leading device", "mdScoreDelta": "Delta {delta} pts", @@ -321,7 +321,7 @@ "addSameCategoryTitle": "Add same-category {unit}", "addCategorySlotTitle": "Add {category}", "remainingSlotsSub": "{remaining} same-category slots available", - "radarRowMatrixTitle": "Price signal across 10 stores (below-median deals and fake sales)", + "radarRowMatrixTitle": "Price signal across 22 stores (below-median deals and fake sales)", "radarStableMedian": "Stable near the market median", "radarGenuineFloor": "Cross-platform price floor (-{pct}% vs median • {platform})", "radarBelowMedian": "Below median (-{pct}% • {platform})", @@ -335,7 +335,7 @@ "mdRowBatteryEnergy": "Battery and power", "csvColSpecGroup": "Spec group", "csvColTechCriterion": "Technical criterion", - "csvRadarGroupTitle": "0. Price signal across 10 stores", + "csvRadarGroupTitle": "0. Price signal across 22 stores", "csvRadarVerdictRow": "Verdict and price gap", "quickToggleLimitTitle": "Maximum 4 devices in comparison table", "quickToggleRemoveTitle": "Remove from comparison list", @@ -677,12 +677,12 @@ "cloudSavedPartial": "Saved {saved}/{total} alerts to Rate Cloud{errorSuffix}. Remaining alerts are kept in this browser.", "cloudSaveError": "Network error while syncing alerts to Rate Cloud.", "mdHeader": "### 🔔 Price watchlist on Rate.vn ({count, plural, one {# model} other {# models}})", - "mdTotalMin": "- **Total value (lowest price across 10 stores):** {price} ₫", + "mdTotalMin": "- **Total value (lowest price across 22 stores):** {price} ₫", "mdTotalTarget": "- **Total target budget:** {price} ₫", "mdTotalSpread": "- **Total cross-store savings:** {price} ₫", "mdAvgRating": "- **Average JReviews score:** ★ {rating}", "mdNoRating": "N/A", - "mdTableHead": "| Device | Brand | Current lowest | Target price | 10-store gap | Price signal | Status | Best offer |", + "mdTableHead": "| Device | Brand | Current lowest | Target price | 22-store gap | Price signal | Status | Best offer |", "mdSourcesCount": "{count, plural, one {# source} other {# sources}}", "mdStatusReached": "✅ Target reached", "mdStatusWatching": "⏳ Watching", @@ -698,7 +698,7 @@ "compareSameCatBtn": "Compare {count, plural, one {# same-category device} other {# same-category devices}}", "kpiTotalMinLabel": "Total at lowest prices", "kpiTotalTargetLabel": "Total target budget", - "kpiSpreadSavingsLabel": "Savings across 10 stores", + "kpiSpreadSavingsLabel": "Savings across 22 stores", "kpiAvgRatingLabel": "Average JReviews score", "kpiNoRating": "No score yet", "cloudExplain": "Rate Cloud alerts are linked to your signed-in DOS ID account and emailed when prices hit your target threshold.", @@ -721,7 +721,7 @@ "radarGenuineBadge": "Cross-platform low (-{pct}% vs median on {platform})", "radarBelowMedianBadge": "Below median (-{pct}% on {platform})", "radarFakeBadge": "{platform} fake markup +{pct}%", - "radarSpreadBadge": "Price gap across 10 stores +{pct}% ({vnd} ₫ between {cheapest} and {priciest})", + "radarSpreadBadge": "Price gap across 22 stores +{pct}% ({vnd} ₫ between {cheapest} and {priciest})", "savedDateLabel": "Saved on: {date}", "colCurrentLowest": "Current lowest price", "highestPriceSub": "Highest: {price} ₫", @@ -752,10 +752,10 @@ "sizeRequiredProductLink": "Open the product page" }, "deals": { - "metaTitle": "Best-value tech deals, checked across 10 stores | Rate.vn", - "metaDescription": "Find the best-value tech devices by budget and usage persona, cross-checked against cross-platform prices and fake discount filters across 10 marketplaces.", + "metaTitle": "Best-value tech deals, checked across 22 stores | Rate.vn", + "metaDescription": "Find the best-value tech devices by budget and usage persona, cross-checked against cross-platform prices and fake discount filters across 22 marketplaces.", "pageEyebrow": "Verified deal discovery", - "pageTitle": "Best-value deals with fake sales filtered out (10 stores)", + "pageTitle": "Best-value deals with fake sales filtered out (22 stores)", "pageSubtitle": "Ranks devices by Price-to-JReviews Score efficiency and cross-platform arbitrage savings across official stores. Supports Markdown, CSV, and JSON exports.", "leaderboardBtn": "JReviews Leaderboard", "inspectBtn": "Check a fake-discount link", @@ -770,7 +770,7 @@ "personaPhotography": "Camera and audio", "personaGaming": "Performance and gaming", "personaEndurance": "Battery and fast charging", - "radarMdHeader": "### 🔥 Below-median prices and fake-sale warnings (10 stores) - Rate.vn", + "radarMdHeader": "### 🔥 Below-median prices and fake-sale warnings (22 stores) - Rate.vn", "radarMdMeta": "- **Category:** {category} | **Clusters analyzed:** {clusters} ({offers, plural, one {# listing} other {# listings}})", "radarMdGenuineTitle": "#### 🟢 Below the cross-store median", "radarMdGenuineTableHead": "| Device | Store / seller | Current price | Listing median | Real savings | JReviews score |", @@ -784,7 +784,7 @@ "dealsMdUrlLine": "- **View on Rate.vn:** {url}", "dealsMdTableHead": "| Rank | Device | Brand | Priority score | JReviews score | Lowest price | Cross-store savings | Price signal |", "samePrice": "Uniform price", - "filterBadge": "Deals checked across 10 stores", + "filterBadge": "Deals checked across 22 stores", "showingCount": "Showing {visible} of {count, plural, one {# device} other {# devices}} within your budget", "copiedMdBtn": "✓ Markdown Copied!", "copyMdBtn": "Copy Markdown", @@ -795,7 +795,7 @@ "maxBudgetLabel": "Maximum budget:", "maxBudgetAria": "Maximum budget", "searchPlaceholder": "Quick search by model name or brand (Apple, Samsung, Xiaomi, Sony...)", - "radarBannerBadge": "Below-median prices and fake-sale warnings across 10 stores", + "radarBannerBadge": "Below-median prices and fake-sale warnings across 22 stores", "radarScannedSummary": "Scanned {offers, plural, one {# merchant listing} other {# merchant listings}} across {clusters, plural, one {# product cluster} other {# product clusters}}", "copiedRadarMdBtn": "✓ Price signals copied", "copyRadarMdBtn": "Copy price signals (Markdown)", @@ -815,7 +815,7 @@ "labNoScore": "Lab: N/A", "spreadSavingsBadge": "Cross-platform savings {amount} ₫", "costPerPointSub": "({cost} ₫ / JReviews pt)", - "audit10PlatformsLink": "Compare prices across 10 stores →", + "audit10PlatformsLink": "Compare prices across 22 stores →", "radarBadgeGenuine": "🔥 Cross-platform low (-{pct}%)", "radarBadgeBelowMedian": "✅ Below median (-{pct}%)", "radarBadgeFakeTrap": "🚨 Fake sale warning (+{pct}%)", @@ -850,12 +850,12 @@ "genuineDiscountBadge": "The listed price matches the real price history.", "implausiblyLowBadge": "Suspiciously low price", "implausiblyLowTitle": "Far cheaper than every other store: possibly a counterfeit, an accessory or a bait listing. Check the shop carefully before buying.", - "radarSectionBadge": "Price signals and price gaps across 10 stores", - "openDealRadarLink": "See deals across 10 stores →", + "radarSectionBadge": "Price signals and price gaps across 22 stores", + "openDealRadarLink": "See deals across 22 stores →", "radarGenuinePill": "Lowest across stores: -{pct}% on {platform} ({price} ₫)", "radarBelowMedianPill": "Below median: -{pct}% on {platform} ({price} ₫)", "radarFakePill": "Fake discount: +{pct}% on {platform}", - "radarSpreadPill": "Price gap across 10 stores: +{pct}% ({vnd} ₫ between {cheapest} and {priciest})", + "radarSpreadPill": "Price gap across 22 stores: +{pct}% ({vnd} ₫ between {cheapest} and {priciest})", "masterProductSection": "Matched product (10 spec groups)", "userNoScore": "Buyers: no score", "expertNoScore": "no score", @@ -1007,7 +1007,7 @@ "profileRadarGenuineCount": "{count, plural, one {# below-median listing} other {# below-median listings}}", "profileRadarFakeCount": "{count, plural, one {# fake-sale markup alert} other {# fake-sale markup alerts}}", "profileRadarZeroFake": "0 fake-sale markup alerts", - "openRadar10PlatformsBtn": "Deals across 10 stores →", + "openRadar10PlatformsBtn": "Deals across 22 stores →", "low60dAndMedian": "Market low: {min} ₫ • Median: {median} ₫", "vsMedianBadge": "-{pct}% vs median", "inflatedOriginalPrice": "Inflated list price: {price} ₫", @@ -1141,7 +1141,7 @@ "noOffersYet": "No marketplace listings are currently linked to this model.", "competitorsBadge": "Same-segment products ({category})", "competitorsTitle": "Alternatives to {name}", - "dealHub10PlatformsBtn": "Deals across 10 stores", + "dealHub10PlatformsBtn": "Deals across 22 stores", "compareAllPeersBtn": "{count, plural, =2 {Compare both models} other {Compare all # models}} →", "peerNoRating": "N/A", "cheaperByBadge": "{amount} ₫ cheaper", @@ -1340,7 +1340,7 @@ "compare10GroupsBtn": "Compare 10 spec groups", "scoreDeltaLabel": "{delta} pts apart", "view1v1ScoreBtn": "See the 1v1 breakdown", - "radarHomeBadge": "Price signals across 10 stores", + "radarHomeBadge": "Price signals across 22 stores", "radarHomeAnalyzed": "Automatically cross-checking {offers, plural, one {# listing} other {# listings}} from {merchants, plural, one {# merchant} other {# merchants}} across {clusters, plural, one {# product cluster} other {# product clusters}}", "radarHomeDealHubBtn": "Deal hub", "radarHomeInspectBtn": "Check a sale link", @@ -1429,9 +1429,9 @@ "ep5Params": "q or url (Shopee/Lazada/Tiki link or keyword)", "ep5Summary": "Read a product or shop link and match it to a normalized product and the seller's trust profile. Limited to 30 requests per minute per IP (shared with /inspect); past the limit the answer is a 429 with a Retry-After header.", "ep6Params": "q or url (URL or model name), price (price you see, optional), originalPrice (struck-through price, optional)", - "ep6Summary": "Price and link check (/inspect): normalizes URLs across 10 marketplaces and retailers, filters out accessories and parts, compares against the median price and returns a 5-level price verdict. Limited to 30 requests per minute per IP (shared with /lookup); past the limit the answer is a 429 with a Retry-After header.", + "ep6Summary": "Price and link check (/inspect): normalizes URLs across 22 marketplaces and retailers, filters out accessories and parts, compares against the median price and returns a 5-level price verdict. Limited to 30 requests per minute per IP (shared with /lookup); past the limit the answer is a 429 with a Retry-After header.", "ep7Params": "url, title, price, originalPrice, skuText", - "ep7Summary": "Fast endpoint for the Rate browser extension across 10 marketplaces and retailers (Shopee, Lazada, Tiki, TikTok Shop, CellphoneS, TGDD, FPT Shop, Hoang Ha, Di Dong Viet, Phong Vu).", + "ep7Summary": "Fast endpoint for the Rate browser extension across 22 marketplaces and retailers (Shopee, Lazada, Tiki, TikTok Shop, CellphoneS, TGDD, Dien May Xanh, TopZone, FPT Shop, Hoang Ha, Di Dong Viet, Phong Vu, GearVN, Nguyen Kim, ShopDunk, HACOM, Clickbuy, Viettel Store, Pico, MediaMart, MemoryZone, An Phat).", "ep8Params": "Body JSON: { url, title, price, originalPrice?, platform?, selectedVariant?, userConsentOptIn: true }", "ep8Summary": "Accepts anonymous product signals from the browser extension once the user has consented: validates the shape, strips personal identifiers (PII) and queues them in rate.crawl_jobs.", "ep9Params": "platform, officialOnly, min_trust, q, sort, limit", @@ -1513,7 +1513,7 @@ "pgPreset5Title": "Head to head (/versus)", "pgPreset5Desc": "Scores two same-category models on 5 criteria (display, performance, camera, battery, value), with adjustable weights and the price gap.", "pgPreset6Title": "Price and link check (/inspect)", - "pgPreset6Desc": "Check any product URL or model name across 10 marketplaces and retailers (Shopee, Lazada, Tiki, TikTok Shop, CellphoneS, TGDD, FPT Shop, Hoang Ha, Di Dong Viet, Phong Vu) and get a 5-level price verdict.", + "pgPreset6Desc": "Check any product URL or model name across 22 marketplaces and retailers (Shopee, Lazada, Tiki, TikTok Shop, CellphoneS, TGDD, Dien May Xanh, TopZone, FPT Shop, Hoang Ha, Di Dong Viet, Phong Vu, GearVN, Nguyen Kim, ShopDunk, HACOM, Clickbuy, Viettel Store, Pico, MediaMart, MemoryZone, An Phat) and get a 5-level price verdict.", "pgPreset7Title": "Browser extension lookup", "pgPreset7Desc": "Fast endpoint for the Rate browser extension: normalizes URLs, filters out accessories and parts, and returns a 5-level price verdict.", "pgPreset8Title": "Send a product signal (POST)", @@ -1524,8 +1524,8 @@ "pgPreset10Desc": "Get current lowest prices, median prices and real-or-fake discount verdicts for watched products in one call.", "pgPreset11Title": "Platform numbers (/stats)", "pgPreset11Desc": "Returns master product counts, price observations, the share of genuine reviews and models per category.", - "pgPreset12Title": "Real deals and fake sales on 10 marketplaces (/deals)", - "pgPreset12Desc": "Scans prices across 10 marketplaces to find genuinely low prices (genuineDeals) and inflated original prices (fakeSaleTraps).", + "pgPreset12Title": "Real deals and fake sales on 22 marketplaces (/deals)", + "pgPreset12Desc": "Scans prices across 22 marketplaces to find genuinely low prices (genuineDeals) and inflated original prices (fakeSaleTraps).", "pgPreset13Title": "OpenAPI 3.1.0 spec (/openapi.json)", "pgPreset13Desc": "Returns the OpenAPI 3.1.0 spec in JSON for the Rate.vn REST API v1 endpoints.", "authPublic": "Public (CORS)", @@ -1600,7 +1600,7 @@ "privacyS4Title": "4. Sellers' private details", "privacyS4Desc": "A seller's private details (phone number, bank account) are kept in fields the public cannot read. The website and the API can only read the public fields.", "privacyS5Title": "5. The Rate.vn browser extension", - "privacyS5Desc": "On product pages of the 10 supported stores, the extension sends Rate.vn the store, the product URL without its parameters, the product title, the item and shop ids, the selected variant, the price and the original price to look up price history; this lookup is on by default, read-only and needs no account. Text you type into the extension's search box is also sent to look it up. Only if you choose \"Yes\" on the page shown at install or turn on \"Help find new products (only when you turn it on)\" in the side panel (off by default) does it also send an observation of that listing to a moderation queue: the store, the URL without its parameters, the item and shop ids, the variant ID (SKU), the selected variant, the price, the original price, the stock status and quantity, the time you saw the price and the extension version, with a random contributor ID for this install. The server stores it with the time it was received and a salted hash of your network range (not your IP) to tell independent senders apart; the hash is deleted after 28 days and the observation after 180 days. Rate.vn's servers may re-check that listing on the store, and this data does not change public prices by itself. Turning contributions off deletes the contributor ID and every observation sent with it; if you uninstall without turning it off, they are deleted after 180 days. The extension sends no account, name, email or cookies, opens no page you did not open, and keeps only the server address, the opt-in choice, the contributor ID while you contribute, and a session-only cache of the products you viewed, your latest search, their lookup results and a lookup wait time in your browser. Like any web request, the server receives your IP address: Rate.vn's code uses it in memory for a per-minute request limit and, when you contribute, to derive the network-range hash above; the IP itself is never stored, and our hosting provider keeps standard access logs for a short time.", + "privacyS5Desc": "On product pages of the 22 supported stores, the extension sends Rate.vn the store, the product URL without its parameters, the product title, the item and shop ids, the selected variant, the price and the original price to look up price history; this lookup is on by default, read-only and needs no account. Text you type into the extension's search box is also sent to look it up. Only if you choose \"Yes\" on the page shown at install or turn on \"Help find new products (only when you turn it on)\" in the side panel (off by default) does it also send an observation of that listing to a moderation queue: the store, the URL without its parameters, the item and shop ids, the variant ID (SKU), the selected variant, the price, the original price, the stock status and quantity, the time you saw the price and the extension version, with a random contributor ID for this install. The server stores it with the time it was received and a salted hash of your network range (not your IP) to tell independent senders apart; the hash is deleted after 28 days and the observation after 180 days. Rate.vn's servers may re-check that listing on the store, and this data does not change public prices by itself. Turning contributions off deletes the contributor ID and every observation sent with it; if you uninstall without turning it off, they are deleted after 180 days. The extension sends no account, name, email or cookies, opens no page you did not open, and keeps only the server address, the opt-in choice, the contributor ID while you contribute, and a session-only cache of the products you viewed, your latest search, their lookup results and a lookup wait time in your browser. Like any web request, the server receives your IP address: Rate.vn's code uses it in memory for a per-minute request limit and, when you contribute, to derive the network-range hash above; the IP itself is never stored, and our hosting provider keeps standard access logs for a short time.", "privacySide1Title": "Check the open code", "privacySide1Desc": "The data access rules and how votes are stored are public in the GitHub repository.", "privacySide1Btn": "Technical and API docs", @@ -1634,7 +1634,7 @@ "contactSeoDesc": "Report fake discounts or fake reviews, or ask for a seller trust review on Rate.vn.", "contactHeroBadge": "Contact & feedback", "contactHeroTitle": "Quick URL inspection & suspicious merchant reporting", - "contactHeroDesc": "Paste a product or shop link from Shopee, Lazada, Tiki, TikTok Shop, CellphoneS, TGDD, FPT Shop, Hoang Ha, Di Dong Viet or Phong Vu below to see its price history, or send the link for Rate.vn to check.", + "contactHeroDesc": "Paste a product or shop link from 22 supported marketplaces and retailers (Shopee, Lazada, Tiki, TikTok Shop, CellphoneS, TGDD, Dien May Xanh, TopZone, FPT Shop, Hoang Ha, Di Dong Viet, Phong Vu, GearVN, Nguyen Kim, ShopDunk, HACOM, Clickbuy, Viettel Store, Pico, MediaMart, MemoryZone, An Phat) below to see its price history, or send the link for Rate.vn to check.", "contactCard1Title": "1. Report fake discounts and fake reviews", "contactCard1Desc": "If you see a list price inflated before a sale, paste the product link into the checker on this page. If you see fake accounts repeating template reviews, sign in and click \"Report\" on that review on the product page.", "contactCard1Btn": "Go to product catalog →", @@ -1673,7 +1673,7 @@ "quarantineOutcome": { "accepted": "The link is in the queue for checking. The price you entered is not published directly.", "noConsent": "Please tick the sharing consent box before sending.", - "invalidUrl": "This is not a product page from one of the 10 supported stores. Open the product page and copy its link again.", + "invalidUrl": "This is not a product page from one of the 22 supported stores. Open the product page and copy its link again.", "platformPending": "Rate.vn is not taking links from this store yet. Please try again later.", "invalidPrice": "The current price is not valid. Enter the amount in dong.", "accessory": "This looks like an accessory or a part. Rate.vn only tracks device prices.", @@ -1865,10 +1865,10 @@ "sortByPrefix": "Sort: {label}", "radarBannerBadge": "Below-median prices and fake-sale warnings ({title})", "radarAnalyzedSub": "Checked {count, plural, one {# store listing} other {# store listings}}", - "viewAllRadarBtn": "See all deals across 10 stores", + "viewAllRadarBtn": "See all deals across 22 stores", "vsMedianBadge": "-{pct}% vs median", "fakeMarkupBadge": "Inflated +{pct}%", - "spreadHeader": "Largest price gap across 10 marketplaces ({title}):", + "spreadHeader": "Largest price gap across 22 marketplaces ({title}):", "spreadSub": "Save millions of VND by choosing the right marketplace", "spreadDiffBadge": "Spread +{pct}% ({amount} ₫)", "emptySyncingTitle": "Category \"{title}\" is awaiting normalized product data sync", diff --git a/apps/web/locales/vi.json b/apps/web/locales/vi.json index fc2d20cd6..f720595be 100644 --- a/apps/web/locales/vi.json +++ b/apps/web/locales/vi.json @@ -178,7 +178,7 @@ "leadingDeltaNote": "(Chênh lệch +{delta} điểm sao tổng)", "labScorePending": "Lab: chưa có", "price60dStable": "Giá ổn định", - "radarRowTitle": "Tín hiệu giá 10 sàn (deal dưới trung vị, giảm giá ảo)", + "radarRowTitle": "Tín hiệu giá 22 sàn (deal dưới trung vị, giảm giá ảo)", "md1v1Heading": "Kết luận so sánh 1v1: {nameA} vs {nameB}", "mdLeadingDevice": "Thiết bị dẫn trước", "mdScoreDelta": "Chênh lệch {delta} điểm", @@ -321,7 +321,7 @@ "addSameCategoryTitle": "Thêm {unit} cùng danh mục", "addCategorySlotTitle": "Thêm {category}", "remainingSlotsSub": "Còn trống {remaining} vị trí cùng nhóm", - "radarRowMatrixTitle": "Tín hiệu giá trên 10 sàn (deal dưới giá trung vị và giảm giá ảo)", + "radarRowMatrixTitle": "Tín hiệu giá trên 22 sàn (deal dưới giá trung vị và giảm giá ảo)", "radarStableMedian": "Ổn định quanh trung vị thị trường", "radarGenuineFloor": "Đáy giá đa sàn (-{pct}% so với trung vị • {platform})", "radarBelowMedian": "Dưới giá trung vị (-{pct}% • {platform})", @@ -335,7 +335,7 @@ "mdRowBatteryEnergy": "Pin và năng lượng", "csvColSpecGroup": "Nhóm thông số", "csvColTechCriterion": "Tiêu chí kỹ thuật", - "csvRadarGroupTitle": "0. Tín hiệu giá trên 10 sàn", + "csvRadarGroupTitle": "0. Tín hiệu giá trên 22 sàn", "csvRadarVerdictRow": "Kết luận và độ lệch giá", "quickToggleLimitTitle": "Tối đa 4 thiết bị trong bảng so sánh", "quickToggleRemoveTitle": "Bỏ khỏi danh sách so sánh", @@ -677,12 +677,12 @@ "cloudSavedPartial": "Chỉ lưu được {saved}/{total} cảnh báo lên Rate Cloud{errorSuffix}. Các cảnh báo còn lại vẫn nằm trên trình duyệt này.", "cloudSaveError": "Lỗi kết nối, chưa lưu được cảnh báo lên Rate Cloud.", "mdHeader": "### 🔔 Danh sách theo dõi giá trên Rate.vn ({count} mẫu)", - "mdTotalMin": "- **Tổng giá trị (giá thấp nhất trên 10 sàn):** {price} ₫", + "mdTotalMin": "- **Tổng giá trị (giá thấp nhất trên 22 sàn):** {price} ₫", "mdTotalTarget": "- **Tổng ngân sách mục tiêu:** {price} ₫", "mdTotalSpread": "- **Tổng tiết kiệm giữa các sàn:** {price} ₫", "mdAvgRating": "- **Điểm JReviews trung bình danh mục:** ★ {rating}", "mdNoRating": "chưa có", - "mdTableHead": "| Thiết bị | Hãng | Giá thấp nhất hiện tại | Giá mục tiêu | Chênh lệch 10 sàn | Tín hiệu giá | Trạng thái | Deal tốt nhất |", + "mdTableHead": "| Thiết bị | Hãng | Giá thấp nhất hiện tại | Giá mục tiêu | Chênh lệch 22 sàn | Tín hiệu giá | Trạng thái | Deal tốt nhất |", "mdSourcesCount": "{count} nguồn", "mdStatusReached": "✅ Đạt mục tiêu", "mdStatusWatching": "⏳ Đang canh", @@ -698,7 +698,7 @@ "compareSameCatBtn": "So sánh {count} máy cùng danh mục", "kpiTotalMinLabel": "Tổng giá trị danh mục (Giá đáy)", "kpiTotalTargetLabel": "Tổng ngân sách mục tiêu", - "kpiSpreadSavingsLabel": "Tiết kiệm giữa 10 sàn", + "kpiSpreadSavingsLabel": "Tiết kiệm giữa 22 sàn", "kpiAvgRatingLabel": "Điểm JReviews trung bình danh mục", "kpiNoRating": "Chưa có", "cloudExplain": "Cảnh báo trên Rate Cloud gắn với tài khoản DOS ID đã đăng nhập và gửi tới email của tài khoản đó khi giá chạm ngưỡng mục tiêu.", @@ -721,7 +721,7 @@ "radarGenuineBadge": "Đáy giá đa sàn (-{pct}% so trung vị tại {platform})", "radarBelowMedianBadge": "Dưới giá trung vị (-{pct}% tại {platform})", "radarFakeBadge": "Cảnh báo sàn {platform} kê khống +{pct}%", - "radarSpreadBadge": "Độ lệch 10 sàn +{pct}% (Chênh {vnd} ₫ giữa {cheapest} & {priciest})", + "radarSpreadBadge": "Độ lệch 22 sàn +{pct}% (Chênh {vnd} ₫ giữa {cheapest} & {priciest})", "savedDateLabel": "Lưu ngày: {date}", "colCurrentLowest": "Giá hiện tại thấp nhất", "highestPriceSub": "Cao nhất: {price} ₫", @@ -752,10 +752,10 @@ "sizeRequiredProductLink": "Mở trang sản phẩm" }, "deals": { - "metaTitle": "Deal công nghệ đã kiểm tra trên 10 sàn | Rate.vn", - "metaDescription": "Tìm kiếm thiết bị công nghệ đáng tiền nhất theo ngân sách và nhu cầu sử dụng, đã đối chiếu giá giữa các sàn và lọc khuyến mãi ảo trên 10 sàn TMĐT.", + "metaTitle": "Deal công nghệ đã kiểm tra trên 22 sàn | Rate.vn", + "metaDescription": "Tìm kiếm thiết bị công nghệ đáng tiền nhất theo ngân sách và nhu cầu sử dụng, đã đối chiếu giá giữa các sàn và lọc khuyến mãi ảo trên 22 sàn và đại lý.", "pageEyebrow": "Săn deal đã kiểm chứng", - "pageTitle": "Deal đáng tiền nhất, đã lọc khuyến mãi ảo trên 10 sàn", + "pageTitle": "Deal đáng tiền nhất, đã lọc khuyến mãi ảo trên 22 sàn", "pageSubtitle": "Xếp hạng thiết bị theo chỉ số hiệu suất giá / điểm JReviews và biên độ tiết kiệm giữa các sàn chính hãng. Hỗ trợ xuất Markdown, CSV và JSON.", "leaderboardBtn": "Bảng xếp hạng JReviews", "inspectBtn": "Kiểm tra link giảm giá ảo", @@ -770,7 +770,7 @@ "personaPhotography": "Camera và âm thanh", "personaGaming": "Hiệu năng và chơi game", "personaEndurance": "Pin trâu và sạc nhanh", - "radarMdHeader": "### 🔥 Giá dưới trung vị các sàn và cảnh báo giá gốc bị nâng khống (10 sàn) - Rate.vn", + "radarMdHeader": "### 🔥 Giá dưới trung vị các sàn và cảnh báo giá gốc bị nâng khống (22 sàn) - Rate.vn", "radarMdMeta": "- **Ngành hàng:** {category} | **Cụm sản phẩm phân tích:** {clusters} ({offers} tin bán)", "radarMdGenuineTitle": "#### 🟢 Rẻ hơn giá trung vị các sàn", "radarMdGenuineTableHead": "| Thiết bị | Sàn / gian hàng | Giá bán hiện tại | Giá trung vị các tin bán | Tiết kiệm thật | Điểm JReviews |", @@ -784,7 +784,7 @@ "dealsMdUrlLine": "- **Xem trên Rate.vn:** {url}", "dealsMdTableHead": "| Hạng | Thiết bị | Hãng | Điểm theo nhu cầu | Điểm JReviews | Giá thấp nhất | Tiết kiệm giữa các sàn | Tín hiệu giá |", "samePrice": "Đồng giá", - "filterBadge": "Tìm deal đã kiểm tra trên 10 sàn", + "filterBadge": "Tìm deal đã kiểm tra trên 22 sàn", "showingCount": "Hiển thị {visible} trên {count} thiết bị trong ngân sách", "copiedMdBtn": "✓ Đã sao chép Markdown!", "copyMdBtn": "Sao chép Markdown", @@ -795,7 +795,7 @@ "maxBudgetLabel": "Ngân sách tối đa:", "maxBudgetAria": "Ngân sách tối đa", "searchPlaceholder": "Tìm nhanh theo tên máy hoặc thương hiệu (Apple, Samsung, Xiaomi, Sony...)", - "radarBannerBadge": "Deal dưới giá trung vị và cảnh báo giảm giá ảo trên 10 sàn", + "radarBannerBadge": "Deal dưới giá trung vị và cảnh báo giảm giá ảo trên 22 sàn", "radarScannedSummary": "Đã quét {offers} tin bán trên {clusters} cụm sản phẩm", "copiedRadarMdBtn": "✓ Đã chép tín hiệu giá", "copyRadarMdBtn": "Sao chép tín hiệu giá (Markdown)", @@ -815,7 +815,7 @@ "labNoScore": "Lab: chưa có", "spreadSavingsBadge": "Chênh sàn tiết kiệm {amount} ₫", "costPerPointSub": "({cost} ₫ / điểm JReviews)", - "audit10PlatformsLink": "So sánh giá trên 10 sàn →", + "audit10PlatformsLink": "So sánh giá trên 22 sàn →", "radarBadgeGenuine": "🔥 Đáy giá đa sàn (-{pct}%)", "radarBadgeBelowMedian": "✅ Dưới giá trung vị (-{pct}%)", "radarBadgeFakeTrap": "🚨 Cảnh báo giảm giá ảo (+{pct}%)", @@ -850,12 +850,12 @@ "genuineDiscountBadge": "Giá niêm yết khớp với lịch sử giá thật.", "implausiblyLowBadge": "Giá thấp bất thường", "implausiblyLowTitle": "Rẻ hơn nhiều so với mọi nơi bán khác: có thể là hàng giả, phụ kiện hoặc tin câu khách. Hãy kiểm tra kỹ gian hàng trước khi mua.", - "radarSectionBadge": "Tín hiệu giá trên 10 sàn và chênh lệch giá", - "openDealRadarLink": "Xem deal trên 10 sàn →", + "radarSectionBadge": "Tín hiệu giá trên 22 sàn và chênh lệch giá", + "openDealRadarLink": "Xem deal trên 22 sàn →", "radarGenuinePill": "Giá thấp nhất các sàn: -{pct}% tại {platform} ({price} ₫)", "radarBelowMedianPill": "Dưới giá trung vị: -{pct}% tại {platform} ({price} ₫)", "radarFakePill": "Giảm giá ảo: +{pct}% tại {platform}", - "radarSpreadPill": "Chênh lệch giá trên 10 sàn: +{pct}% ({vnd} ₫ giữa {cheapest} và {priciest})", + "radarSpreadPill": "Chênh lệch giá trên 22 sàn: +{pct}% ({vnd} ₫ giữa {cheapest} và {priciest})", "masterProductSection": "Sản phẩm khớp (10 nhóm thông số)", "userNoScore": "Người mua: chưa có điểm", "expertNoScore": "chưa có điểm", @@ -1007,7 +1007,7 @@ "profileRadarGenuineCount": "{count} tin bán dưới giá trung vị", "profileRadarFakeCount": "{count} cảnh báo kê khống giá gốc", "profileRadarZeroFake": "0 cảnh báo nâng khống giá gốc", - "openRadar10PlatformsBtn": "Xem deal trên 10 sàn →", + "openRadar10PlatformsBtn": "Xem deal trên 22 sàn →", "low60dAndMedian": "Thấp nhất thị trường: {min} ₫ • Trung vị: {median} ₫", "vsMedianBadge": "-{pct}% so trung vị", "inflatedOriginalPrice": "Giá gạch ngang kê khống: {price} ₫", @@ -1141,7 +1141,7 @@ "noOffersYet": "Hiện chưa có sàn bán nào liên kết với mẫu máy này.", "competitorsBadge": "Sản phẩm cùng phân khúc ({category})", "competitorsTitle": "Lựa chọn thay thế cho {name}", - "dealHub10PlatformsBtn": "Xem deal trên 10 sàn", + "dealHub10PlatformsBtn": "Xem deal trên 22 sàn", "compareAllPeersBtn": "So sánh cả {count} máy →", "peerNoRating": "chưa có", "cheaperByBadge": "Rẻ hơn {amount} ₫", @@ -1340,7 +1340,7 @@ "compare10GroupsBtn": "So sánh 10 nhóm thông số", "scoreDeltaLabel": "Chênh {delta} điểm", "view1v1ScoreBtn": "Xem chấm điểm 1v1", - "radarHomeBadge": "Tín hiệu giá trên 10 sàn", + "radarHomeBadge": "Tín hiệu giá trên 22 sàn", "radarHomeAnalyzed": "Đối chiếu tự động {offers} tin bán của {merchants} gian hàng trên {clusters} cụm sản phẩm", "radarHomeDealHubBtn": "Trung tâm săn deal", "radarHomeInspectBtn": "Kiểm tra link khuyến mãi", @@ -1429,9 +1429,9 @@ "ep5Params": "q hoặc url (link Shopee/Lazada/Tiki hoặc từ khóa)", "ep5Summary": "Đọc link sản phẩm hoặc gian hàng, ghép với sản phẩm chuẩn hóa và hồ sơ tin cậy của gian hàng. Giới hạn 30 yêu cầu mỗi phút cho mỗi IP (dùng chung với /inspect); vượt giới hạn sẽ nhận mã 429. Retry-After trong header cho biết số giây cần chờ.", "ep6Params": "q hoặc url (URL hoặc tên máy), price (giá đang thấy, không bắt buộc), originalPrice (giá gốc bị gạch, không bắt buộc)", - "ep6Summary": "Kiểm tra giá và link (/inspect): chuẩn hóa URL trên 10 sàn và đại lý, loại phụ kiện và linh kiện, so với giá trung vị rồi trả kết luận giá 5 mức. Giới hạn 30 yêu cầu mỗi phút cho mỗi IP (dùng chung với /lookup); vượt giới hạn sẽ nhận mã 429. Retry-After trong header cho biết số giây cần chờ.", + "ep6Summary": "Kiểm tra giá và link (/inspect): chuẩn hóa URL trên 22 sàn và đại lý, loại phụ kiện và linh kiện, so với giá trung vị rồi trả kết luận giá 5 mức. Giới hạn 30 yêu cầu mỗi phút cho mỗi IP (dùng chung với /lookup); vượt giới hạn sẽ nhận mã 429. Retry-After trong header cho biết số giây cần chờ.", "ep7Params": "url, title, price, originalPrice, skuText", - "ep7Summary": "Endpoint nhanh cho tiện ích trình duyệt Rate trên 10 sàn và đại lý (Shopee, Lazada, Tiki, TikTok Shop, CellphoneS, TGDĐ, FPT Shop, Hoàng Hà, Di Động Việt, Phong Vũ).", + "ep7Summary": "Endpoint nhanh cho tiện ích trình duyệt Rate trên 22 sàn và đại lý (Shopee, Lazada, Tiki, TikTok Shop, CellphoneS, TGDĐ, Điện Máy Xanh, TopZone, FPT Shop, Hoàng Hà, Di Động Việt, Phong Vũ, GearVN, Nguyễn Kim, ShopDunk, HACOM, Clickbuy, Viettel Store, Pico, MediaMart, MemoryZone, An Phát).", "ep8Params": "Body JSON: { url, title, price, originalPrice?, platform?, selectedVariant?, userConsentOptIn: true }", "ep8Summary": "Nhận tín hiệu sản phẩm ẩn danh từ tiện ích trình duyệt khi người dùng đã đồng ý: kiểm tra cấu trúc, xóa tham số định danh cá nhân (PII) rồi đưa vào hàng đợi rate.crawl_jobs.", "ep9Params": "platform, officialOnly, min_trust, q, sort, limit", @@ -1513,7 +1513,7 @@ "pgPreset5Title": "So sánh trực tiếp hai máy (/versus)", "pgPreset5Desc": "Chấm điểm hai mẫu cùng ngành hàng theo 5 tiêu chí (màn hình, hiệu năng, camera, pin, đáng tiền), cho phép đổi trọng số theo nhu cầu và tính chênh lệch giá.", "pgPreset6Title": "Kiểm tra giá và link (/inspect)", - "pgPreset6Desc": "Kiểm tra URL hoặc tên máy trên 10 sàn và đại lý (Shopee, Lazada, Tiki, TikTok Shop, CellphoneS, TGDĐ, FPT Shop, Hoàng Hà, Di Động Việt, Phong Vũ) rồi trả kết luận giá 5 mức.", + "pgPreset6Desc": "Kiểm tra URL hoặc tên máy trên 22 sàn và đại lý (Shopee, Lazada, Tiki, TikTok Shop, CellphoneS, TGDĐ, Điện Máy Xanh, TopZone, FPT Shop, Hoàng Hà, Di Động Việt, Phong Vũ, GearVN, Nguyễn Kim, ShopDunk, HACOM, Clickbuy, Viettel Store, Pico, MediaMart, MemoryZone, An Phát) rồi trả kết luận giá 5 mức.", "pgPreset7Title": "Tra cứu cho tiện ích trình duyệt", "pgPreset7Desc": "Endpoint nhanh cho tiện ích trình duyệt Rate: chuẩn hóa URL, loại phụ kiện và linh kiện, trả kết luận giá 5 mức.", "pgPreset8Title": "Gửi tín hiệu sản phẩm (POST)", @@ -1524,8 +1524,8 @@ "pgPreset10Desc": "Truy vấn hàng loạt giá thấp nhất hiện tại, trung vị lịch sử và trạng thái giảm giá thật/ảo cho danh sách sản phẩm đang theo dõi.", "pgPreset11Title": "Số liệu toàn nền tảng (/stats)", "pgPreset11Desc": "Trả về số lượng sản phẩm chuẩn hóa, bản ghi lịch sử giá, tỷ lệ đánh giá thực chất và số lượng mẫu theo từng ngành hàng.", - "pgPreset12Title": "Deal thật và giảm giá ảo trên 10 sàn (/deals)", - "pgPreset12Desc": "Quét giá trên 10 sàn để tìm giá thấp thật (genuineDeals) và giá gốc bị nâng khống (fakeSaleTraps).", + "pgPreset12Title": "Deal thật và giảm giá ảo trên 22 sàn (/deals)", + "pgPreset12Desc": "Quét giá trên 22 sàn để tìm giá thấp thật (genuineDeals) và giá gốc bị nâng khống (fakeSaleTraps).", "pgPreset13Title": "Spec OpenAPI 3.1.0 (/openapi.json)", "pgPreset13Desc": "Trả về spec OpenAPI 3.1.0 dạng JSON cho các endpoint REST API v1 của Rate.vn.", "authPublic": "Công khai (CORS)", @@ -1600,7 +1600,7 @@ "privacyS4Title": "4. Thông tin riêng của gian hàng", "privacyS4Desc": "Thông tin riêng của gian hàng (số điện thoại, tài khoản ngân hàng) nằm ở các trường mà công chúng không đọc được. Trang web và API chỉ đọc được các trường công khai.", "privacyS5Title": "5. Tiện ích trình duyệt Rate.vn", - "privacyS5Desc": "Trên trang sản phẩm của 10 sàn được hỗ trợ, tiện ích gửi cho Rate.vn sàn, URL sản phẩm đã bỏ tham số, tên sản phẩm, mã sản phẩm và mã gian hàng, phiên bản đang chọn, giá bán và giá gốc để tra lịch sử giá; việc tra cứu này bật sẵn, chỉ đọc và không cần tài khoản. Nội dung bạn gõ vào ô tìm kiếm của tiện ích cũng được gửi để tra cứu. Chỉ khi bạn chọn \"Có\" ở trang hiện ra lúc cài đặt hoặc bật \"Đóng góp phát hiện sản phẩm mới (chỉ khi bạn bật)\" trong bảng bên cạnh (mặc định tắt), tiện ích còn gửi vào hàng đợi kiểm duyệt một quan sát về tin bán đó: sàn, URL đã bỏ tham số, mã sản phẩm, mã gian hàng, mã SKU của phân loại, phiên bản đang chọn, giá bán, giá gốc, tình trạng và số lượng còn hàng, thời điểm bạn thấy giá và phiên bản tiện ích, kèm một mã người đóng góp ngẫu nhiên của lượt cài này. Máy chủ lưu kèm thời điểm nhận và một mã băm có muối của dải mạng (không phải IP) để phân biệt người gửi độc lập; mã băm được xóa sau 28 ngày, quan sát sau 180 ngày. Máy chủ Rate.vn có thể kiểm tra lại tin bán đó trên sàn, và dữ liệu này không tự đổi giá công khai. Tắt đóng góp là xóa mã người đóng góp cùng mọi quan sát đã gửi; nếu gỡ tiện ích mà chưa tắt, chúng tự xóa sau 180 ngày. Tiện ích không gửi tài khoản, tên, email hay cookie, không mở trang bạn không mở, và chỉ lưu trên trình duyệt của bạn địa chỉ máy chủ, lựa chọn có đóng góp hay không, mã người đóng góp khi bạn đóng góp, cùng bộ nhớ tạm theo phiên gồm các sản phẩm bạn vừa xem, lần tìm kiếm gần nhất, kết quả tra cứu và thời gian chờ khi bị giới hạn tra cứu. Như mọi yêu cầu web, máy chủ nhận địa chỉ IP của bạn: mã của Rate.vn dùng nó trong bộ nhớ để giới hạn số yêu cầu mỗi phút và, khi bạn đóng góp, để tính mã băm dải mạng nói trên; bản thân IP không bao giờ được lưu, còn nhà cung cấp hosting giữ nhật ký truy cập thông thường trong thời gian ngắn.", + "privacyS5Desc": "Trên trang sản phẩm của 22 sàn được hỗ trợ, tiện ích gửi cho Rate.vn sàn, URL sản phẩm đã bỏ tham số, tên sản phẩm, mã sản phẩm và mã gian hàng, phiên bản đang chọn, giá bán và giá gốc để tra lịch sử giá; việc tra cứu này bật sẵn, chỉ đọc và không cần tài khoản. Nội dung bạn gõ vào ô tìm kiếm của tiện ích cũng được gửi để tra cứu. Chỉ khi bạn chọn \"Có\" ở trang hiện ra lúc cài đặt hoặc bật \"Đóng góp phát hiện sản phẩm mới (chỉ khi bạn bật)\" trong bảng bên cạnh (mặc định tắt), tiện ích còn gửi vào hàng đợi kiểm duyệt một quan sát về tin bán đó: sàn, URL đã bỏ tham số, mã sản phẩm, mã gian hàng, mã SKU của phân loại, phiên bản đang chọn, giá bán, giá gốc, tình trạng và số lượng còn hàng, thời điểm bạn thấy giá và phiên bản tiện ích, kèm một mã người đóng góp ngẫu nhiên của lượt cài này. Máy chủ lưu kèm thời điểm nhận và một mã băm có muối của dải mạng (không phải IP) để phân biệt người gửi độc lập; mã băm được xóa sau 28 ngày, quan sát sau 180 ngày. Máy chủ Rate.vn có thể kiểm tra lại tin bán đó trên sàn, và dữ liệu này không tự đổi giá công khai. Tắt đóng góp là xóa mã người đóng góp cùng mọi quan sát đã gửi; nếu gỡ tiện ích mà chưa tắt, chúng tự xóa sau 180 ngày. Tiện ích không gửi tài khoản, tên, email hay cookie, không mở trang bạn không mở, và chỉ lưu trên trình duyệt của bạn địa chỉ máy chủ, lựa chọn có đóng góp hay không, mã người đóng góp khi bạn đóng góp, cùng bộ nhớ tạm theo phiên gồm các sản phẩm bạn vừa xem, lần tìm kiếm gần nhất, kết quả tra cứu và thời gian chờ khi bị giới hạn tra cứu. Như mọi yêu cầu web, máy chủ nhận địa chỉ IP của bạn: mã của Rate.vn dùng nó trong bộ nhớ để giới hạn số yêu cầu mỗi phút và, khi bạn đóng góp, để tính mã băm dải mạng nói trên; bản thân IP không bao giờ được lưu, còn nhà cung cấp hosting giữ nhật ký truy cập thông thường trong thời gian ngắn.", "privacySide1Title": "Kiểm tra mã nguồn công khai", "privacySide1Desc": "Quy tắc phân quyền dữ liệu và cách lưu bình chọn đều công khai trong repository trên GitHub.", "privacySide1Btn": "Xem tài liệu kỹ thuật và API", @@ -1634,7 +1634,7 @@ "contactSeoDesc": "Gửi link sản phẩm hoặc gian hàng Shopee, Lazada, Tiki có dấu hiệu nâng khống giá gốc hoặc đánh giá ảo để Rate.vn kiểm tra.", "contactHeroBadge": "Liên hệ & phản hồi", "contactHeroTitle": "Kiểm tra nhanh và báo cáo gian hàng bất thường", - "contactHeroDesc": "Dán link sản phẩm hoặc gian hàng từ Shopee, Lazada, Tiki, TikTok Shop, CellphoneS, TGDĐ, FPT Shop, Hoàng Hà, Di Động Việt hoặc Phong Vũ vào ô bên dưới để xem lịch sử giá, hoặc gửi link để Rate.vn kiểm tra.", + "contactHeroDesc": "Dán link sản phẩm hoặc gian hàng từ 22 sàn và chuỗi bán lẻ (Shopee, Lazada, Tiki, TikTok Shop, CellphoneS, TGDĐ, Điện Máy Xanh, TopZone, FPT Shop, Hoàng Hà, Di Động Việt, Phong Vũ, GearVN, Nguyễn Kim, ShopDunk, HACOM, Clickbuy, Viettel Store, Pico, MediaMart, MemoryZone, An Phát) vào ô bên dưới để xem lịch sử giá, hoặc gửi link để Rate.vn kiểm tra.", "contactCard1Title": "1. Báo cáo giảm giá ảo và đánh giá ảo", "contactCard1Desc": "Khi thấy giá gốc bị nâng trước ngày sale, hãy dán link sản phẩm vào ô kiểm tra ở trang này. Khi thấy tài khoản ảo lặp lại bình luận mẫu để đẩy sao, hãy đăng nhập rồi bấm \"Báo cáo\" ngay tại đánh giá đó trên trang sản phẩm.", "contactCard1Btn": "Tới danh mục sản phẩm →", @@ -1673,7 +1673,7 @@ "quarantineOutcome": { "accepted": "Link đã vào hàng chờ kiểm tra. Giá bạn nhập không được đưa thẳng lên trang.", "noConsent": "Hãy đánh dấu ô đồng ý chia sẻ trước khi gửi.", - "invalidUrl": "Link này không phải trang chi tiết sản phẩm của một trong 10 sàn được hỗ trợ. Hãy mở trang sản phẩm và sao chép lại link.", + "invalidUrl": "Link này không phải trang chi tiết sản phẩm của một trong 22 sàn được hỗ trợ. Hãy mở trang sản phẩm và sao chép lại link.", "platformPending": "Rate.vn tạm thời chưa nhận link từ sàn này. Vui lòng thử lại sau.", "invalidPrice": "Giá đang bán không hợp lệ. Hãy nhập số tiền bằng đồng.", "accessory": "Có vẻ đây là phụ kiện hoặc linh kiện. Rate.vn chỉ theo dõi giá của thiết bị.", @@ -1865,10 +1865,10 @@ "sortByPrefix": "Sắp xếp: {label}", "radarBannerBadge": "Deal dưới giá trung vị và cảnh báo giảm giá ảo ({title})", "radarAnalyzedSub": "Đã kiểm tra {count} tin bán", - "viewAllRadarBtn": "Xem tất cả deal trên 10 sàn", + "viewAllRadarBtn": "Xem tất cả deal trên 22 sàn", "vsMedianBadge": "-{pct}% so trung vị", "fakeMarkupBadge": "Kê khống +{pct}%", - "spreadHeader": "Chênh lệch giá lớn nhất giữa 10 sàn ({title}):", + "spreadHeader": "Chênh lệch giá lớn nhất giữa 22 sàn ({title}):", "spreadSub": "Mua đúng sàn tiết kiệm hàng triệu đồng", "spreadDiffBadge": "Lệch +{pct}% ({amount} ₫)", "emptySyncingTitle": "Danh mục \"{title}\" đang chờ đồng bộ dữ liệu sản phẩm mới", diff --git a/apps/web/src/app/api/v1/rate/deals/route.ts b/apps/web/src/app/api/v1/rate/deals/route.ts index 8046d21e4..9cb7284ed 100644 --- a/apps/web/src/app/api/v1/rate/deals/route.ts +++ b/apps/web/src/app/api/v1/rate/deals/route.ts @@ -3,6 +3,7 @@ import { getCrossPlatformDealRadar } from '../../../../../server/rate/deals'; import type { CanonicalCategorySlug } from '../../../../../lib/rate-api'; import { PUBLIC_API_CORS_HEADERS, + SUPPORTED_PLATFORM_SLUGS, jsonApiError, parseBoundedIntParam, parseBoundedStringParam, @@ -16,18 +17,7 @@ const VALID_CATEGORIES = new Set([ 'earbuds', ]); -const VALID_PLATFORMS = new Set([ - 'shopee', - 'lazada', - 'tiki', - 'tiktok', - 'cellphones', - 'tgdd', - 'fptshop', - 'hoangha', - 'didongviet', - 'phongvu', -]); +const VALID_PLATFORMS = SUPPORTED_PLATFORM_SLUGS; export async function OPTIONS() { return new NextResponse(null, { diff --git a/apps/web/src/app/api/v1/rate/extension/ingest/route.ts b/apps/web/src/app/api/v1/rate/extension/ingest/route.ts index 4e1419dce..66f56b6d2 100644 --- a/apps/web/src/app/api/v1/rate/extension/ingest/route.ts +++ b/apps/web/src/app/api/v1/rate/extension/ingest/route.ts @@ -37,6 +37,18 @@ const CrowdIngestSchema = z.object({ 'hoangha', 'didongviet', 'phongvu', + 'dienmayxanh', + 'topzone', + 'gearvn', + 'nguyenkim', + 'shopdunk', + 'hacom', + 'clickbuy', + 'viettelstore', + 'pico', + 'mediamart', + 'memoryzone', + 'anphatpc', ]) .optional(), externalItemId: z.string().trim().min(1).max(120).optional(), diff --git a/apps/web/src/app/api/v1/rate/extension/lookup/route.ts b/apps/web/src/app/api/v1/rate/extension/lookup/route.ts index e6cd43947..bcf42bc08 100644 --- a/apps/web/src/app/api/v1/rate/extension/lookup/route.ts +++ b/apps/web/src/app/api/v1/rate/extension/lookup/route.ts @@ -41,7 +41,7 @@ export async function OPTIONS() { * GET /api/v1/rate/extension/lookup * Fast-Path Read-Only Lookup for Rate Browser Extension MV3 (Two-Speed Hybrid Architecture v2). * Query parameters: - * - platform: shopee | lazada | tiki | tiktok | cellphones | tgdd | fptshop | hoangha | didongviet | phongvu + * - platform: shopee | lazada | tiki | tiktok | cellphones | tgdd | fptshop | hoangha | didongviet | phongvu | dienmayxanh | topzone | gearvn | nguyenkim | shopdunk | hacom | clickbuy | viettelstore | pico | mediamart | memoryzone | anphatpc * - externalId: platform item ID or shopId_itemId * - shopId: platform shop ID * - url: product URL (automatically canonicalized, stripping tracking params) diff --git a/apps/web/src/components/deals/DealFinderWorkspace.tsx b/apps/web/src/components/deals/DealFinderWorkspace.tsx index a528e0981..1f94c4fe8 100644 --- a/apps/web/src/components/deals/DealFinderWorkspace.tsx +++ b/apps/web/src/components/deals/DealFinderWorkspace.tsx @@ -719,7 +719,7 @@ export default function DealFinderWorkspace({ if (typeof window === 'undefined' || !dealRadar) return; const payload = { source: - 'Rate.vn cross-store price lows and fake-sale warnings (10 stores)', + 'Rate.vn cross-store price lows and fake-sale warnings (22 stores)', categoryFilter, exportedAt: new Date().toISOString(), totalClustersAnalyzed: dealRadar.totalClustersAnalyzed, diff --git a/apps/web/src/components/home/HeroSearchInspector.tsx b/apps/web/src/components/home/HeroSearchInspector.tsx index 69ff73e6f..3a8166d77 100644 --- a/apps/web/src/components/home/HeroSearchInspector.tsx +++ b/apps/web/src/components/home/HeroSearchInspector.tsx @@ -104,7 +104,9 @@ export function isLikelyEcommerceUrl(input: unknown): boolean { const s = input.replace(HERO_INSPECTOR_CONTROL_CHARS_RE, '').trim(); return ( /^https?:\/\//i.test(s) || - /shopee\.vn|lazada\.vn|tiki\.vn|tiktok\.com|i\.\d+\.\d+/i.test(s) + /(?:^|\/\/|\.)(?:shopee\.vn|lazada\.vn|tiki\.vn|tiktok\.com|cellphones\.com\.vn|thegioididong\.com|dienmayxanh\.com|topzone\.vn|fptshop\.com\.vn|hoanghamobile\.com|didongviet\.vn|phongvu\.vn|gearvn\.com|nguyenkim\.com|shopdunk\.com|hacom\.vn|clickbuy\.com\.vn|viettelstore\.vn|pico\.vn|mediamart\.vn|memoryzone\.com\.vn|anphatpc\.com\.vn)\/|i\.\d+\.\d+/i.test( + s + ) ); } diff --git a/apps/web/src/components/merchants/MerchantDirectoryExplorer.tsx b/apps/web/src/components/merchants/MerchantDirectoryExplorer.tsx index 2768a21f1..8b48c5d49 100644 --- a/apps/web/src/components/merchants/MerchantDirectoryExplorer.tsx +++ b/apps/web/src/components/merchants/MerchantDirectoryExplorer.tsx @@ -619,6 +619,18 @@ export default function MerchantDirectoryExplorer({ 'hoangha', 'didongviet', 'phongvu', + 'dienmayxanh', + 'topzone', + 'gearvn', + 'nguyenkim', + 'shopdunk', + 'hacom', + 'clickbuy', + 'viettelstore', + 'pico', + 'mediamart', + 'memoryzone', + 'anphatpc', ]; for (const p of platformCounts.keys()) { if (!base.includes(p)) base.push(p); diff --git a/apps/web/src/components/watchlist/WatchlistWorkspace.tsx b/apps/web/src/components/watchlist/WatchlistWorkspace.tsx index 294d861d6..e7c4befc4 100644 --- a/apps/web/src/components/watchlist/WatchlistWorkspace.tsx +++ b/apps/web/src/components/watchlist/WatchlistWorkspace.tsx @@ -107,6 +107,18 @@ const PLATFORM_DISPLAY_LABELS: Record = { hoangha: 'Hoàng Hà Mobile', didongviet: 'Di Động Việt', phongvu: 'Phong Vũ', + dienmayxanh: 'Điện Máy Xanh', + topzone: 'TopZone', + gearvn: 'GearVN', + nguyenkim: 'Nguyễn Kim', + shopdunk: 'ShopDunk', + hacom: 'HACOM', + clickbuy: 'Clickbuy', + viettelstore: 'Viettel Store', + pico: 'Pico', + mediamart: 'MediaMart', + memoryzone: 'MemoryZone', + anphatpc: 'An Phát Computer', }; export function sanitizeWatchlistBestOfferUrl(rawUrl: unknown): string | null { @@ -1487,8 +1499,13 @@ export default function WatchlistWorkspace({ {t('bestOfferPrefix', { count: platformCount })} {' '} - {PLATFORM_DISPLAY_LABELS[bestOffer.platform] || - bestOffer.platform.toUpperCase()} + +>([ + 'nguyenkim', + 'shopdunk', + 'hacom', + 'clickbuy', + 'viettelstore', + 'pico', + 'mediamart', + 'memoryzone', +]); + +function encodeAnPhatSlugForItemId(value: string): string { + return value.toLowerCase().replace(/[^a-z0-9-]/g, (ch) => { + const hex = ch.codePointAt(0)?.toString(16).padStart(2, '0') ?? '00'; + return `_${hex}`; + }); +} + function lookupOfferDiscountAnalysis( byOffer: Record | null | undefined, rawId: unknown @@ -4613,6 +4645,27 @@ export async function inspectProductOrShopUrl( : undefined; if (prefix && !parsedUrl.platformItemId.startsWith(prefix)) { candidateIds.add(`${prefix}${parsedUrl.platformItemId}`); + const lowerId = parsedUrl.platformItemId.toLowerCase(); + candidateIds.add(`${prefix}${lowerId}`); + if ( + parsedUrl.platform && + WAVE_UNDERSCORE_ENCODED_PLATFORMS.has(parsedUrl.platform) && + lowerId.includes('_') + ) { + const waveEncoded = `${prefix}${lowerId.replace(/_/g, '_5f')}`; + if (waveEncoded.length <= 128) candidateIds.add(waveEncoded); + } + if (parsedUrl.platform === 'anphatpc') { + const apEncoded = `${prefix}${encodeAnPhatSlugForItemId(parsedUrl.platformItemId)}`; + if (apEncoded.length <= 128) candidateIds.add(apEncoded); + } + } + if ( + (parsedUrl.platform === 'topzone' || + parsedUrl.platform === 'dienmayxanh') && + !parsedUrl.platformItemId.startsWith('tgdd-') + ) { + candidateIds.add(`tgdd-${parsedUrl.platformItemId}`); } const { data: prodRow, error: prodErr } = await supabase diff --git a/apps/web/src/lib/rate-domain-core.ts b/apps/web/src/lib/rate-domain-core.ts index 03d8160bd..b1a20d27d 100644 --- a/apps/web/src/lib/rate-domain-core.ts +++ b/apps/web/src/lib/rate-domain-core.ts @@ -1595,6 +1595,18 @@ export interface ParsedEcommerceUrl { | 'hoangha' | 'didongviet' | 'phongvu' + | 'dienmayxanh' + | 'topzone' + | 'gearvn' + | 'nguyenkim' + | 'shopdunk' + | 'hacom' + | 'clickbuy' + | 'viettelstore' + | 'pico' + | 'mediamart' + | 'memoryzone' + | 'anphatpc' | 'rate' | null; platformShopId: string | null; @@ -1606,31 +1618,110 @@ function isDomainOrSubdomain(host: string, domain: string): boolean { return host === domain || host.endsWith(`.${domain}`); } +const KNOWN_ECOMMERCE_DOMAIN_TOKEN_REGEX = + /(?:^|\/\/|\.)(?:shopee\.vn|lazada\.vn|tiki\.vn|tiktok\.com|cellphones\.com\.vn|thegioididong\.com|dienmayxanh\.com|topzone\.vn|fptshop\.com\.vn|hoanghamobile\.com|didongviet\.vn|phongvu\.vn|gearvn\.com|nguyenkim\.com|shopdunk\.com|hacom\.vn|clickbuy\.com\.vn|viettelstore\.vn|pico\.vn|mediamart\.vn|memoryzone\.com\.vn|anphatpc\.com\.vn|rate\.vn)(?:\/|$)/i; + const RETAIL_NON_PRODUCT_FIRST_SEGMENTS = new Set([ 'tin-tuc', + 'tin-khuyen-mai', + 'cong-nghe', 'sforum', 'dchannel', 'hoi-dap', + 'huong-dan', 'khuyen-mai', + 'hot-deal', 'tra-gop', + 'thu-cu-doi-moi', 'bao-hanh', + 'tra-bao-hanh', + 'tra-cuu-bao-hanh', + 'chinh-sach', + 'lien-he', + 'gioi-thieu', + 've-chung-toi', + 'tuyen-dung', + 'so-sanh', + 'so-sanh-san-pham', + 'compare', + 'cua-hang', + 'showroom', + 'sieu-thi', 'he-thong-cua-hang', 'he-thong-sieu-thi', + 'he-thong-showroom', + 'he-thong-trung-tam', + 'trung-tam-bao-hanh', 'catalogsearch', 'tim-kiem', + 'ket-qua-tim-kiem', + 'tim', 'search', + 'filter', 'cart', 'gio-hang', + 'checkout', + 'thanh-toan', 'account', + 'tai-khoan', + 'taikhoan', 'login', + 'dang-nhap', + 'register', + 'dang-ky', + 'logout', + 'dang-xuat', + 'auth', + 'captcha', + 'challenge', 'blog', + 'blogs', 'news', 'event', + 'su-kien', 'landing', 'collection', + 'collections', + 'pages', + 'page', + 'policies', + 'tag', + 'tags', + 'brand', + 'thuong-hieu', + 'buildpc', + 'xay-dung-cau-hinh', + 'sua-chua', + 'dich-vu', + 'may-cu', + 'hang-cu', + 'may-cu-gia-re', + 'likenew', + 'like-new', + 'outlet', + 'xa-kho', + 'ajax', + 'api', + 'media', + 'static', + 'assets', + 'cdn-cgi', 'c', + 'danh-muc', ]); +const RETAIL_AUTH_OR_NON_PRODUCT_SLUG_REGEX = + /^(?:chinh-sach-|quy-che-|huong-dan-|dieu-khoan-|gioi-thieu(?:-|$)|ve-chung-toi(?:-|$)|tin-khuyen-mai(?:-|$)|tin-tuc-|khuyen-mai-|sua-chua(?:-|$)|dich-vu(?:-|$)|tra-bao-hanh(?:-|$)|tra-cuu-bao-hanh(?:-|$)|he-thong-(?:cua-hang|sieu-thi|showroom|trung-tam)(?:-|$)|ket-qua-tim-kiem$|so-sanh(?:-san-pham)?$|buildpc$|xay-dung-cau-hinh$)/i; + +const RETAIL_AUTH_SEGMENT_REGEX = + /^(?:login|register|account|tai-khoan|taikhoan|dang-nhap|dang-ky|logout|dang-xuat|auth|captcha|challenge)$/i; + +const RETAIL_STATIC_ASSET_EXT_REGEX = + /\.(?:js|mjs|cjs|json|css|xml|txt|pdf|zip|rar|7z|png|jpe?g|webp|avif|svg|gif|ico|woff2?|ttf|eot|map|mp[34]|webm|aspx|ashx|axd|php)$/i; + +const ANPHAT_DESK_PHONE_SLUG_REGEX = + /^(?:dien-thoai-(?:huu-tuyen|ip|ban|de-ban|khong-day|keo-dai|hoi-nghi)|tong-dai-ip)(?:-|$)/i; + // A path ending in a bare brand lists that brand's products, as in // cellphones.com.vn/mobile/apple.html or fptshop.com.vn/dien-thoai/samsung; // no product slug is a brand alone (DOS/Rate#1246). Keep these rules in @@ -1672,6 +1763,15 @@ const RETAIL_BRAND_LISTING_SLUGS = new Set([ 'anker', 'baseus', 'ugreen', + 'logitech', + 'razer', + 'corsair', + 'hyperx', + 'steelseries', + 'bose', + 'sennheiser', + 'gigabyte', + 'tcl', 'mac', ]); @@ -1684,23 +1784,63 @@ const isSeriesListingSlug = (slug: string) => const RETAIL_CATEGORY_ROOT_SLUGS = new Set([ 'dtdd', + 'mtb', 'dien-thoai', 'dien-thoai-di-dong', + 'dien-thoai-thong-minh', 'mobile', 'smartphones', 'laptop', 'laptops', + 'laptop-gaming', + 'laptop-gaming-do-hoa', + 'laptop-van-phong', + 'laptop-tablet-mobile', 'may-tinh-xach-tay', + 'may-tinh-xach-tay-laptop', 'may-tinh-bang', + 'may-tinh-bang-tablet', 'tablet', 'tablets', + 'dong-ho', 'dong-ho-thong-minh', 'smartwatch', 'smartwatches', 'tai-nghe', + 'tai-nghe-bluetooth', + 'tai-nghe-nhet-tai', + 'tai-nghe-chup-tai', + 'tai-nghe-gaming', + 'am-thanh', + 'thiet-bi-am-thanh', + 'loa', 'earbuds', 'phu-kien', + 'phu-kien-di-dong', + 'linh-kien', + 'linh-kien-may-tinh', + 'man-hinh', + 'man-hinh-may-tinh', + 'pc', + 'pc-gaming', + 'pc-van-phong-do-hoa', + 'may-tinh-de-ban', + 'gaming-gear', + 'tivi', + 'tu-lanh', + 'may-giat', + 'may-lanh', + 'gia-dung', + 'dien-gia-dung', + 'dien-may', + 'sim-so', + 'san-pham', + 'products', + 'product', 'apple', + 'apple-iphone', + 'apple-ipad', + 'apple-watch', 'iphone', 'ipad', 'macbook', @@ -1708,6 +1848,132 @@ const RETAIL_CATEGORY_ROOT_SLUGS = new Set([ 'airpods', ]); +function extractValidRetailItemSlug( + retailPlatform: NonNullable, + segments: readonly string[] +): string | null { + if (segments.length === 0) return null; + + for (const seg of segments) { + const strippedSeg = seg + .toLowerCase() + .replace(/\.(?:html|htm|aspx|ashx|axd|php)$/i, ''); + if ( + RETAIL_AUTH_SEGMENT_REGEX.test(strippedSeg) || + RETAIL_AUTH_SEGMENT_REGEX.test(seg) + ) { + return null; + } + } + + const firstRawLower = segments[0]!.toLowerCase(); + const firstSegLower = firstRawLower.replace(/\.html?$/i, ''); + const lastRaw = segments[segments.length - 1]!; + if (RETAIL_STATIC_ASSET_EXT_REGEX.test(lastRaw)) { + return null; + } + if ( + (retailPlatform === 'nguyenkim' || retailPlatform === 'pico') && + /\.(?:c|b)$/i.test(lastRaw) + ) { + return null; + } + + const isCollectionProductPath = + segments.length === 4 && + firstSegLower === 'collections' && + segments[2]!.toLowerCase() === 'products'; + + if (retailPlatform === 'gearvn') { + if ( + !(segments.length === 2 && firstSegLower === 'products') && + !isCollectionProductPath + ) { + return null; + } + } else if (retailPlatform === 'memoryzone') { + if ( + segments.length !== 1 && + !(segments.length === 2 && firstSegLower === 'products') && + !isCollectionProductPath + ) { + return null; + } + } else if (retailPlatform === 'mediamart') { + if (segments.length !== 2) return null; + } else if ( + retailPlatform === 'tgdd' || + retailPlatform === 'dienmayxanh' || + retailPlatform === 'topzone' + ) { + if (segments.length < 2) return null; + } else if (retailPlatform === 'cellphones') { + // CellphoneS product pages sit at the root (DOS/Rate#1246). + if (segments.length > 1) return null; + } else if ( + retailPlatform === 'nguyenkim' || + retailPlatform === 'shopdunk' || + retailPlatform === 'hacom' || + retailPlatform === 'clickbuy' || + retailPlatform === 'pico' + ) { + if ( + segments.length !== 1 && + !( + segments.length === 2 && + (firstSegLower === 'products' || firstSegLower === 'san-pham') + ) + ) { + return null; + } + } else if (retailPlatform === 'viettelstore') { + if (segments.length > 2) return null; + } else if (retailPlatform === 'anphatpc') { + const hasHtmlExt = /\.html?$/i.test(lastRaw); + const isDirectRoutePrefix = + segments.length === 2 && + (firstSegLower === 'products' || firstSegLower === 'san-pham'); + if (!hasHtmlExt && !isDirectRoutePrefix) return null; + if (firstRawLower.startsWith('ajax') || firstRawLower.endsWith('.php')) { + return null; + } + if (segments.some((s) => /_dm\d+$/i.test(s.replace(/\.html?$/i, '')))) { + return null; + } + } + + if ( + !isCollectionProductPath && + RETAIL_NON_PRODUCT_FIRST_SEGMENTS.has(firstSegLower) + ) { + return null; + } + + const lastSeg = lastRaw.replace(/\.html?$/i, '') || null; + const lastSegLower = (lastSeg || '').toLowerCase(); + if ( + !lastSeg || + lastSeg.length < 2 || + lastSeg.length > 256 || + !/^[a-z0-9][a-z0-9._-]*[a-z0-9]$/i.test(lastSegLower) || + lastSegLower.includes('..') || + /^(?:0+|null|undefined|nan|infinity|-infinity|true|false|default|index|home|trang-chu|404|page-not-found|error)$/i.test( + lastSegLower + ) || + RETAIL_NON_PRODUCT_FIRST_SEGMENTS.has(lastSegLower) || + RETAIL_CATEGORY_ROOT_SLUGS.has(lastSegLower) || + RETAIL_BRAND_LISTING_SLUGS.has(lastSegLower) || + RETAIL_AUTH_OR_NON_PRODUCT_SLUG_REGEX.test(lastSegLower) || + isSeriesListingSlug(lastSegLower) || + (retailPlatform === 'anphatpc' && + ANPHAT_DESK_PHONE_SLUG_REGEX.test(lastSegLower)) + ) { + return null; + } + + return lastSeg; +} + export function parseEcommerceUrlOrQuery(raw: string): ParsedEcommerceUrl { const trimmed = typeof raw === 'string' @@ -1717,10 +1983,7 @@ export function parseEcommerceUrlOrQuery(raw: string): ParsedEcommerceUrl { .slice(0, 2048) : ''; const hasHttpProtocol = /^https?:\/\//i.test(trimmed); - const hasKnownDomainToken = - /(?:^|\/\/|\.)(?:shopee\.vn|lazada\.vn|tiki\.vn|tiktok\.com|cellphones\.com\.vn|thegioididong\.com|topzone\.vn|dienmayxanh\.com|fptshop\.com\.vn|hoanghamobile\.com|didongviet\.vn|phongvu\.vn|rate\.vn)(?:\/|$)/i.test( - trimmed - ); + const hasKnownDomainToken = KNOWN_ECOMMERCE_DOMAIN_TOKEN_REGEX.test(trimmed); const isUrl = hasHttpProtocol || hasKnownDomainToken; const toPositiveNumericId = ( @@ -1868,55 +2131,68 @@ export function parseEcommerceUrlOrQuery(raw: string): ParsedEcommerceUrl { 'cellphones.com.vn' ) ? 'cellphones' - : isDomainOrSubdomain(parsedHost, 'thegioididong.com') || - isDomainOrSubdomain(parsedHost, 'topzone.vn') || - isDomainOrSubdomain(parsedHost, 'dienmayxanh.com') + : isDomainOrSubdomain(parsedHost, 'thegioididong.com') ? 'tgdd' - : isDomainOrSubdomain(parsedHost, 'fptshop.com.vn') - ? 'fptshop' - : isDomainOrSubdomain(parsedHost, 'hoanghamobile.com') - ? 'hoangha' - : isDomainOrSubdomain(parsedHost, 'didongviet.vn') - ? 'didongviet' - : isDomainOrSubdomain(parsedHost, 'phongvu.vn') - ? 'phongvu' - : null; + : isDomainOrSubdomain(parsedHost, 'dienmayxanh.com') + ? 'dienmayxanh' + : isDomainOrSubdomain(parsedHost, 'topzone.vn') + ? 'topzone' + : isDomainOrSubdomain(parsedHost, 'fptshop.com.vn') + ? 'fptshop' + : isDomainOrSubdomain(parsedHost, 'hoanghamobile.com') + ? 'hoangha' + : isDomainOrSubdomain(parsedHost, 'didongviet.vn') + ? 'didongviet' + : isDomainOrSubdomain(parsedHost, 'phongvu.vn') + ? 'phongvu' + : isDomainOrSubdomain(parsedHost, 'gearvn.com') + ? 'gearvn' + : isDomainOrSubdomain(parsedHost, 'nguyenkim.com') + ? 'nguyenkim' + : isDomainOrSubdomain(parsedHost, 'shopdunk.com') + ? 'shopdunk' + : isDomainOrSubdomain(parsedHost, 'hacom.vn') + ? 'hacom' + : isDomainOrSubdomain(parsedHost, 'clickbuy.com.vn') + ? 'clickbuy' + : isDomainOrSubdomain( + parsedHost, + 'viettelstore.vn' + ) + ? 'viettelstore' + : isDomainOrSubdomain(parsedHost, 'pico.vn') + ? 'pico' + : isDomainOrSubdomain( + parsedHost, + 'mediamart.vn' + ) + ? 'mediamart' + : isDomainOrSubdomain( + parsedHost, + 'memoryzone.com.vn' + ) + ? 'memoryzone' + : isDomainOrSubdomain( + parsedHost, + 'anphatpc.com.vn' + ) + ? 'anphatpc' + : null; if (retailPlatform) { const segments = parsedPathname .split('/') .map((s) => s.trim()) .filter(Boolean); - const firstSegLower = (segments[0] || '') - .replace(/\.html?$/i, '') - .toLowerCase(); - const lastSeg = - segments[segments.length - 1]?.replace(/\.html?$/i, '') || null; - const lastSegLower = (lastSeg || '').toLowerCase(); - const isValidItemSlug = - Boolean(lastSeg) && - lastSeg!.length >= 2 && - lastSeg!.length <= 256 && - /^[a-z0-9][a-z0-9._-]*[a-z0-9]$/i.test(lastSegLower) && - !lastSegLower.includes('..') && - !/^(?:0+|null|undefined|nan|infinity|-infinity|true|false)$/i.test( - lastSegLower - ) && - !RETAIL_NON_PRODUCT_FIRST_SEGMENTS.has(firstSegLower) && - !RETAIL_NON_PRODUCT_FIRST_SEGMENTS.has(lastSegLower) && - !( - segments.length === 1 && RETAIL_CATEGORY_ROOT_SLUGS.has(firstSegLower) - ) && - !RETAIL_BRAND_LISTING_SLUGS.has(lastSegLower) && - !isSeriesListingSlug(lastSegLower) && - !(retailPlatform === 'tgdd' && segments.length < 2) && - // CellphoneS product pages sit at the root (DOS/Rate#1246). - !(retailPlatform === 'cellphones' && segments.length > 1); + const validItemSlug = extractValidRetailItemSlug( + retailPlatform, + segments + ); return { isUrl: true, platform: retailPlatform, platformShopId: null, - platformItemId: isValidItemSlug ? lastSeg : null, + platformItemId: validItemSlug, internalSlug: null, }; } @@ -2054,18 +2330,17 @@ export function stripEcommerceNoiseTokens(rawText: string): string { /** * Extract a clean, human-readable product search keyword from an e-commerce product URL - * across all 10 supported platforms (Shopee, Lazada, Tiki, TikTok Shop, CellphoneS, - * TGDD/TopZone/DMX, FPT Shop, Hoàng Hà, Di Động Việt, Phong Vũ). + * across all 22 supported platforms (Shopee, Lazada, Tiki, TikTok Shop, CellphoneS, + * TGDD, Điện Máy Xanh, TopZone, FPT Shop, Hoàng Hà, Di Động Việt, Phong Vũ, + * GearVN, Nguyễn Kim, ShopDunk, HACOM, Clickbuy, Viettel Store, Pico, MediaMart, + * MemoryZone, An Phát Computer). */ export function extractProductKeywordFromUrl(rawUrl?: string | null): string { if (!rawUrl || typeof rawUrl !== 'string') return ''; const trimmed = rawUrl.replace(/\p{Cc}+/gu, '').trim(); if (!trimmed || trimmed.length > 2048) return ''; const hasHttpProtocol = /^https?:\/\//i.test(trimmed); - const hasKnownDomainToken = - /(?:^|\/\/|\.)(?:shopee\.vn|lazada\.vn|tiki\.vn|tiktok\.com|cellphones\.com\.vn|thegioididong\.com|topzone\.vn|dienmayxanh\.com|fptshop\.com\.vn|hoanghamobile\.com|didongviet\.vn|phongvu\.vn|rate\.vn)(?:\/|$)/i.test( - trimmed - ); + const hasKnownDomainToken = KNOWN_ECOMMERCE_DOMAIN_TOKEN_REGEX.test(trimmed); if (!hasHttpProtocol && !hasKnownDomainToken) return ''; try { @@ -2089,14 +2364,27 @@ export function extractProductKeywordFromUrl(rawUrl?: string | null): string { const firstSegLower = (rawSegments[0] || '') .replace(/\.html?$/i, '') .toLowerCase(); + const isCollectionProductPath = + rawSegments.length === 4 && + firstSegLower === 'collections' && + rawSegments[2]?.toLowerCase() === 'products'; if ( - RETAIL_NON_PRODUCT_FIRST_SEGMENTS.has(firstSegLower) || + (!isCollectionProductPath && + RETAIL_NON_PRODUCT_FIRST_SEGMENTS.has(firstSegLower)) || firstSegLower === 'shop' || firstSegLower === 'opaanlp' || firstSegLower === 'video' ) { return ''; } + const rawLeaf = rawSegments[rawSegments.length - 1] || ''; + if ( + RETAIL_STATIC_ASSET_EXT_REGEX.test(rawLeaf) || + /\.(?:c|b)$/i.test(rawLeaf) || + /_dm\d+(?:\.html?)?$/i.test(rawLeaf) + ) { + return ''; + } const cleanedPath = decodedPathname .replace(/(?:\/a-i|-i|\/i)\.\d+\.\d+\/?$/i, '') @@ -2105,13 +2393,16 @@ export function extractProductKeywordFromUrl(rawUrl?: string | null): string { .replace(/(?:\/|-)i\d+(?:-s\d+)?\.html?$/i, '') .replace(/(?:\/|-)p\d+\.html?$/i, '') .replace(/--s\d+(?:\.html?)?$/i, '') + .replace(/(?:_id|-pid)\d+(?:\.html?)?$/i, '') .replace(/\.html?$/i, '') + .replace(/^\/collections\/[^/]+\/products\//i, '/') .replace( /^\/(?:products?|san-pham|dien-thoai|dien-thoai-di-dong|dtdd|may-tinh-bang|may-tinh-xach-tay|laptop|dong-ho-thong-minh|tai-nghe|smartphones|tablets|laptops|smartwatches|earbuds|apple|iphone|ipad|macbook|watch|airpods)\//i, '/' ); const segments = cleanedPath.split('/').filter(Boolean); - const lastSeg = segments[segments.length - 1] || ''; + const rawLastSeg = segments[segments.length - 1] || ''; + const lastSeg = rawLastSeg.replace(/^\d{3,8}-(?=.*[a-z])/i, ''); const lastSegLower = lastSeg.toLowerCase(); if ( !lastSeg || @@ -2119,6 +2410,8 @@ export function extractProductKeywordFromUrl(rawUrl?: string | null): string { /^(?:a-)?i\.\d+\.\d+$/i.test(lastSeg) || lastSeg.startsWith('@') || RETAIL_CATEGORY_ROOT_SLUGS.has(lastSegLower) || + RETAIL_NON_PRODUCT_FIRST_SEGMENTS.has(lastSegLower) || + RETAIL_AUTH_OR_NON_PRODUCT_SLUG_REGEX.test(lastSegLower) || /^(?:search|tim-kiem|result|product|products|view)$/.test(lastSegLower) ) { return ''; diff --git a/apps/web/src/server/rate/__tests__/core-rate-architecture.test.ts b/apps/web/src/server/rate/__tests__/core-rate-architecture.test.ts index a06652583..8d11ebba0 100644 --- a/apps/web/src/server/rate/__tests__/core-rate-architecture.test.ts +++ b/apps/web/src/server/rate/__tests__/core-rate-architecture.test.ts @@ -350,7 +350,7 @@ async function runCoreArchitectureSuite() { enum: string[]; } ).enum.length, - 10 + 22 ); console.log( ' ✅ [7/8] OpenAPI 3.1.0 Specification (/api/v1/rate/openapi.json) passed' @@ -623,12 +623,25 @@ async function runCoreArchitectureSuite() { 'shopee', 'lazada', 'tiki', + 'tiktok', 'cellphones', 'tgdd', 'fptshop', 'hoangha', 'didongviet', 'phongvu', + 'dienmayxanh', + 'topzone', + 'gearvn', + 'nguyenkim', + 'shopdunk', + 'hacom', + 'clickbuy', + 'viettelstore', + 'pico', + 'mediamart', + 'memoryzone', + 'anphatpc', ]) { assert.ok( merchantExplorerSrc.includes(`'${plat}'`), @@ -7943,7 +7956,7 @@ async function runCoreArchitectureSuite() { // keep their capitals; two or more other capitalised words in a row mean // Title Case. const names = - /Rate\.vn|Rate Lab|Rate Cloud|DOS ID|DOSafe|JReviews|Markdown|OpenAPI|Next\.js|PostgreSQL|Supabase|Authorization: Bearer|TikTok Shop|Official Mall|Apple Watch|Galaxy Watch|Galaxy Buds|Galaxy Tab|Xiaomi Watch|Xiaomi Pad|Huawei Watch|AirPods Pro|Hoang Ha Mobile|Hoang Ha|Di Dong Viet|The Gioi Di Dong|Phong Vu|Natural Titanium|Alex Nguyen|Wikimedia Commons|Vietnam|Shopee|Lazada|Tiki|Apple|iPhone|Pro|Max|Samsung|Galaxy|Xiaomi|Google|Pixel|Huawei|Garmin|Sony|Bose|Sennheiser|MacBook|iPad|Rate\b|Bayesian \w+|Helpful|Report|[A-Z]{2,}\w*|\w+-[A-Z]\w*/g; + /Rate\.vn|Rate Lab|Rate Cloud|DOS ID|DOSafe|JReviews|Markdown|OpenAPI|Next\.js|PostgreSQL|Supabase|Authorization: Bearer|TikTok Shop|Official Mall|Apple Watch|Galaxy Watch|Galaxy Buds|Galaxy Tab|Xiaomi Watch|Xiaomi Pad|Huawei Watch|AirPods Pro|Hoang Ha Mobile|Hoang Ha|Di Dong Viet|The Gioi Di Dong|Dien May Xanh|TopZone|GearVN|Nguyen Kim|ShopDunk|HACOM|Clickbuy|Viettel Store|Pico|MediaMart|MemoryZone|An Phat Computer|An Phat|Phong Vu|Natural Titanium|Alex Nguyen|Wikimedia Commons|Vietnam|Shopee|Lazada|Tiki|Apple|iPhone|Pro|Max|Samsung|Galaxy|Xiaomi|Google|Pixel|Huawei|Garmin|Sony|Bose|Sennheiser|MacBook|iPad|Rate\b|Bayesian \w+|Helpful|Report|[A-Z]{2,}\w*|\w+-[A-Z]\w*/g; const strip = (s: string) => s.replace(/\{[^}]+\}/g, '').replace(names, ''); const titleCase = /\b[A-Z][a-z]+\b(\s+(&|and|of|to|for|in|the|a|on|with|by|or|from|vs|at)?\s*\b[A-Z][a-z]+\b)+/; @@ -7981,7 +7994,7 @@ async function runCoreArchitectureSuite() { // Names keep their capitals: brands, products, retailers, programs, // places and people used in examples. const names = - /Rate\.vn|Rate Lab|Rate Cloud|DOS ID|DOSafe|JReviews|Markdown|TikTok Shop|Official Mall|Apple Watch|Galaxy Watch|Galaxy Buds|Galaxy Tab|Xiaomi Watch|Xiaomi Pad|Huawei Watch|AirPods Pro|OpenAPI|Next\.js|PostgreSQL|Supabase|Authorization: Bearer|Hoàng Hà|Di Động Việt|Thế Giới Di Động|Phong Vũ|Việt Nam|Wikimedia Commons|Bộ TT&TT|Minh Quân|Hà Nội|Nguyễn Văn A|Pro Max|Pro|Titan Tự Nhiên|AI Review Analyzer|Rate Trust Score|Bayesian|GSMArena|PhoneArena|GitHub|Wi-Fi|Bluetooth|Hi-Res|Qi|MagSafe|Hz|Bayes|Rate Lab|API Playground|Kiểm tra link|Liên hệ|Hữu ích|Báo cáo|Shopee|Lazada|Tiki|Apple|iPhone|Samsung|Galaxy|Xiaomi|Google|Pixel|Sony|Bose|Sennheiser|MacBook|iPad|Rate\b|[A-ZĐ]{2,}\w*/g; + /Rate\.vn|Rate Lab|Rate Cloud|DOS ID|DOSafe|JReviews|Markdown|TikTok Shop|Official Mall|Apple Watch|Galaxy Watch|Galaxy Buds|Galaxy Tab|Xiaomi Watch|Xiaomi Pad|Huawei Watch|AirPods Pro|OpenAPI|Next\.js|PostgreSQL|Supabase|Authorization: Bearer|Hoàng Hà|Di Động Việt|Thế Giới Di Động|Điện Máy Xanh|TopZone|GearVN|Nguyễn Kim|ShopDunk|HACOM|Clickbuy|Viettel Store|Pico|MediaMart|MemoryZone|An Phát Computer|An Phát|Phong Vũ|Việt Nam|Wikimedia Commons|Bộ TT&TT|Minh Quân|Hà Nội|Nguyễn Văn A|Pro Max|Pro|Titan Tự Nhiên|AI Review Analyzer|Rate Trust Score|Bayesian|GSMArena|PhoneArena|GitHub|Wi-Fi|Bluetooth|Hi-Res|Qi|MagSafe|Hz|Bayes|Rate Lab|API Playground|Kiểm tra link|Liên hệ|Hữu ích|Báo cáo|Shopee|Lazada|Tiki|Apple|iPhone|Samsung|Galaxy|Xiaomi|Google|Pixel|Sony|Bose|Sennheiser|MacBook|iPad|Rate\b|[A-ZĐ]{2,}\w*/g; const strip = (s: string) => s .normalize('NFC') @@ -14989,6 +15002,209 @@ async function runCoreArchitectureSuite() { await runProductPointsDisplaySuite(); } + // DOS/Rate#1850: All 12 Wave 1-3 retail platforms across web URL parser, lookup candidate IDs, OpenAPI, and SQL-safe crowd ingest boundary + { + const { + EXTENSION_CAPABILITY_MATRIX, + buildCandidateExternalItemIds, + detectPlatformFromInput, + ingestExtensionCrowdSignal, + } = await import('../extension'); + const { SUPPORTED_PLATFORM_SLUGS } = await import('../api-handler'); + const { extractProductKeywordFromUrl, parseEcommerceUrlOrQuery } = + await import('../../../lib/rate-domain-core'); + + const wave1To3Cases = [ + { + platform: 'dienmayxanh' as const, + pdpUrl: 'https://www.dienmayxanh.com/dtdd/iphone-16-pro-max-256gb', + nonPdpUrl: 'https://www.dienmayxanh.com/dtdd', + expectedSlug: 'iphone-16-pro-max-256gb', + expectedPrefixedId: 'dmx-iphone-16-pro-max-256gb', + }, + { + platform: 'topzone' as const, + pdpUrl: 'https://www.topzone.vn/iphone/iphone-16-pro-max-256gb', + nonPdpUrl: 'https://www.topzone.vn/iphone', + expectedSlug: 'iphone-16-pro-max-256gb', + expectedPrefixedId: 'tz-iphone-16-pro-max-256gb', + }, + { + platform: 'gearvn' as const, + pdpUrl: 'https://gearvn.com/products/laptop-asus-rog-strix-g16', + nonPdpUrl: 'https://gearvn.com/collections/laptop-gaming', + expectedSlug: 'laptop-asus-rog-strix-g16', + expectedPrefixedId: 'gearvn-laptop-asus-rog-strix-g16', + }, + { + platform: 'nguyenkim' as const, + pdpUrl: 'https://www.nguyenkim.com/dien-thoai-iphone-16-pro-max.html', + nonPdpUrl: 'https://www.nguyenkim.com/dien-thoai.c', + expectedSlug: 'dien-thoai-iphone-16-pro-max', + expectedPrefixedId: 'nk-dien-thoai-iphone-16-pro-max', + }, + { + platform: 'shopdunk' as const, + pdpUrl: 'https://shopdunk.com/iphone-16-pro-max-256gb', + nonPdpUrl: 'https://shopdunk.com/iphone', + expectedSlug: 'iphone-16-pro-max-256gb', + expectedPrefixedId: 'shopdunk-iphone-16-pro-max-256gb', + }, + { + platform: 'hacom' as const, + pdpUrl: 'https://hacom.vn/laptop-apple-macbook-air-m3-256gb', + nonPdpUrl: 'https://hacom.vn/laptop-gaming-do-hoa', + expectedSlug: 'laptop-apple-macbook-air-m3-256gb', + expectedPrefixedId: 'hacom-laptop-apple-macbook-air-m3-256gb', + }, + { + platform: 'clickbuy' as const, + pdpUrl: 'https://clickbuy.com.vn/iphone-16-pro-max-256gb', + nonPdpUrl: 'https://clickbuy.com.vn/sua-chua', + expectedSlug: 'iphone-16-pro-max-256gb', + expectedPrefixedId: 'cb-iphone-16-pro-max-256gb', + }, + { + platform: 'viettelstore' as const, + pdpUrl: + 'https://viettelstore.vn/dien-thoai/iphone-16-pro-max-pid341920.html', + nonPdpUrl: 'https://viettelstore.vn/ket-qua-tim-kiem.html', + expectedSlug: 'iphone-16-pro-max-pid341920', + expectedPrefixedId: 'vts-iphone-16-pro-max-pid341920', + }, + { + platform: 'pico' as const, + pdpUrl: 'https://pico.vn/45678-dien-thoai-iphone-16-pro-max.html', + nonPdpUrl: 'https://pico.vn/dien-thoai', + expectedSlug: '45678-dien-thoai-iphone-16-pro-max', + expectedPrefixedId: 'pico-45678-dien-thoai-iphone-16-pro-max', + }, + { + platform: 'mediamart' as const, + pdpUrl: 'https://mediamart.vn/smartphones/iphone-16-pro-max-256gb', + nonPdpUrl: 'https://mediamart.vn/smartphones', + expectedSlug: 'iphone-16-pro-max-256gb', + expectedPrefixedId: 'mm-iphone-16-pro-max-256gb', + }, + { + platform: 'memoryzone' as const, + pdpUrl: + 'https://memoryzone.com.vn/products/laptop-apple-macbook-air-m3', + nonPdpUrl: 'https://memoryzone.com.vn/collections/laptop', + expectedSlug: 'laptop-apple-macbook-air-m3', + expectedPrefixedId: 'mz-laptop-apple-macbook-air-m3', + }, + { + platform: 'anphatpc' as const, + pdpUrl: + 'https://www.anphatpc.com.vn/laptop-apple-macbook-air-13.6-inch-m3_id49201.html', + nonPdpUrl: + 'https://www.anphatpc.com.vn/may-tinh-xach-tay-laptop_dm1005.html', + expectedSlug: 'laptop-apple-macbook-air-13.6-inch-m3_id49201', + expectedPrefixedId: + 'ap-laptop-apple-macbook-air-13_2e6-inch-m3_5fid49201', + }, + ]; + + assert.equal(SUPPORTED_PLATFORM_SLUGS.size, 22); + + let rpcInvoked = false; + const fakeRateClient = { + rpc: async () => { + rpcInvoked = true; + return { data: null, error: null }; + }, + }; + + for (const tc of wave1To3Cases) { + assert.ok(SUPPORTED_PLATFORM_SLUGS.has(tc.platform), tc.platform); + const cap = EXTENSION_CAPABILITY_MATRIX[tc.platform]; + assert.ok(cap, tc.platform); + assert.equal(cap.lookup, true, tc.platform); + assert.equal(cap.exactItemMatch, true, tc.platform); + assert.equal(cap.crossCatalogMatch, true, tc.platform); + assert.equal(cap.crowdVerifyQueue, false, tc.platform); + + assert.equal(detectPlatformFromInput(null, tc.pdpUrl), tc.platform); + assert.equal(detectPlatformFromInput(tc.platform, null), tc.platform); + + const parsedPdp = parseEcommerceUrlOrQuery(tc.pdpUrl); + assert.equal(parsedPdp.isUrl, true, tc.pdpUrl); + assert.equal(parsedPdp.platform, tc.platform, tc.pdpUrl); + assert.equal(parsedPdp.platformItemId, tc.expectedSlug, tc.pdpUrl); + + const parsedNonPdp = parseEcommerceUrlOrQuery(tc.nonPdpUrl); + assert.equal(parsedNonPdp.isUrl, true, tc.nonPdpUrl); + assert.equal(parsedNonPdp.platform, tc.platform, tc.nonPdpUrl); + assert.equal(parsedNonPdp.platformItemId, null, tc.nonPdpUrl); + + const kw = extractProductKeywordFromUrl(tc.pdpUrl); + assert.ok(kw.length >= 4, `${tc.platform} keyword: "${kw}"`); + + const candidateIds = buildCandidateExternalItemIds({ + externalId: tc.expectedSlug, + platform: tc.platform, + }); + assert.ok( + candidateIds.includes(tc.expectedPrefixedId), + `${tc.platform} candidates ${JSON.stringify(candidateIds)} missing ${tc.expectedPrefixedId}` + ); + + // Crowd ingest must stop cleanly at capability gate without calling PostgreSQL RPC + const ingestRes = await ingestExtensionCrowdSignal({ + platform: tc.platform, + externalItemId: tc.expectedSlug, + url: tc.pdpUrl, + title: 'Apple iPhone 16 Pro Max 256GB', + price: 29_990_000, + userConsentOptIn: true, + rateClient: fakeRateClient, + }); + assert.equal(ingestRes.accepted, false, tc.platform); + assert.equal( + ingestRes.jobState, + 'platform_worker_pending_phase_5_1', + tc.platform + ); + } + assert.equal( + rpcInvoked, + false, + 'Wave 1-3 crowd ingest must never call enqueue_crowd_verify_signal before DOS-Me migration' + ); + + // Legacy compatibility: older extension clients sending platform=tgdd on topzone.vn / dienmayxanh.com upgrade cleanly + assert.equal( + detectPlatformFromInput( + 'tgdd', + 'https://www.topzone.vn/iphone/iphone-16-pro-max' + ), + 'topzone' + ); + assert.equal( + detectPlatformFromInput( + 'tgdd', + 'https://www.dienmayxanh.com/dtdd/iphone-16-pro-max' + ), + 'dienmayxanh' + ); + assert.ok( + buildCandidateExternalItemIds({ + externalId: 'iphone-16-pro-max', + platform: 'topzone', + }).includes('tgdd-iphone-16-pro-max') + ); + assert.ok( + buildCandidateExternalItemIds({ + externalId: 'iphone-16-pro-max', + platform: 'dienmayxanh', + }).includes('tgdd-iphone-16-pro-max') + ); + console.log( + ' ✅ DOS/Rate#1850 Wave 1-3 12 retail platforms web & API parity passed' + ); + } + console.log('🎉 All Rate.vn Core Architecture tests passed!'); } diff --git a/apps/web/src/server/rate/api-handler.ts b/apps/web/src/server/rate/api-handler.ts index be12ef508..e13d49c41 100644 --- a/apps/web/src/server/rate/api-handler.ts +++ b/apps/web/src/server/rate/api-handler.ts @@ -870,7 +870,7 @@ export function extractClientRateLimitKey( return 'anon'; } -/** The 10 marketplaces and retailers Rate tracks (DOS/Rate#1308). */ +/** The 22 marketplaces and retailers Rate tracks (DOS/Rate#1308, #1850). */ export const SUPPORTED_PLATFORM_SLUGS: ReadonlySet = new Set([ 'shopee', 'lazada', @@ -882,6 +882,18 @@ export const SUPPORTED_PLATFORM_SLUGS: ReadonlySet = new Set([ 'hoangha', 'didongviet', 'phongvu', + 'dienmayxanh', + 'topzone', + 'gearvn', + 'nguyenkim', + 'shopdunk', + 'hacom', + 'clickbuy', + 'viettelstore', + 'pico', + 'mediamart', + 'memoryzone', + 'anphatpc', ]); /** diff --git a/apps/web/src/server/rate/extension.ts b/apps/web/src/server/rate/extension.ts index 7d450fafb..e116835c6 100644 --- a/apps/web/src/server/rate/extension.ts +++ b/apps/web/src/server/rate/extension.ts @@ -68,7 +68,19 @@ export type SupportedEcommercePlatform = | 'fptshop' | 'hoangha' | 'didongviet' - | 'phongvu'; + | 'phongvu' + | 'dienmayxanh' + | 'topzone' + | 'gearvn' + | 'nguyenkim' + | 'shopdunk' + | 'hacom' + | 'clickbuy' + | 'viettelstore' + | 'pico' + | 'mediamart' + | 'memoryzone' + | 'anphatpc'; export interface PlatformCapability { platform: SupportedEcommercePlatform; @@ -163,6 +175,106 @@ export const EXTENSION_CAPABILITY_MATRIX: Record< crossCatalogMatch: true, crowdVerifyQueue: true, }, + // Wave 1-3 retail chains (DOS/Rate#1850): full lookup, exact item match, and + // cross-catalog comparison are enabled; `crowdVerifyQueue` stays false until + // a DOS-Me migration widens `rate.enqueue_crowd_verify_signal` and M2 SQL + // CHECK constraints (`DOS/Rate#1762`). + dienmayxanh: { + platform: 'dienmayxanh', + displayName: 'Điện Máy Xanh', + lookup: true, + exactItemMatch: true, + crossCatalogMatch: true, + crowdVerifyQueue: false, + }, + topzone: { + platform: 'topzone', + displayName: 'TopZone', + lookup: true, + exactItemMatch: true, + crossCatalogMatch: true, + crowdVerifyQueue: false, + }, + gearvn: { + platform: 'gearvn', + displayName: 'GearVN', + lookup: true, + exactItemMatch: true, + crossCatalogMatch: true, + crowdVerifyQueue: false, + }, + nguyenkim: { + platform: 'nguyenkim', + displayName: 'Nguyễn Kim', + lookup: true, + exactItemMatch: true, + crossCatalogMatch: true, + crowdVerifyQueue: false, + }, + shopdunk: { + platform: 'shopdunk', + displayName: 'ShopDunk', + lookup: true, + exactItemMatch: true, + crossCatalogMatch: true, + crowdVerifyQueue: false, + }, + hacom: { + platform: 'hacom', + displayName: 'HACOM', + lookup: true, + exactItemMatch: true, + crossCatalogMatch: true, + crowdVerifyQueue: false, + }, + clickbuy: { + platform: 'clickbuy', + displayName: 'Clickbuy', + lookup: true, + exactItemMatch: true, + crossCatalogMatch: true, + crowdVerifyQueue: false, + }, + viettelstore: { + platform: 'viettelstore', + displayName: 'Viettel Store', + lookup: true, + exactItemMatch: true, + crossCatalogMatch: true, + crowdVerifyQueue: false, + }, + pico: { + platform: 'pico', + displayName: 'Pico', + lookup: true, + exactItemMatch: true, + crossCatalogMatch: true, + crowdVerifyQueue: false, + }, + mediamart: { + platform: 'mediamart', + displayName: 'MediaMart', + lookup: true, + exactItemMatch: true, + crossCatalogMatch: true, + crowdVerifyQueue: false, + }, + memoryzone: { + platform: 'memoryzone', + displayName: 'MemoryZone', + lookup: true, + exactItemMatch: true, + crossCatalogMatch: true, + crowdVerifyQueue: false, + }, + anphatpc: { + platform: 'anphatpc', + displayName: 'An Phát Computer', + lookup: true, + exactItemMatch: true, + crossCatalogMatch: true, + crowdVerifyQueue: false, + }, }; /** @@ -412,31 +524,9 @@ export function extractKeywordFromProductUrl(rawUrl?: string | null): string { return extractProductKeywordFromUrl(rawUrl); } -export function detectPlatformFromInput( - rawPlatform?: string | null, +function detectPlatformFromUrlHost( rawUrl?: string | null ): SupportedEcommercePlatform | null { - const norm = - typeof rawPlatform === 'string' - ? rawPlatform - .replace(/\p{Cc}+/gu, '') - .trim() - .toLowerCase() - : ''; - if ( - norm === 'shopee' || - norm === 'lazada' || - norm === 'tiki' || - norm === 'tiktok' || - norm === 'cellphones' || - norm === 'tgdd' || - norm === 'fptshop' || - norm === 'hoangha' || - norm === 'didongviet' || - norm === 'phongvu' - ) { - return norm; - } if (!rawUrl || typeof rawUrl !== 'string') return null; if (/\p{Cc}/u.test(rawUrl)) return null; const trimmedUrl = rawUrl.trim(); @@ -477,20 +567,53 @@ export function detectPlatformFromInput( if (isDomainOrSubdomain(host, 'tiki.vn')) return 'tiki'; if (isDomainOrSubdomain(host, 'tiktok.com')) return 'tiktok'; if (isDomainOrSubdomain(host, 'cellphones.com.vn')) return 'cellphones'; - if ( - isDomainOrSubdomain(host, 'thegioididong.com') || - isDomainOrSubdomain(host, 'topzone.vn') || - isDomainOrSubdomain(host, 'dienmayxanh.com') - ) { - return 'tgdd'; - } + if (isDomainOrSubdomain(host, 'thegioididong.com')) return 'tgdd'; + if (isDomainOrSubdomain(host, 'dienmayxanh.com')) return 'dienmayxanh'; + if (isDomainOrSubdomain(host, 'topzone.vn')) return 'topzone'; if (isDomainOrSubdomain(host, 'fptshop.com.vn')) return 'fptshop'; if (isDomainOrSubdomain(host, 'hoanghamobile.com')) return 'hoangha'; if (isDomainOrSubdomain(host, 'didongviet.vn')) return 'didongviet'; if (isDomainOrSubdomain(host, 'phongvu.vn')) return 'phongvu'; + if (isDomainOrSubdomain(host, 'gearvn.com')) return 'gearvn'; + if (isDomainOrSubdomain(host, 'nguyenkim.com')) return 'nguyenkim'; + if (isDomainOrSubdomain(host, 'shopdunk.com')) return 'shopdunk'; + if (isDomainOrSubdomain(host, 'hacom.vn')) return 'hacom'; + if (isDomainOrSubdomain(host, 'clickbuy.com.vn')) return 'clickbuy'; + if (isDomainOrSubdomain(host, 'viettelstore.vn')) return 'viettelstore'; + if (isDomainOrSubdomain(host, 'pico.vn')) return 'pico'; + if (isDomainOrSubdomain(host, 'mediamart.vn')) return 'mediamart'; + if (isDomainOrSubdomain(host, 'memoryzone.com.vn')) return 'memoryzone'; + if (isDomainOrSubdomain(host, 'anphatpc.com.vn')) return 'anphatpc'; return null; } +export function detectPlatformFromInput( + rawPlatform?: string | null, + rawUrl?: string | null +): SupportedEcommercePlatform | null { + const norm = + typeof rawPlatform === 'string' + ? rawPlatform + .replace(/\p{Cc}+/gu, '') + .trim() + .toLowerCase() + : ''; + const urlPlatform = detectPlatformFromUrlHost(rawUrl); + if (Object.hasOwn(EXTENSION_CAPABILITY_MATRIX, norm)) { + // Older extension builds sent `platform=tgdd` for MWG sister domains + // `topzone.vn` and `dienmayxanh.com` before DOS/Rate#1850 promoted them to + // first-class platforms; upgrade seamlessly when `rawUrl` names one. + if ( + norm === 'tgdd' && + (urlPlatform === 'topzone' || urlPlatform === 'dienmayxanh') + ) { + return urlPlatform; + } + return norm as SupportedEcommercePlatform; + } + return urlPlatform; +} + /** * Gatekeeper Layer 0: Distinguish accessories/spare parts from actual phones/tablets/laptops/earbuds. */ @@ -1143,17 +1266,74 @@ export function buildCandidateExternalItemIds(params: { tiktok: 'tts-', cellphones: 'cps-', tgdd: 'tgdd-', + dienmayxanh: 'dmx-', + topzone: 'tz-', fptshop: 'fpt-', hoangha: 'hhm-', didongviet: 'ddv-', phongvu: 'pv-', + gearvn: 'gearvn-', + nguyenkim: 'nk-', + shopdunk: 'shopdunk-', + hacom: 'hacom-', + clickbuy: 'cb-', + viettelstore: 'vts-', + pico: 'pico-', + mediamart: 'mm-', + memoryzone: 'mz-', + anphatpc: 'ap-', }; + const waveUnderscorePlatforms = new Set([ + 'nguyenkim', + 'shopdunk', + 'hacom', + 'clickbuy', + 'viettelstore', + 'pico', + 'mediamart', + 'memoryzone', + ]); const prefix = params.platform ? prefixMap[params.platform] : undefined; if (prefix && !cleanExternalId.startsWith(prefix)) { const prefixed = `${prefix}${cleanExternalId}`; if (isValidExternalEntityId(prefixed)) { candidateItemIds.add(prefixed); } + const lowerPrefixed = `${prefix}${cleanExternalId.toLowerCase()}`; + if (isValidExternalEntityId(lowerPrefixed)) { + candidateItemIds.add(lowerPrefixed); + } + if ( + params.platform && + waveUnderscorePlatforms.has(params.platform) && + cleanExternalId.includes('_') + ) { + const waveEncoded = `${prefix}${cleanExternalId.toLowerCase().replace(/_/g, '_5f')}`; + if (isValidExternalEntityId(waveEncoded)) { + candidateItemIds.add(waveEncoded); + } + } + if (params.platform === 'anphatpc') { + const apEncodedSlug = cleanExternalId + .toLowerCase() + .replace(/[^a-z0-9-]/g, (ch) => { + const hex = ch.codePointAt(0)?.toString(16).padStart(2, '0') ?? '00'; + return `_${hex}`; + }); + const apCandidate = `${prefix}${apEncodedSlug}`; + if (isValidExternalEntityId(apCandidate)) { + candidateItemIds.add(apCandidate); + } + } + } + if ( + (params.platform === 'topzone' || params.platform === 'dienmayxanh') && + !cleanExternalId.startsWith('tgdd-') + ) { + const legacyTgdd = `tgdd-${cleanExternalId}`; + if (isValidExternalEntityId(legacyTgdd)) { + candidateItemIds.add(legacyTgdd); + } } return Array.from(candidateItemIds); } diff --git a/apps/web/src/server/rate/openapi.ts b/apps/web/src/server/rate/openapi.ts index b06001f14..12393551a 100644 --- a/apps/web/src/server/rate/openapi.ts +++ b/apps/web/src/server/rate/openapi.ts @@ -1070,7 +1070,7 @@ function buildBaseRateOpenApiSpec( summary: 'Full Web Product & URL Inspector with price verdict and price history chart', description: - 'Runs the complete hybrid lookup pipeline for the `/inspect` web portal: canonicalizes 10 supported e-commerce/retailer platforms, blocks non-hardware accessories, resolves SKU variant capacity, computes the price verdict (`PriceVerdictLevel`), and returns full product detail with the Deal Radar signal (`data.radarSignal`, null when no product matched). One of `q` or `url` is required. Limited to 30 requests per minute per client IP (shared with `/lookup`, counted on each server instance); past it the answer is 429 with `Retry-After`.', + 'Runs the complete hybrid lookup pipeline for the `/inspect` web portal: canonicalizes 22 supported e-commerce/retailer platforms, blocks non-hardware accessories, resolves SKU variant capacity, computes the price verdict (`PriceVerdictLevel`), and returns full product detail with the Deal Radar signal (`data.radarSignal`, null when no product matched). One of `q` or `url` is required. Limited to 30 requests per minute per client IP (shared with `/lookup`, counted on each server instance); past it the answer is 429 with `Retry-After`.', tags: ['URL Inspector & Extension MV3'], parameters: [ { @@ -1156,7 +1156,7 @@ function buildBaseRateOpenApiSpec( summary: 'Low-latency Hybrid Lookup for Rate Browser Extension Manifest V3', description: - 'Dedicated read-only lookup endpoint for the Rate Browser Extension MV3 across 10 platforms (`shopee`, `lazada`, `tiki`, `tiktok`, `cellphones`, `tgdd`, `fptshop`, `hoangha`, `didongviet`, `phongvu`). Performs deterministic `platform_item_id` lookup, canonical model fallback, accessory gatekeeping, price verdict calculation (`PriceVerdictLevel`), and returns the Deal Radar signal as `data.radarSignal`.', + 'Dedicated read-only lookup endpoint for the Rate Browser Extension MV3 across 22 platforms (`shopee`, `lazada`, `tiki`, `tiktok`, `cellphones`, `tgdd`, `fptshop`, `hoangha`, `didongviet`, `phongvu`, `dienmayxanh`, `topzone`, `gearvn`, `nguyenkim`, `shopdunk`, `hacom`, `clickbuy`, `viettelstore`, `pico`, `mediamart`, `memoryzone`, `anphatpc`). Performs deterministic `platform_item_id` lookup, canonical model fallback, accessory gatekeeping, price verdict calculation (`PriceVerdictLevel`), and returns the Deal Radar signal as `data.radarSignal`.', tags: ['URL Inspector & Extension MV3'], parameters: [ { @@ -2120,7 +2120,7 @@ function buildBaseRateOpenApiSpec( type: 'string', enum: supportedPlatforms, description: - '10 supported Vietnamese e-commerce marketplaces and authorized electronics retailers.', + '22 supported Vietnamese e-commerce marketplaces and authorized electronics retailers.', }, CanonicalRateCategorySlug: { type: 'string', diff --git a/packages/shared-data/src/__tests__/shared-data.test.ts b/packages/shared-data/src/__tests__/shared-data.test.ts index 5d6660de3..25a7730d3 100644 --- a/packages/shared-data/src/__tests__/shared-data.test.ts +++ b/packages/shared-data/src/__tests__/shared-data.test.ts @@ -312,7 +312,7 @@ function testMasterProductAndScrapedProductSchemas(): void { assert.deepEqual(master.images, []); assert.deepEqual(master.metadata, {}); - for (const platform of [ + const all22Platforms = [ 'shopee', 'lazada', 'tiki', @@ -323,16 +323,32 @@ function testMasterProductAndScrapedProductSchemas(): void { 'hoangha', 'didongviet', 'phongvu', - ]) { + 'dienmayxanh', + 'topzone', + 'gearvn', + 'nguyenkim', + 'shopdunk', + 'hacom', + 'clickbuy', + 'viettelstore', + 'pico', + 'mediamart', + 'memoryzone', + 'anphatpc', + ]; + assert.deepEqual(SupportedEcommercePlatformSchema.options, all22Platforms); + for (const platform of all22Platforms) { assert.equal( SupportedEcommercePlatformSchema.safeParse(platform).success, true ); } - assert.equal( - SupportedEcommercePlatformSchema.safeParse('amazon').success, - false - ); + for (const unsupported of ['amazon', 'ebay', 'GEARVN', 'anphat', '']) { + assert.equal( + SupportedEcommercePlatformSchema.safeParse(unsupported).success, + false + ); + } const scraped = ScrapedProductSchema.parse({ platform: 'shopee', diff --git a/packages/shared-data/src/rules/extension-observation.ts b/packages/shared-data/src/rules/extension-observation.ts index 1a31b039b..e11546847 100644 --- a/packages/shared-data/src/rules/extension-observation.ts +++ b/packages/shared-data/src/rules/extension-observation.ts @@ -12,6 +12,13 @@ export const EXTENSION_OBSERVATION_VERSION = 1; +/** + * Marketplaces accepted by `rate.extension_observations` and + * `rate.submit_extension_observation` in PostgreSQL (`20261106160000` in + * `DOS-Me`). Kept at the 10 SQL-checked marketplaces until a coordinated + * `DOS-Me` migration widens the table `CHECK` and RPC allowlist (see + * `DOS/Rate#1762` and `DOS/Rate#1850`). + */ const EXTENSION_MARKETPLACES = [ 'shopee', 'lazada', diff --git a/packages/shared-data/src/schemas/specs.schema.ts b/packages/shared-data/src/schemas/specs.schema.ts index 8d4eedc70..d7ed5f457 100644 --- a/packages/shared-data/src/schemas/specs.schema.ts +++ b/packages/shared-data/src/schemas/specs.schema.ts @@ -188,8 +188,24 @@ export const SupportedEcommercePlatformSchema = z.enum([ 'hoangha', 'didongviet', 'phongvu', + 'dienmayxanh', + 'topzone', + 'gearvn', + 'nguyenkim', + 'shopdunk', + 'hacom', + 'clickbuy', + 'viettelstore', + 'pico', + 'mediamart', + 'memoryzone', + 'anphatpc', ]); +export type SupportedEcommercePlatform = z.infer< + typeof SupportedEcommercePlatformSchema +>; + export const ScrapedReviewerSchema = z.object({ key: z.string().max(128).optional(), isAnonymous: z.boolean().optional(), From 4822d0174bc3bd4bc37a2703a66bacb55f8fdf9f Mon Sep 17 00:00:00 2001 From: JOY <5027251+JOY@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:25:51 +0700 Subject: [PATCH 2/3] fix(shared): harden Wave 1-3 URL, SQL, and MV3 parity --- .../src/extractors/ecommerce-detector.ts | 261 ++++++++++++++++- apps/extension/src/i18n.ts | 1 + apps/extension/src/security-guards.ts | 12 +- apps/extension/src/sidepanel/sidepanel.ts | 4 +- apps/extension/src/test-extension-pipeline.ts | 127 +++++++- .../app/api/v1/rate/extension/ingest/route.ts | 2 +- .../watchlist/WatchlistWorkspace.tsx | 24 +- apps/web/src/lib/rate-api.ts | 70 +++-- apps/web/src/lib/rate-domain-core.ts | 276 +++++++++++++++++- .../__tests__/core-rate-architecture.test.ts | 32 ++ apps/web/src/server/rate/extension.ts | 98 ++++--- apps/web/src/server/rate/openapi.ts | 8 +- .../src/__tests__/shared-data.test.ts | 26 +- .../src/rules/extension-observation.ts | 9 +- .../test-extension-observations-proposal.mjs | 14 + 15 files changed, 835 insertions(+), 129 deletions(-) diff --git a/apps/extension/src/extractors/ecommerce-detector.ts b/apps/extension/src/extractors/ecommerce-detector.ts index 6ac5514d5..20386e14a 100644 --- a/apps/extension/src/extractors/ecommerce-detector.ts +++ b/apps/extension/src/extractors/ecommerce-detector.ts @@ -324,6 +324,186 @@ const ACCESSORY_SLUG_PREFIX = const isSeriesListingSlug = (slug: string) => /-series$/.test(slug) && !ACCESSORY_SLUG_PREFIX.test(slug); +const MEDIAMART_ALLOWED_CATEGORY_PREFIXES = new Set([ + 'smartphones', + 'dien-thoai', + 'dien-thoai-di-dong', + 'laptop', + 'may-tinh-xach-tay', + 'macbook', + 'may-tinh-bang', + 'tablet', + 'ipad', + 'smartwatch', + 'dong-ho-thong-minh', + 'tai-nghe', + 'san-pham', + 'products', +]); + +const HACOM_CATEGORY_BRAND_SLUG_REGEX = + /^(?:laptop-(?:asus|dell|acer|lenovo|hp|msi|apple|lg|gigabyte)|may-tinh-nguyen-bo-theo-hang|may-tinh-mini-da-dung)$/i; + +const CLICKBUY_NON_PRODUCT_SLUG_REGEX = + /^(?:dien-thoai-(?:iphone|samsung|xiaomi|oppo|vivo|realme|nokia|honor|asus|tcl|google|sony|tecno|infinix|masstel|itel)|(?:iphone|samsung|dien-thoai|ipad|macbook|apple-watch)-cu|thay-pin|ep-kinh|google-pixel|trang)$/i; + +const VIETTELSTORE_PRODUCT_CATEGORY_SEGMENTS = new Set([ + 'dien-thoai', + 'may-tinh-bang', + 'tablet', + 'laptop', + 'may-tinh-xach-tay', + 'dong-ho-thong-minh', + 'dong-ho', + 'apple-watch', + 'smartwatch', + 'tai-nghe', + 'am-thanh', + 'loa', + 'phu-kien', + 'man-hinh', + 'pc', + 'tivi', + 'san-pham', + 'products', +]); + +const VIETTELSTORE_NON_PRODUCT_PREFIXES = new Set([ + 'tra-gop', + 'so-sanh', + 'so-sanh-san-pham', + 'tin-tuc', + 'chuyen-muc-tin', + 'landing', + 'khuyen-mai', + 'site', + 'he-thong-sieu-thi', + 'sieu-thi', + 'ho-tro', + 'tuyen-dung', + 'account', + 'login', + 'dang-nhap', + 'register', + 'dang-ky', + 'auth', + 'captcha', + 'challenge', + 'cart', + 'gio-hang', + 'dtdd', + 'mtb', + 'tim-kiem', + 'ket-qua-tim-kiem', +]); + +const VIETTELSTORE_CATEGORY_SLUG_REGEX = + /^(?:dtdd(?:-|$)|mtb(?:-|$)|laptop-(?:apple|asus|acer|dell|hp|lenovo|msi|lg)$|phu-kien-o-to$|bao-da-op-lung$|tam-dan$)/i; + +const ANPHAT_EXTRA_NON_PRODUCT_FIRST_SEGMENTS = new Set([ + 'template', + 'templates', + 'includes', + 'user', + 'order', + 'don-hang', + 'rss', + 'sitemap', + 'robots.txt', +]); + +const ANPHAT_INFO_SUFFIX_REGEX = + /(?:^|-)(?:he-thong-showroom|tin-khuyen-mai|tin-tuc|khuyen-mai|bao-hanh|chinh-sach|huong-dan|lien-he|tuyen-dung|gioi-thieu|pc-an-phat)$/i; + +function sha1Hex10(input: string): string { + const bytes = new TextEncoder().encode(input); + const bitLen = bytes.length * 8; + const paddedLen = (((bytes.length + 8) >>> 6) + 1) << 6; + const buf = new Uint8Array(paddedLen); + buf.set(bytes); + buf[bytes.length] = 0x80; + const view = new DataView(buf.buffer); + view.setUint32(paddedLen - 8, Math.floor(bitLen / 0x100000000), false); + view.setUint32(paddedLen - 4, bitLen >>> 0, false); + + let h0 = 0x67452301; + let h1 = 0xefcdab89; + let h2 = 0x98badcfe; + let h3 = 0x10325476; + let h4 = 0xc3d2e1f0; + const w = new Uint32Array(80); + + for (let offset = 0; offset < paddedLen; offset += 64) { + for (let i = 0; i < 16; i++) { + w[i] = view.getUint32(offset + i * 4, false); + } + for (let i = 16; i < 80; i++) { + const n = w[i - 3]! ^ w[i - 8]! ^ w[i - 14]! ^ w[i - 16]!; + w[i] = ((n << 1) | (n >>> 31)) >>> 0; + } + + let a = h0; + let b = h1; + let c = h2; + let d = h3; + let e = h4; + + for (let i = 0; i < 80; i++) { + let f: number; + let k: number; + if (i < 20) { + f = (b & c) | (~b & d); + k = 0x5a827999; + } else if (i < 40) { + f = b ^ c ^ d; + k = 0x6ed9eba1; + } else if (i < 60) { + f = (b & c) | (b & d) | (c & d); + k = 0x8f1bbcdc; + } else { + f = b ^ c ^ d; + k = 0xca62c1d6; + } + const temp = + ((((a << 5) | (a >>> 27)) >>> 0) + (f >>> 0) + e + k + w[i]!) >>> 0; + e = d; + d = c; + c = ((b << 30) | (b >>> 2)) >>> 0; + b = a; + a = temp; + } + + h0 = (h0 + a) >>> 0; + h1 = (h1 + b) >>> 0; + h2 = (h2 + c) >>> 0; + h3 = (h3 + d) >>> 0; + h4 = (h4 + e) >>> 0; + } + + return ( + h0.toString(16).padStart(8, '0') + h1.toString(16).padStart(8, '0') + ).slice(0, 10); +} + +export function sanitizeAnPhatItemId(rawKey: string): string { + const cleaned = rawKey.trim().replace(/^\/+|\/+$/g, ''); + if (!cleaned) return ''; + const normalized = cleaned.toLowerCase().replace(/[^a-z0-9-]/g, (ch) => { + const hex = ch.codePointAt(0)?.toString(16).padStart(2, '0') ?? '00'; + return `_${hex}`; + }); + if (!normalized) return ''; + const maxSlugLen = 125; + if (normalized.length <= maxSlugLen) { + return `ap-${normalized}`; + } + const digest = sha1Hex10(normalized); + const keepLen = Math.max(1, maxSlugLen - digest.length - 1); + let trimmed = normalized.slice(0, keepLen).replace(/[-_]+$/g, ''); + if (!trimmed) trimmed = normalized.slice(0, keepLen); + return `ap-${trimmed}-${digest}`; +} + function extractValidRetailItemSlug( retailPlatform: SupportedEcommercePlatform, segments: readonly string[] @@ -376,7 +556,12 @@ function extractValidRetailItemSlug( return null; } } else if (retailPlatform === 'mediamart') { - if (segments.length !== 2) return null; + if ( + segments.length !== 2 || + !MEDIAMART_ALLOWED_CATEGORY_PREFIXES.has(firstSegLower) + ) { + return null; + } } else if ( retailPlatform === 'tgdd' || retailPlatform === 'dienmayxanh' || @@ -405,18 +590,52 @@ function extractValidRetailItemSlug( } } else if (retailPlatform === 'viettelstore') { if (segments.length > 2) return null; + if (segments.length === 2) { + if (VIETTELSTORE_NON_PRODUCT_PREFIXES.has(firstSegLower)) return null; + const leafLower = lastRaw.toLowerCase().replace(/\.html?$/i, ''); + const hasPid = /(?:^|-)pid[1-9]\d{1,14}$/i.test(leafLower); + if ( + !VIETTELSTORE_PRODUCT_CATEGORY_SEGMENTS.has(firstSegLower) && + !hasPid + ) { + return null; + } + } } else if (retailPlatform === 'anphatpc') { const hasHtmlExt = /\.html?$/i.test(lastRaw); const isDirectRoutePrefix = segments.length === 2 && (firstSegLower === 'products' || firstSegLower === 'san-pham'); if (!hasHtmlExt && !isDirectRoutePrefix) return null; - if (firstRawLower.startsWith('ajax') || firstRawLower.endsWith('.php')) { + if ( + firstRawLower.startsWith('ajax') || + firstRawLower.endsWith('.php') || + ANPHAT_EXTRA_NON_PRODUCT_FIRST_SEGMENTS.has(firstRawLower) || + ANPHAT_EXTRA_NON_PRODUCT_FIRST_SEGMENTS.has(firstSegLower) || + RETAIL_NON_PRODUCT_FIRST_SEGMENTS.has(firstSegLower) + ) { return null; } if (segments.some((s) => /_dm\d+$/i.test(s.replace(/\.html?$/i, '')))) { return null; } + if (segments.length > 1 && !isDirectRoutePrefix) { + const lastClean = lastRaw.replace(/\.html?$/i, ''); + if (!lastClean) return null; + const rawKey = [...segments.slice(0, -1), lastClean].join('/'); + const rawKeyLower = rawKey.toLowerCase(); + if ( + rawKey.length < 3 || + rawKey.length > 512 || + rawKeyLower.includes('..') || + ANPHAT_DESK_PHONE_SLUG_REGEX.test(rawKeyLower) || + RETAIL_AUTH_OR_NON_PRODUCT_SLUG_REGEX.test(rawKeyLower) || + ANPHAT_INFO_SUFFIX_REGEX.test(lastClean.toLowerCase()) + ) { + return null; + } + return sanitizeAnPhatItemId(rawKey) || null; + } } if ( @@ -428,10 +647,13 @@ function extractValidRetailItemSlug( const lastSeg = lastRaw.replace(/\.html?$/i, '') || null; const lastSegLower = (lastSeg || '').toLowerCase(); + const vtsHasPid = + retailPlatform === 'viettelstore' && + /(?:^|-)pid[1-9]\d{1,14}$/i.test(lastSegLower); if ( !lastSeg || lastSeg.length < 2 || - lastSeg.length > 120 || + lastSeg.length > 256 || !/^[a-z0-9][a-z0-9._-]*[a-z0-9]$/i.test(lastSegLower) || lastSegLower.includes('..') || /^(?:0+|null|undefined|nan|infinity|-infinity|true|false|default|index|home|trang-chu|404|page-not-found|error)$/i.test( @@ -442,13 +664,26 @@ function extractValidRetailItemSlug( RETAIL_BRAND_LISTING_SLUGS.has(lastSegLower) || RETAIL_AUTH_OR_NON_PRODUCT_SLUG_REGEX.test(lastSegLower) || isSeriesListingSlug(lastSegLower) || + (retailPlatform === 'hacom' && + HACOM_CATEGORY_BRAND_SLUG_REGEX.test(lastSegLower)) || + (retailPlatform === 'clickbuy' && + CLICKBUY_NON_PRODUCT_SLUG_REGEX.test(lastSegLower)) || + (retailPlatform === 'viettelstore' && + !vtsHasPid && + (VIETTELSTORE_NON_PRODUCT_PREFIXES.has(lastSegLower) || + VIETTELSTORE_CATEGORY_SLUG_REGEX.test(lastSegLower))) || (retailPlatform === 'anphatpc' && - ANPHAT_DESK_PHONE_SLUG_REGEX.test(lastSegLower)) + (ANPHAT_DESK_PHONE_SLUG_REGEX.test(lastSegLower) || + ANPHAT_INFO_SUFFIX_REGEX.test(lastSegLower))) ) { return null; } - return lastSeg; + if (retailPlatform === 'anphatpc' && lastSeg.length > 120) { + return sanitizeAnPhatItemId(lastSeg) || null; + } + + return lastSeg.length <= 120 ? lastSeg : null; } export function extractIdsFromUrl( @@ -1020,10 +1255,14 @@ export function extractRatingFromJsonLd(aggRaw: unknown): { export function cleanExtractedProductTitle(rawTitle: string): string { if (typeof rawTitle !== 'string') return ''; - const withoutPlatformSuffix = stripLoneSurrogates(rawTitle) - .replace(/\p{Cc}+/gu, ' ') + // Bound code points and collapse whitespace first so suffix matching stays strictly O(N). + const normalizedTitle = sliceCodePoints(stripLoneSurrogates(rawTitle), 2048) + .replace(/[\p{Cc}\s]+/gu, ' ') + .trim(); + if (!normalizedTitle) return ''; + const withoutPlatformSuffix = normalizedTitle .replace( - /\s*(?:\||[-\u2013\u2014])\s*(?:Shopee(?:\s*Việt\s*Nam|\s*VN)?|Lazada(?:\s*Việt\s*Nam|\s*VN)?|Tiki(?:\.vn)?|TikTok\s*Shop|CellphoneS(?:\.com\.vn)?|Thế\s*Giới\s*Di\s*Động|Thegioididong(?:\.com)?|TopZone(?:\.vn)?|Điện\s*Máy\s*Xanh|Dienmayxanh(?:\.com)?|FPT\s*Shop|Fptshop(?:\.com\.vn)?|Hoàng\s*Hà\s*Mobile|HoangHaMobile(?:\.com)?|Di\s*Động\s*Việt|Didongviet(?:\.vn)?|Phong\s*Vũ|Phongvu(?:\.vn)?|GearVN(?:\.com)?|Nguy\u1ec5n\s*Kim|Nguyenkim(?:\.com)?|ShopDunk(?:\.com)?|HACOM(?:\.vn)?|Hanoicomputer(?:\.vn)?|Clickbuy(?:\.com\.vn)?|Viettel\s*Store|Viettelstore(?:\.vn)?|Si\u00eau\s*th\u1ecb\s*\u0111i\u1ec7n\s*m\u00e1y\s*Pico|Pico(?:\.vn)?|Media\s*Mart|Mediamart(?:\.vn)?|MemoryZone(?:\.com\.vn)?|An\s*Ph\u00e1t(?:\s*Computer|\s*PC)?|Anphatpc(?:\.com\.vn)?).*$/i, + / ?(?:\||[-\u2013\u2014]) ?(?:Shopee(?:\s*Việt\s*Nam|\s*VN)?|Lazada(?:\s*Việt\s*Nam|\s*VN)?|Tiki(?:\.vn)?|TikTok\s*Shop|CellphoneS(?:\.com\.vn)?|Thế\s*Giới\s*Di\s*Động|Thegioididong(?:\.com)?|TopZone(?:\.vn)?|Điện\s*Máy\s*Xanh|Dienmayxanh(?:\.com)?|FPT\s*Shop|Fptshop(?:\.com\.vn)?|Hoàng\s*Hà\s*Mobile|HoangHaMobile(?:\.com)?|Di\s*Động\s*Việt|Didongviet(?:\.vn)?|Phong\s*Vũ|Phongvu(?:\.vn)?|GearVN(?:\.com)?|Nguy\u1ec5n\s*Kim|Nguyenkim(?:\.com)?|ShopDunk(?:\.com)?|HACOM(?:\.vn)?|Hanoicomputer(?:\.vn)?|Clickbuy(?:\.com\.vn)?|Viettel\s*Store|Viettelstore(?:\.vn)?|Si\u00eau\s*th\u1ecb\s*\u0111i\u1ec7n\s*m\u00e1y\s*Pico|Pico(?:\.vn)?|Media\s*Mart|Mediamart(?:\.vn)?|MemoryZone(?:\.com\.vn)?|An\s*Ph\u00e1t(?:\s*Computer|\s*PC)?|Anphatpc(?:\.com\.vn)?).*$/i, '' ) .replace(/\s+/g, ' ') @@ -1306,7 +1545,7 @@ export function extractProductSignalFromDom( '.product-detail-price .price-sale', '.cb-pbox__now:not([hidden])', '.wrap-price .new-price', - '.special-price .price', + '.special-price .price:not(.related-products *):not(.product-item *):not(.product-card *):not(.product-box *):not(header *):not(footer *)', '.tpt---sale-price', '.box-price-present', ]; @@ -1333,8 +1572,8 @@ export function extractProductSignalFromDom( '.product-detail-price .price-old', '.cb-pbox__old:not([hidden])', '.wrap-price .old-price', - '.product-price-regular', - '.old-price .price', + '.product-price-regular:not(.related-products *):not(.product-item *):not(.product-card *):not(.product-box *):not(header *):not(footer *)', + '.old-price .price:not(.related-products *):not(.product-item *):not(.product-card *):not(.product-box *):not(header *):not(footer *)', '.tpt---price-through', '.box-price-old', 'del', diff --git a/apps/extension/src/i18n.ts b/apps/extension/src/i18n.ts index 4bfa61eab..a80b79ac0 100644 --- a/apps/extension/src/i18n.ts +++ b/apps/extension/src/i18n.ts @@ -88,6 +88,7 @@ const VIETNAMESE_WORDS = new Set([ 'c\u00f3', 'b\u00e1n', 'n\u00f3ng', + 'ph\u00e1t', 'nhanh', 'nghe', ]); diff --git a/apps/extension/src/security-guards.ts b/apps/extension/src/security-guards.ts index e47a79402..85b5910a8 100644 --- a/apps/extension/src/security-guards.ts +++ b/apps/extension/src/security-guards.ts @@ -269,16 +269,17 @@ export function selectFreshestSessionSignal( return tabSignal ?? latestSignal ?? null; } -const SAFE_EXTERNAL_ID_REGEX = /^[a-zA-Z0-9_.-]{1,120}$/; +const SAFE_EXTERNAL_ID_CHARS_REGEX = /^[a-zA-Z0-9_.-]+$/; const RESERVED_EXTERNAL_ID_REGEX = /^(?:0+|null|undefined|nan|infinity|-infinity|true|false)$/i; -function sanitizeExternalIdentifier(val: unknown): string | null { +function sanitizeExternalIdentifier(val: unknown, maxLen = 120): string | null { if (typeof val !== 'string') return null; const cleaned = val.replace(/\p{Cc}+/gu, '').trim(); if ( !cleaned || - !SAFE_EXTERNAL_ID_REGEX.test(cleaned) || + cleaned.length > maxLen || + !SAFE_EXTERNAL_ID_CHARS_REGEX.test(cleaned) || !/[a-zA-Z0-9]/.test(cleaned) || cleaned.startsWith('.') || cleaned.endsWith('.') || @@ -397,7 +398,10 @@ export function sanitizeExtensionProductSignal( ...safeSignal, platform: validPlatform, canonicalUrl: sanitizeCanonicalSignalUrl(safeSignal.canonicalUrl), - externalItemId: sanitizeExternalIdentifier(safeSignal.externalItemId), + externalItemId: sanitizeExternalIdentifier( + safeSignal.externalItemId, + validPlatform === 'anphatpc' ? 128 : 120 + ), externalShopId: sanitizeExternalIdentifier(safeSignal.externalShopId), title: trimmedTitle, selectedVariant: trimmedVariant, diff --git a/apps/extension/src/sidepanel/sidepanel.ts b/apps/extension/src/sidepanel/sidepanel.ts index 4956e46b9..7b7c2315f 100644 --- a/apps/extension/src/sidepanel/sidepanel.ts +++ b/apps/extension/src/sidepanel/sidepanel.ts @@ -351,8 +351,8 @@ function renderPanelContent(
${escapeHtml(t('noProductTitle'))}

${tHtml('noProductBody', [ - `${escapeHtml(t('noProductStores'))}`, - `${escapeHtml(t('noProductLastStore'))}`, + `${contentTextHtml(t('noProductStores'))}`, + `${contentTextHtml(t('noProductLastStore'))}`, `${escapeHtml(t('quickLookupBoxName'))}`, ])}

diff --git a/apps/extension/src/test-extension-pipeline.ts b/apps/extension/src/test-extension-pipeline.ts index 4f8bac4e7..74352d385 100644 --- a/apps/extension/src/test-extension-pipeline.ts +++ b/apps/extension/src/test-extension-pipeline.ts @@ -838,16 +838,14 @@ async function runTests() { '2.1.0' ); assert.ok(sample); - for (const tgddSisterUrl of [ - 'https://topzone.vn/iphone/iphone-16-pro-max', - 'https://www.topzone.vn/iphone/iphone-16-pro-max', - 'https://dienmayxanh.com/dtdd/iphone-16-pro-max', - 'https://www.dienmayxanh.com/dtdd/iphone-16-pro-max', + for (const tgddUrl of [ + 'https://thegioididong.com/dtdd/iphone-16-pro-max', + 'https://www.thegioididong.com/dtdd/iphone-16-pro-max', ]) { const obs = buildExtensionObservationV1( { platform: 'tgdd', - canonicalUrl: tgddSisterUrl, + canonicalUrl: tgddUrl, externalItemId: 'iphone-16-pro-max', externalShopId: null, title: 'iPhone 16 Pro Max', @@ -860,10 +858,17 @@ async function runTests() { new Date(), '2.1.0' ); - assert.ok(obs, `tgdd observation must accept ${tgddSisterUrl}`); - assert.equal(obs.listing_url, tgddSisterUrl); + assert.ok(obs, `tgdd observation must accept ${tgddUrl}`); + assert.equal(obs.listing_url, tgddUrl); } - for (const lookalikeUrl of [ + // TopZone and Dien May Xanh are standalone Wave 1A platforms (#1850), and + // PostgreSQL `extension_observations_listing_url_check` allows only + // `thegioididong.com` under `marketplace = 'tgdd'`. + for (const disallowedForTgddUrl of [ + 'https://topzone.vn/iphone/iphone-16-pro-max', + 'https://www.topzone.vn/iphone/iphone-16-pro-max', + 'https://dienmayxanh.com/dtdd/iphone-16-pro-max', + 'https://www.dienmayxanh.com/dtdd/iphone-16-pro-max', 'https://eviltopzone.vn/iphone/iphone-16-pro-max', 'https://evildienmayxanh.com/dtdd/iphone-16-pro-max', ]) { @@ -871,7 +876,7 @@ async function runTests() { buildExtensionObservationV1( { platform: 'tgdd', - canonicalUrl: lookalikeUrl, + canonicalUrl: disallowedForTgddUrl, externalItemId: 'iphone-16-pro-max', externalShopId: null, title: 'iPhone 16 Pro Max', @@ -885,7 +890,7 @@ async function runTests() { '2.1.0' ), null, - `tgdd observation must reject lookalike ${lookalikeUrl}` + `tgdd observation must reject ${disallowedForTgddUrl}` ); } assert.deepEqual( @@ -12112,7 +12117,7 @@ async function runTests() { ] : [], querySelector: (sel: string) => - sel === '.product-price-regular' + sel.startsWith('.product-price-regular') ? { textContent: '34.990.000₫' } : null, } as unknown as Document; @@ -12468,6 +12473,104 @@ async function runTests() { console.log( ' ✅ [Wave 1-3 12 retail platforms across detector, lookup & SQL boundary (#1850)] Verified' ); + + // Round 1 review hardening (#1850): An Phat multi-segment Apple URLs + SHA-1 truncation, + // prefix-collision candidates, category/editorial guards, O(N) title cleaning & An Phát lang="vi" + const { createHash } = await import('node:crypto'); + const { sanitizeAnPhatItemId } = + await import('./extractors/ecommerce-detector.js'); + const { isVietnameseText } = await import('./i18n.js'); + + assert.deepEqual( + extractIdsFromUrl( + 'anphatpc', + 'https://www.anphatpc.com.vn/apple-ipad-11-inch-ipad-wi-fi-128gb-blue-md4a4za/a.html' + ), + { + externalItemId: + 'ap-apple-ipad-11-inch-ipad-wi-fi-128gb-blue-md4a4za_2fa', + externalShopId: null, + } + ); + const longAnPhatPath = + 'laptop-apple-macbook-air-mdhf4sa/a-mba-13.6-m5/10c/10gpu/16g/1t/35w/midnight-vietnam-edition-special-config-2026-ultra-extended-sku'; + const expectedNormalized = longAnPhatPath.replace(/[^a-z0-9-]/g, (ch) => { + const hex = ch.codePointAt(0)?.toString(16).padStart(2, '0') ?? '00'; + return `_${hex}`; + }); + const expectedSha1 = createHash('sha1') + .update(expectedNormalized) + .digest('hex') + .slice(0, 10); + const expectedTrimmed = expectedNormalized + .slice(0, 114) + .replace(/[-_]+$/g, ''); + const expectedLongApId = `ap-${expectedTrimmed}-${expectedSha1}`; + assert.equal(sanitizeAnPhatItemId(longAnPhatPath), expectedLongApId); + assert.equal( + extractIdsFromUrl( + 'anphatpc', + `https://www.anphatpc.com.vn/${longAnPhatPath}.html` + ).externalItemId, + expectedLongApId + ); + assert.ok(expectedLongApId.length <= 128); + + // Prefix-starting slugs & pre-prefixed unencoded IDs, plus non-leaking numeric underscore suffixes + const mzSelfPrefixed = buildCandidateExternalItemIds({ + platform: 'memoryzone', + externalId: 'mz-v9p1t0bw', + }); + assert.ok( + mzSelfPrefixed.includes('mz-mz-v9p1t0bw'), + 'raw slug starting with mz- must still produce mz-mz-...' + ); + const apPrePrefixed = buildCandidateExternalItemIds({ + platform: 'anphatpc', + externalId: 'ap-laptop_id49201', + }); + assert.ok( + apPrePrefixed.includes('ap-laptop_5fid49201') && + apPrePrefixed.includes('ap-ap-laptop_5fid49201') + ); + const nkNumericUnderscore = buildCandidateExternalItemIds({ + platform: 'nguyenkim', + externalId: 'laptop_274819201', + }); + assert.equal( + nkNumericUnderscore.includes('274819201'), + false, + 'retail underscore slugs must not leak bare numeric suffixes across platforms' + ); + + // Editorial / brand-category / used-hub rejections on MediaMart, HACOM, Clickbuy, Viettel Store + for (const [plat, nonPdp] of [ + ['mediamart', 'https://mediamart.vn/tu-van-tieu-dung/top-5-iphone-16'], + ['hacom', 'https://hacom.vn/laptop-asus'], + ['clickbuy', 'https://clickbuy.com.vn/dien-thoai-iphone'], + ['clickbuy', 'https://clickbuy.com.vn/iphone-cu'], + ['clickbuy', 'https://clickbuy.com.vn/thay-pin'], + ['viettelstore', 'https://viettelstore.vn/chuyen-muc-tin/iphone-16'], + ['viettelstore', 'https://viettelstore.vn/dtdd-apple-iphone'], + ] as const) { + assert.equal( + extractIdsFromUrl(plat, nonPdp).externalItemId, + null, + nonPdp + ); + } + + // O(N) title cleaning on pathological whitespace input & An Phát Vietnamese detection + const t0 = performance.now(); + const cleanedAdversarial = cleanExtractedProductTitle( + `iPhone 16 Pro${' '.repeat(20_000)}|NotAStore` + ); + assert.ok( + performance.now() - t0 < 50, + 'cleanExtractedProductTitle must run in O(N)' + ); + assert.ok(cleanedAdversarial.startsWith('iPhone 16 Pro')); + assert.equal(isVietnameseText('An Phát Computer'), true); } console.log('🎉 All Rate Browser Extension MV3 v2 tests passed!'); } diff --git a/apps/web/src/app/api/v1/rate/extension/ingest/route.ts b/apps/web/src/app/api/v1/rate/extension/ingest/route.ts index 66f56b6d2..e89a9befd 100644 --- a/apps/web/src/app/api/v1/rate/extension/ingest/route.ts +++ b/apps/web/src/app/api/v1/rate/extension/ingest/route.ts @@ -51,7 +51,7 @@ const CrowdIngestSchema = z.object({ 'anphatpc', ]) .optional(), - externalItemId: z.string().trim().min(1).max(120).optional(), + externalItemId: z.string().trim().min(1).max(128).optional(), externalShopId: z.string().trim().max(120).nullish(), url: z .string() diff --git a/apps/web/src/components/watchlist/WatchlistWorkspace.tsx b/apps/web/src/components/watchlist/WatchlistWorkspace.tsx index e7c4befc4..e9af1dd99 100644 --- a/apps/web/src/components/watchlist/WatchlistWorkspace.tsx +++ b/apps/web/src/components/watchlist/WatchlistWorkspace.tsx @@ -121,6 +121,16 @@ const PLATFORM_DISPLAY_LABELS: Record = { anphatpc: 'An Phát Computer', }; +const VIETNAMESE_NAMED_PLATFORMS = new Set([ + 'tgdd', + 'hoangha', + 'didongviet', + 'phongvu', + 'dienmayxanh', + 'nguyenkim', + 'anphatpc', +]); + export function sanitizeWatchlistBestOfferUrl(rawUrl: unknown): string | null { if (typeof rawUrl !== 'string') return null; const cleaned = rawUrl.replace(/\p{Cc}+/gu, '').trim(); @@ -1501,10 +1511,20 @@ export default function WatchlistWorkspace({ diff --git a/apps/web/src/lib/rate-api.ts b/apps/web/src/lib/rate-api.ts index 1d8a473dc..b772084dc 100644 --- a/apps/web/src/lib/rate-api.ts +++ b/apps/web/src/lib/rate-api.ts @@ -39,6 +39,7 @@ import { sanitizePostgrestFilterToken, type ParsedEcommerceUrl, parseEcommerceUrlOrQuery, + sanitizeAnPhatItemId, extractProductKeywordFromUrl, firstImageUrl, resolveCompareEffectiveUserRating, @@ -69,6 +70,7 @@ export { filterAndSortMerchants, sanitizePostgrestFilterToken, parseEcommerceUrlOrQuery, + sanitizeAnPhatItemId, stripEcommerceNoiseTokens, extractProductKeywordFromUrl, } from './rate-domain-core'; @@ -4526,13 +4528,6 @@ const WAVE_UNDERSCORE_ENCODED_PLATFORMS = new Set< 'memoryzone', ]); -function encodeAnPhatSlugForItemId(value: string): string { - return value.toLowerCase().replace(/[^a-z0-9-]/g, (ch) => { - const hex = ch.codePointAt(0)?.toString(16).padStart(2, '0') ?? '00'; - return `_${hex}`; - }); -} - function lookupOfferDiscountAnalysis( byOffer: Record | null | undefined, rawId: unknown @@ -4592,7 +4587,7 @@ export function selectOfferForUrlInspection( } /** - * Inspect an e-commerce product/shop URL (all 10 platforms) or keyword: + * Inspect an e-commerce product/shop URL (all 22 platforms) or keyword: * - Resolves exact `platform_item_id` or `url` against `rate.products` * - Or resolves `platform_shop_id` / merchant name against `rate.merchants` * - Or resolves product slug / keyword against `rate.master_products` @@ -4634,38 +4629,53 @@ export async function inspectProductOrShopUrl( // 1. Direct lookup by platform_item_id if parsed from URL if (parsedUrl.platformItemId) { - const candidateIds = new Set([parsedUrl.platformItemId]); + const rawItemId = parsedUrl.platformItemId; + const lowerItemId = rawItemId.toLowerCase(); + const candidateIds = new Set([rawItemId, lowerItemId]); if (parsedUrl.platformShopId) { - candidateIds.add( - `${parsedUrl.platformShopId}_${parsedUrl.platformItemId}` - ); + candidateIds.add(`${parsedUrl.platformShopId}_${rawItemId}`); } const prefix = parsedUrl.platform ? PLATFORM_ITEM_ID_PREFIX[parsedUrl.platform] : undefined; - if (prefix && !parsedUrl.platformItemId.startsWith(prefix)) { - candidateIds.add(`${prefix}${parsedUrl.platformItemId}`); - const lowerId = parsedUrl.platformItemId.toLowerCase(); - candidateIds.add(`${prefix}${lowerId}`); - if ( - parsedUrl.platform && - WAVE_UNDERSCORE_ENCODED_PLATFORMS.has(parsedUrl.platform) && - lowerId.includes('_') - ) { - const waveEncoded = `${prefix}${lowerId.replace(/_/g, '_5f')}`; - if (waveEncoded.length <= 128) candidateIds.add(waveEncoded); + if (prefix) { + const rawSlugs = [rawItemId]; + if (lowerItemId.startsWith(prefix) && rawItemId.length > prefix.length) { + rawSlugs.push(rawItemId.slice(prefix.length)); } - if (parsedUrl.platform === 'anphatpc') { - const apEncoded = `${prefix}${encodeAnPhatSlugForItemId(parsedUrl.platformItemId)}`; - if (apEncoded.length <= 128) candidateIds.add(apEncoded); + for (const slugCandidate of rawSlugs) { + const lowerSlug = slugCandidate.toLowerCase(); + if (`${prefix}${slugCandidate}`.length <= 128) { + candidateIds.add(`${prefix}${slugCandidate}`); + } + if (`${prefix}${lowerSlug}`.length <= 128) { + candidateIds.add(`${prefix}${lowerSlug}`); + } + if ( + parsedUrl.platform && + WAVE_UNDERSCORE_ENCODED_PLATFORMS.has(parsedUrl.platform) && + lowerSlug.includes('_') + ) { + const waveEncoded = `${prefix}${lowerSlug.replace(/_/g, '_5f')}`; + if (waveEncoded.length <= 128) candidateIds.add(waveEncoded); + } + if (parsedUrl.platform === 'anphatpc') { + const apEncoded = sanitizeAnPhatItemId(slugCandidate); + if (apEncoded && apEncoded.length <= 128) { + candidateIds.add(apEncoded); + } + } } } if ( - (parsedUrl.platform === 'topzone' || - parsedUrl.platform === 'dienmayxanh') && - !parsedUrl.platformItemId.startsWith('tgdd-') + parsedUrl.platform === 'topzone' || + parsedUrl.platform === 'dienmayxanh' ) { - candidateIds.add(`tgdd-${parsedUrl.platformItemId}`); + const bareMwg = rawItemId.replace(/^(?:tz|dmx|tgdd)-/i, ''); + if (bareMwg) { + candidateIds.add(`tgdd-${bareMwg}`); + candidateIds.add(`tgdd-${bareMwg.toLowerCase()}`); + } } const { data: prodRow, error: prodErr } = await supabase diff --git a/apps/web/src/lib/rate-domain-core.ts b/apps/web/src/lib/rate-domain-core.ts index b1a20d27d..990f24e43 100644 --- a/apps/web/src/lib/rate-domain-core.ts +++ b/apps/web/src/lib/rate-domain-core.ts @@ -1848,6 +1848,190 @@ const RETAIL_CATEGORY_ROOT_SLUGS = new Set([ 'airpods', ]); +const MEDIAMART_ALLOWED_CATEGORY_PREFIXES = new Set([ + 'smartphones', + 'dien-thoai', + 'dien-thoai-di-dong', + 'laptop', + 'may-tinh-xach-tay', + 'macbook', + 'may-tinh-bang', + 'tablet', + 'ipad', + 'smartwatch', + 'dong-ho-thong-minh', + 'tai-nghe', + 'san-pham', + 'products', +]); + +const HACOM_CATEGORY_BRAND_SLUG_REGEX = + /^(?:laptop-(?:asus|dell|acer|lenovo|hp|msi|apple|lg|gigabyte)|may-tinh-nguyen-bo-theo-hang|may-tinh-mini-da-dung)$/i; + +const CLICKBUY_NON_PRODUCT_SLUG_REGEX = + /^(?:dien-thoai-(?:iphone|samsung|xiaomi|oppo|vivo|realme|nokia|honor|asus|tcl|google|sony|tecno|infinix|masstel|itel)|(?:iphone|samsung|dien-thoai|ipad|macbook|apple-watch)-cu|thay-pin|ep-kinh|google-pixel|trang)$/i; + +const VIETTELSTORE_PRODUCT_CATEGORY_SEGMENTS = new Set([ + 'dien-thoai', + 'may-tinh-bang', + 'tablet', + 'laptop', + 'may-tinh-xach-tay', + 'dong-ho-thong-minh', + 'dong-ho', + 'apple-watch', + 'smartwatch', + 'tai-nghe', + 'am-thanh', + 'loa', + 'phu-kien', + 'man-hinh', + 'pc', + 'tivi', + 'san-pham', + 'products', +]); + +const VIETTELSTORE_NON_PRODUCT_PREFIXES = new Set([ + 'tra-gop', + 'so-sanh', + 'so-sanh-san-pham', + 'tin-tuc', + 'chuyen-muc-tin', + 'landing', + 'khuyen-mai', + 'site', + 'he-thong-sieu-thi', + 'sieu-thi', + 'ho-tro', + 'tuyen-dung', + 'account', + 'login', + 'dang-nhap', + 'register', + 'dang-ky', + 'auth', + 'captcha', + 'challenge', + 'cart', + 'gio-hang', + 'dtdd', + 'mtb', + 'tim-kiem', + 'ket-qua-tim-kiem', +]); + +const VIETTELSTORE_CATEGORY_SLUG_REGEX = + /^(?:dtdd(?:-|$)|mtb(?:-|$)|laptop-(?:apple|asus|acer|dell|hp|lenovo|msi|lg)$|phu-kien-o-to$|bao-da-op-lung$|tam-dan$)/i; + +const ANPHAT_EXTRA_NON_PRODUCT_FIRST_SEGMENTS = new Set([ + 'template', + 'templates', + 'includes', + 'user', + 'order', + 'don-hang', + 'rss', + 'sitemap', + 'robots.txt', +]); + +const ANPHAT_INFO_SUFFIX_REGEX = + /(?:^|-)(?:he-thong-showroom|tin-khuyen-mai|tin-tuc|khuyen-mai|bao-hanh|chinh-sach|huong-dan|lien-he|tuyen-dung|gioi-thieu|pc-an-phat)$/i; + +function sha1Hex10(input: string): string { + const bytes = new TextEncoder().encode(input); + const bitLen = bytes.length * 8; + const paddedLen = (((bytes.length + 8) >>> 6) + 1) << 6; + const buf = new Uint8Array(paddedLen); + buf.set(bytes); + buf[bytes.length] = 0x80; + const view = new DataView(buf.buffer); + view.setUint32(paddedLen - 8, Math.floor(bitLen / 0x100000000), false); + view.setUint32(paddedLen - 4, bitLen >>> 0, false); + + let h0 = 0x67452301; + let h1 = 0xefcdab89; + let h2 = 0x98badcfe; + let h3 = 0x10325476; + let h4 = 0xc3d2e1f0; + const w = new Uint32Array(80); + + for (let offset = 0; offset < paddedLen; offset += 64) { + for (let i = 0; i < 16; i++) { + w[i] = view.getUint32(offset + i * 4, false); + } + for (let i = 16; i < 80; i++) { + const n = w[i - 3]! ^ w[i - 8]! ^ w[i - 14]! ^ w[i - 16]!; + w[i] = ((n << 1) | (n >>> 31)) >>> 0; + } + + let a = h0; + let b = h1; + let c = h2; + let d = h3; + let e = h4; + + for (let i = 0; i < 80; i++) { + let f: number; + let k: number; + if (i < 20) { + f = (b & c) | (~b & d); + k = 0x5a827999; + } else if (i < 40) { + f = b ^ c ^ d; + k = 0x6ed9eba1; + } else if (i < 60) { + f = (b & c) | (b & d) | (c & d); + k = 0x8f1bbcdc; + } else { + f = b ^ c ^ d; + k = 0xca62c1d6; + } + const temp = + ((((a << 5) | (a >>> 27)) >>> 0) + (f >>> 0) + e + k + w[i]!) >>> 0; + e = d; + d = c; + c = ((b << 30) | (b >>> 2)) >>> 0; + b = a; + a = temp; + } + + h0 = (h0 + a) >>> 0; + h1 = (h1 + b) >>> 0; + h2 = (h2 + c) >>> 0; + h3 = (h3 + d) >>> 0; + h4 = (h4 + e) >>> 0; + } + + return ( + h0.toString(16).padStart(8, '0') + h1.toString(16).padStart(8, '0') + ).slice(0, 10); +} + +/** + * Encodes an An Phat Computer URL slug/path into canonical `ap-` format + * (`<= 128` chars, matching `AnPhatScraper.sanitizeAnPhatItemId` in `DOS/Rate-Services`). + */ +export function sanitizeAnPhatItemId(rawKey: string): string { + const cleaned = rawKey.trim().replace(/^\/+|\/+$/g, ''); + if (!cleaned) return ''; + const normalized = cleaned.toLowerCase().replace(/[^a-z0-9-]/g, (ch) => { + const hex = ch.codePointAt(0)?.toString(16).padStart(2, '0') ?? '00'; + return `_${hex}`; + }); + if (!normalized) return ''; + const maxSlugLen = 125; + if (normalized.length <= maxSlugLen) { + return `ap-${normalized}`; + } + const digest = sha1Hex10(normalized); + const keepLen = Math.max(1, maxSlugLen - digest.length - 1); + let trimmed = normalized.slice(0, keepLen).replace(/[-_]+$/g, ''); + if (!trimmed) trimmed = normalized.slice(0, keepLen); + return `ap-${trimmed}-${digest}`; +} + function extractValidRetailItemSlug( retailPlatform: NonNullable, segments: readonly string[] @@ -1900,7 +2084,12 @@ function extractValidRetailItemSlug( return null; } } else if (retailPlatform === 'mediamart') { - if (segments.length !== 2) return null; + if ( + segments.length !== 2 || + !MEDIAMART_ALLOWED_CATEGORY_PREFIXES.has(firstSegLower) + ) { + return null; + } } else if ( retailPlatform === 'tgdd' || retailPlatform === 'dienmayxanh' || @@ -1928,18 +2117,52 @@ function extractValidRetailItemSlug( } } else if (retailPlatform === 'viettelstore') { if (segments.length > 2) return null; + if (segments.length === 2) { + if (VIETTELSTORE_NON_PRODUCT_PREFIXES.has(firstSegLower)) return null; + const leafLower = lastRaw.toLowerCase().replace(/\.html?$/i, ''); + const hasPid = /(?:^|-)pid[1-9]\d{1,14}$/i.test(leafLower); + if ( + !VIETTELSTORE_PRODUCT_CATEGORY_SEGMENTS.has(firstSegLower) && + !hasPid + ) { + return null; + } + } } else if (retailPlatform === 'anphatpc') { const hasHtmlExt = /\.html?$/i.test(lastRaw); const isDirectRoutePrefix = segments.length === 2 && (firstSegLower === 'products' || firstSegLower === 'san-pham'); if (!hasHtmlExt && !isDirectRoutePrefix) return null; - if (firstRawLower.startsWith('ajax') || firstRawLower.endsWith('.php')) { + if ( + firstRawLower.startsWith('ajax') || + firstRawLower.endsWith('.php') || + ANPHAT_EXTRA_NON_PRODUCT_FIRST_SEGMENTS.has(firstRawLower) || + ANPHAT_EXTRA_NON_PRODUCT_FIRST_SEGMENTS.has(firstSegLower) || + RETAIL_NON_PRODUCT_FIRST_SEGMENTS.has(firstSegLower) + ) { return null; } if (segments.some((s) => /_dm\d+$/i.test(s.replace(/\.html?$/i, '')))) { return null; } + if (segments.length > 1 && !isDirectRoutePrefix) { + const lastClean = lastRaw.replace(/\.html?$/i, ''); + if (!lastClean) return null; + const rawKey = [...segments.slice(0, -1), lastClean].join('/'); + const rawKeyLower = rawKey.toLowerCase(); + if ( + rawKey.length < 3 || + rawKey.length > 512 || + rawKeyLower.includes('..') || + ANPHAT_DESK_PHONE_SLUG_REGEX.test(rawKeyLower) || + RETAIL_AUTH_OR_NON_PRODUCT_SLUG_REGEX.test(rawKeyLower) || + ANPHAT_INFO_SUFFIX_REGEX.test(lastClean.toLowerCase()) + ) { + return null; + } + return sanitizeAnPhatItemId(rawKey) || null; + } } if ( @@ -1951,6 +2174,9 @@ function extractValidRetailItemSlug( const lastSeg = lastRaw.replace(/\.html?$/i, '') || null; const lastSegLower = (lastSeg || '').toLowerCase(); + const vtsHasPid = + retailPlatform === 'viettelstore' && + /(?:^|-)pid[1-9]\d{1,14}$/i.test(lastSegLower); if ( !lastSeg || lastSeg.length < 2 || @@ -1965,12 +2191,25 @@ function extractValidRetailItemSlug( RETAIL_BRAND_LISTING_SLUGS.has(lastSegLower) || RETAIL_AUTH_OR_NON_PRODUCT_SLUG_REGEX.test(lastSegLower) || isSeriesListingSlug(lastSegLower) || + (retailPlatform === 'hacom' && + HACOM_CATEGORY_BRAND_SLUG_REGEX.test(lastSegLower)) || + (retailPlatform === 'clickbuy' && + CLICKBUY_NON_PRODUCT_SLUG_REGEX.test(lastSegLower)) || + (retailPlatform === 'viettelstore' && + !vtsHasPid && + (VIETTELSTORE_NON_PRODUCT_PREFIXES.has(lastSegLower) || + VIETTELSTORE_CATEGORY_SLUG_REGEX.test(lastSegLower))) || (retailPlatform === 'anphatpc' && - ANPHAT_DESK_PHONE_SLUG_REGEX.test(lastSegLower)) + (ANPHAT_DESK_PHONE_SLUG_REGEX.test(lastSegLower) || + ANPHAT_INFO_SUFFIX_REGEX.test(lastSegLower))) ) { return null; } + if (retailPlatform === 'anphatpc' && lastSeg.length > 120) { + return sanitizeAnPhatItemId(lastSeg) || null; + } + return lastSeg; } @@ -2357,6 +2596,7 @@ export function extractProductKeywordFromUrl(rawUrl?: string | null): string { decodedPathname = parsed.pathname; } + const parsedHostLower = parsed.hostname.toLowerCase(); const rawSegments = decodedPathname .split('/') .map((s) => s.trim()) @@ -2373,7 +2613,16 @@ export function extractProductKeywordFromUrl(rawUrl?: string | null): string { RETAIL_NON_PRODUCT_FIRST_SEGMENTS.has(firstSegLower)) || firstSegLower === 'shop' || firstSegLower === 'opaanlp' || - firstSegLower === 'video' + firstSegLower === 'video' || + (isDomainOrSubdomain(parsedHostLower, 'mediamart.vn') && + (rawSegments.length !== 2 || + !MEDIAMART_ALLOWED_CATEGORY_PREFIXES.has(firstSegLower))) || + (isDomainOrSubdomain(parsedHostLower, 'viettelstore.vn') && + rawSegments.length === 2 && + VIETTELSTORE_NON_PRODUCT_PREFIXES.has(firstSegLower)) || + (isDomainOrSubdomain(parsedHostLower, 'anphatpc.com.vn') && + (ANPHAT_EXTRA_NON_PRODUCT_FIRST_SEGMENTS.has(firstSegLower) || + rawSegments.some((s) => /_dm\d+(?:\.html?)?$/i.test(s)))) ) { return ''; } @@ -2386,7 +2635,20 @@ export function extractProductKeywordFromUrl(rawUrl?: string | null): string { return ''; } - const cleanedPath = decodedPathname + // Multi-segment An Phat Computer URLs embed `/` inside Apple part numbers + // (e.g. `/apple-ipad-11-inch-ipad-wi-fi-128gb-blue-md4a4za/a.html`); + // flatten the full path before extracting keywords so the trailing `/a` + // is never treated as a 1-character product slug. + const effectivePath = + isDomainOrSubdomain(parsedHostLower, 'anphatpc.com.vn') && + rawSegments.length > 1 && + firstSegLower !== 'products' && + firstSegLower !== 'san-pham' && + /\.html?$/i.test(rawLeaf) + ? `/${rawSegments.join('-').replace(/\.html?$/i, '')}` + : decodedPathname; + + const cleanedPath = effectivePath .replace(/(?:\/a-i|-i|\/i)\.\d+\.\d+\/?$/i, '') .replace(/\/(?:product|opaanlp)\/\d+\/\d+\/?$/i, '') .replace(/\/(?:view\/)?product\/\d+\/?$/i, '') @@ -2406,12 +2668,16 @@ export function extractProductKeywordFromUrl(rawUrl?: string | null): string { const lastSegLower = lastSeg.toLowerCase(); if ( !lastSeg || + lastSeg.length < 2 || /^\d+$/.test(lastSeg) || /^(?:a-)?i\.\d+\.\d+$/i.test(lastSeg) || lastSeg.startsWith('@') || RETAIL_CATEGORY_ROOT_SLUGS.has(lastSegLower) || RETAIL_NON_PRODUCT_FIRST_SEGMENTS.has(lastSegLower) || RETAIL_AUTH_OR_NON_PRODUCT_SLUG_REGEX.test(lastSegLower) || + HACOM_CATEGORY_BRAND_SLUG_REGEX.test(lastSegLower) || + CLICKBUY_NON_PRODUCT_SLUG_REGEX.test(lastSegLower) || + ANPHAT_DESK_PHONE_SLUG_REGEX.test(lastSegLower) || /^(?:search|tim-kiem|result|product|products|view)$/.test(lastSegLower) ) { return ''; diff --git a/apps/web/src/server/rate/__tests__/core-rate-architecture.test.ts b/apps/web/src/server/rate/__tests__/core-rate-architecture.test.ts index 8d11ebba0..19be261eb 100644 --- a/apps/web/src/server/rate/__tests__/core-rate-architecture.test.ts +++ b/apps/web/src/server/rate/__tests__/core-rate-architecture.test.ts @@ -15200,6 +15200,38 @@ async function runCoreArchitectureSuite() { platform: 'dienmayxanh', }).includes('tgdd-iphone-16-pro-max') ); + assert.equal( + parseEcommerceUrlOrQuery( + 'https://www.anphatpc.com.vn/apple-ipad-11-inch-ipad-wi-fi-128gb-blue-md4a4za/a.html' + ).platformItemId, + 'ap-apple-ipad-11-inch-ipad-wi-fi-128gb-blue-md4a4za_2fa' + ); + assert.ok( + extractProductKeywordFromUrl( + 'https://www.anphatpc.com.vn/apple-ipad-11-inch-ipad-wi-fi-128gb-blue-md4a4za/a.html' + ).includes('ipad') + ); + assert.equal( + parseEcommerceUrlOrQuery( + 'https://mediamart.vn/tu-van-tieu-dung/top-5-iphone-16' + ).platformItemId, + null + ); + assert.equal( + parseEcommerceUrlOrQuery('https://hacom.vn/laptop-asus').platformItemId, + null + ); + assert.equal( + parseEcommerceUrlOrQuery('https://clickbuy.com.vn/dien-thoai-iphone') + .platformItemId, + null + ); + assert.equal( + parseEcommerceUrlOrQuery( + 'https://viettelstore.vn/chuyen-muc-tin/iphone-16' + ).platformItemId, + null + ); console.log( ' ✅ DOS/Rate#1850 Wave 1-3 12 retail platforms web & API parity passed' ); diff --git a/apps/web/src/server/rate/extension.ts b/apps/web/src/server/rate/extension.ts index e116835c6..9a98ad634 100644 --- a/apps/web/src/server/rate/extension.ts +++ b/apps/web/src/server/rate/extension.ts @@ -26,6 +26,7 @@ import { normalizeMasterProductRow, parseEcommerceUrlOrQuery, RateDataUnavailableError, + sanitizeAnPhatItemId, stripEcommerceNoiseTokens, type CanonicalCategorySlug, type MasterProduct, @@ -1252,16 +1253,6 @@ export function buildCandidateExternalItemIds(params: { return []; } - candidateItemIds.add(cleanExternalId); - if (cleanExternalId.includes('_')) { - const parts = cleanExternalId.split('_'); - if (parts[1] && isValidExternalEntityId(parts[1])) { - candidateItemIds.add(parts[1]); - } - } - if (cleanShopId && !cleanExternalId.includes('_')) { - candidateItemIds.add(`${cleanShopId}_${cleanExternalId}`); - } const prefixMap: Partial> = { tiktok: 'tts-', cellphones: 'cps-', @@ -1294,45 +1285,68 @@ export function buildCandidateExternalItemIds(params: { 'memoryzone', ]); const prefix = params.platform ? prefixMap[params.platform] : undefined; - if (prefix && !cleanExternalId.startsWith(prefix)) { - const prefixed = `${prefix}${cleanExternalId}`; - if (isValidExternalEntityId(prefixed)) { - candidateItemIds.add(prefixed); - } - const lowerPrefixed = `${prefix}${cleanExternalId.toLowerCase()}`; - if (isValidExternalEntityId(lowerPrefixed)) { - candidateItemIds.add(lowerPrefixed); + + candidateItemIds.add(cleanExternalId); + const lowerCleanExternalId = cleanExternalId.toLowerCase(); + if (isValidExternalEntityId(lowerCleanExternalId)) { + candidateItemIds.add(lowerCleanExternalId); + } + // `shopId_itemId` underscore splitting applies only to non-prefixed marketplaces + // (`shopee`, `lazada`, `tiki`); retail slugs with `_` must not split into numeric suffixes. + if (!prefix && cleanExternalId.includes('_')) { + const parts = cleanExternalId.split('_'); + if (parts[1] && isValidExternalEntityId(parts[1])) { + candidateItemIds.add(parts[1]); } + } + if (!prefix && cleanShopId && !cleanExternalId.includes('_')) { + candidateItemIds.add(`${cleanShopId}_${cleanExternalId}`); + } + if (prefix) { + const rawSlugs = [cleanExternalId]; if ( - params.platform && - waveUnderscorePlatforms.has(params.platform) && - cleanExternalId.includes('_') + lowerCleanExternalId.startsWith(prefix) && + cleanExternalId.length > prefix.length ) { - const waveEncoded = `${prefix}${cleanExternalId.toLowerCase().replace(/_/g, '_5f')}`; - if (isValidExternalEntityId(waveEncoded)) { - candidateItemIds.add(waveEncoded); - } + rawSlugs.push(cleanExternalId.slice(prefix.length)); } - if (params.platform === 'anphatpc') { - const apEncodedSlug = cleanExternalId - .toLowerCase() - .replace(/[^a-z0-9-]/g, (ch) => { - const hex = ch.codePointAt(0)?.toString(16).padStart(2, '0') ?? '00'; - return `_${hex}`; - }); - const apCandidate = `${prefix}${apEncodedSlug}`; - if (isValidExternalEntityId(apCandidate)) { - candidateItemIds.add(apCandidate); + for (const slugCandidate of rawSlugs) { + const lowerSlug = slugCandidate.toLowerCase(); + const prefixed = `${prefix}${slugCandidate}`; + if (isValidExternalEntityId(prefixed)) { + candidateItemIds.add(prefixed); + } + const lowerPrefixed = `${prefix}${lowerSlug}`; + if (isValidExternalEntityId(lowerPrefixed)) { + candidateItemIds.add(lowerPrefixed); + } + if ( + params.platform && + waveUnderscorePlatforms.has(params.platform) && + lowerSlug.includes('_') + ) { + const waveEncoded = `${prefix}${lowerSlug.replace(/_/g, '_5f')}`; + if (isValidExternalEntityId(waveEncoded)) { + candidateItemIds.add(waveEncoded); + } + } + if (params.platform === 'anphatpc') { + const apCandidate = sanitizeAnPhatItemId(slugCandidate); + if (apCandidate && isValidExternalEntityId(apCandidate)) { + candidateItemIds.add(apCandidate); + } } } } - if ( - (params.platform === 'topzone' || params.platform === 'dienmayxanh') && - !cleanExternalId.startsWith('tgdd-') - ) { - const legacyTgdd = `tgdd-${cleanExternalId}`; - if (isValidExternalEntityId(legacyTgdd)) { - candidateItemIds.add(legacyTgdd); + if (params.platform === 'topzone' || params.platform === 'dienmayxanh') { + const bareMwg = cleanExternalId.replace(/^(?:tz|dmx|tgdd)-/i, ''); + for (const mwgCandidate of [ + `tgdd-${bareMwg}`, + `tgdd-${bareMwg.toLowerCase()}`, + ]) { + if (bareMwg && isValidExternalEntityId(mwgCandidate)) { + candidateItemIds.add(mwgCandidate); + } } } return Array.from(candidateItemIds); diff --git a/apps/web/src/server/rate/openapi.ts b/apps/web/src/server/rate/openapi.ts index 12393551a..77eb7ae46 100644 --- a/apps/web/src/server/rate/openapi.ts +++ b/apps/web/src/server/rate/openapi.ts @@ -303,7 +303,7 @@ function buildBaseRateOpenApiSpec( summary: 'Standardized 10-Group Tech Specs, Price History, Product Deal Radar & AI Review Auditing API', description: - 'OpenAPI 3.1 specification for the Rate.vn REST API v1. The website, the Rate browser extension (10 Vietnamese marketplaces and retailers) and open e-commerce research all use these endpoints.', + 'OpenAPI 3.1 specification for the Rate.vn REST API v1. The website, the Rate browser extension (22 Vietnamese marketplaces and retailers) and open e-commerce research all use these endpoints.', license: { name: 'MIT Open-Core License', url: 'https://github.com/DOS/Rate', @@ -333,7 +333,7 @@ function buildBaseRateOpenApiSpec( { name: 'URL Inspector & Extension MV3', description: - 'Real-time URL/SKU canonicalization, 10-platform hybrid lookup, evidence-based price verdict, and zero-trust quarantine ingestion.', + 'Real-time URL/SKU canonicalization, 22-platform hybrid lookup, evidence-based price verdict, and zero-trust quarantine ingestion.', }, { name: 'Merchants & Dual Risk Score', @@ -1948,7 +1948,7 @@ function buildBaseRateOpenApiSpec( get: { operationId: 'getCrossPlatformDealRadar', summary: - 'Cross-Platform Deal Radar & Fake-Sale Trap Feed across 10 platforms', + 'Cross-Platform Deal Radar & Fake-Sale Trap Feed across 22 platforms', description: 'Returns real-time genuine cross-platform deals (`genuineDeals`, current offers below the cross-retailer median) and inflated fake-sale traps (`fakeSaleTraps`) audited against cross-retailer median prices. A genuine deal has `verdict` `genuine_all_time_low` (the multi-platform price floor) only when the product has 3 or more offers and the deal is the cheapest offer at least 2% below the median; otherwise it is `best_market_deal`, since the median of 2 offers is just their midpoint.', tags: ['Products & Specs'], @@ -1987,7 +1987,7 @@ function buildBaseRateOpenApiSpec( responses: { '200': { description: - 'Genuine deal radar and fake-sale trap list across 10 retailers.', + 'Genuine deal radar and fake-sale trap list across 22 retailers.', }, }, }, diff --git a/packages/shared-data/src/__tests__/shared-data.test.ts b/packages/shared-data/src/__tests__/shared-data.test.ts index 25a7730d3..d16d71393 100644 --- a/packages/shared-data/src/__tests__/shared-data.test.ts +++ b/packages/shared-data/src/__tests__/shared-data.test.ts @@ -2942,10 +2942,6 @@ function testExtensionObservation(): void { for (const tgddUrl of [ 'https://thegioididong.com/dtdd/iphone-16-pro-max', 'https://www.thegioididong.com/dtdd/iphone-16-pro-max', - 'https://topzone.vn/iphone/iphone-16-pro-max', - 'https://www.topzone.vn/iphone/iphone-16-pro-max', - 'https://dienmayxanh.com/dtdd/iphone-16-pro-max', - 'https://www.dienmayxanh.com/dtdd/iphone-16-pro-max', ]) { assert.ok( parse({ @@ -2956,14 +2952,28 @@ function testExtensionObservation(): void { tgddUrl ); } + for (const separatedSisterUrl of [ + 'https://topzone.vn/iphone/iphone-16-pro-max', + 'https://www.topzone.vn/iphone/iphone-16-pro-max', + 'https://dienmayxanh.com/dtdd/iphone-16-pro-max', + 'https://www.dienmayxanh.com/dtdd/iphone-16-pro-max', + ]) { + const res = parse({ + ...valid, + marketplace: 'tgdd', + listing_url: separatedSisterUrl, + }); + assert.equal(res.ok, false, separatedSisterUrl); + if (!res.ok) assert.equal(res.field, 'listing_url'); + } // Every marketplace accepts its own hosts and refuses another's. assert.ok(rules.isExtensionMarketplaceHost('lazada', 'www.lazada.vn')); assert.ok(rules.isExtensionMarketplaceHost('tgdd', 'thegioididong.com')); assert.ok(rules.isExtensionMarketplaceHost('tgdd', 'www.thegioididong.com')); - assert.ok(rules.isExtensionMarketplaceHost('tgdd', 'topzone.vn')); - assert.ok(rules.isExtensionMarketplaceHost('tgdd', 'www.topzone.vn')); - assert.ok(rules.isExtensionMarketplaceHost('tgdd', 'dienmayxanh.com')); - assert.ok(rules.isExtensionMarketplaceHost('tgdd', 'www.dienmayxanh.com')); + assert.ok(!rules.isExtensionMarketplaceHost('tgdd', 'topzone.vn')); + assert.ok(!rules.isExtensionMarketplaceHost('tgdd', 'www.topzone.vn')); + assert.ok(!rules.isExtensionMarketplaceHost('tgdd', 'dienmayxanh.com')); + assert.ok(!rules.isExtensionMarketplaceHost('tgdd', 'www.dienmayxanh.com')); assert.ok(rules.isExtensionMarketplaceHost('tiktok', 'shop.tiktok.com')); assert.ok(!rules.isExtensionMarketplaceHost('tiktok', 'm.tiktok.com')); assert.ok(!rules.isExtensionMarketplaceHost('lazada', 'notlazada.vn')); diff --git a/packages/shared-data/src/rules/extension-observation.ts b/packages/shared-data/src/rules/extension-observation.ts index e11546847..70acf8741 100644 --- a/packages/shared-data/src/rules/extension-observation.ts +++ b/packages/shared-data/src/rules/extension-observation.ts @@ -54,14 +54,7 @@ const EXTENSION_MARKETPLACE_HOSTS: Readonly< tiki: ['tiki.vn'], tiktok: ['www.tiktok.com', 'shop.tiktok.com'], cellphones: ['cellphones.com.vn'], - tgdd: [ - 'thegioididong.com', - '.thegioididong.com', - 'topzone.vn', - '.topzone.vn', - 'dienmayxanh.com', - '.dienmayxanh.com', - ], + tgdd: ['thegioididong.com', '.thegioididong.com'], fptshop: ['fptshop.com.vn'], hoangha: ['hoanghamobile.com'], didongviet: ['didongviet.vn'], diff --git a/scripts/test-extension-observations-proposal.mjs b/scripts/test-extension-observations-proposal.mjs index 387129fe7..bbe3ac65e 100644 --- a/scripts/test-extension-observations-proposal.mjs +++ b/scripts/test-extension-observations-proposal.mjs @@ -463,6 +463,20 @@ try { 'listing_url', good({ marketplace: 'tiktok', listing_url: 'https://m.tiktok.com/x' }), ], + [ + 'listing_url', + good({ + marketplace: 'tgdd', + listing_url: 'https://www.topzone.vn/iphone/x', + }), + ], + [ + 'listing_url', + good({ + marketplace: 'tgdd', + listing_url: 'https://www.dienmayxanh.com/dtdd/x', + }), + ], [ 'listing_url', good({ listing_url: `https://shopee.vn/${'a'.repeat(2031)}` }), From 7597d6895fb79d20be0e0e538907e396561f0be8 Mon Sep 17 00:00:00 2001 From: JOY <5027251+JOY@users.noreply.github.com> Date: Sun, 22 Nov 2026 19:02:33 +0700 Subject: [PATCH 3/3] fix(shared): address CodeRabbit review threads in web and extension - Scope legacy tgdd- fallback lookups to the parsed retailer platform and prefer canonical tz-/dmx- IDs in inspect, extension lookup, and item-model resolution. - Align non-An Phat URL slug bounds to 120 chars and An Phat externalId bounds to 128 chars across lookup route and OpenAPI spec. - Exclude An Phat smartphone slugs and HACOM sub-series category paths while keeping laptop, tablet, smartwatch, and earbud listings. - Harden DOM active-container price selectors and PicoPix title suffix boundaries, and clarify 22-store lookup vs 10-store observation scope. --- apps/extension/CHROMEWEBSTORE.md | 2 +- apps/extension/RELEASE.md | 25 +-- apps/extension/src/_locales/cs/messages.json | 2 +- apps/extension/src/_locales/en/messages.json | 2 +- apps/extension/src/_locales/vi/messages.json | 2 +- .../src/extractors/ecommerce-detector.ts | 112 ++++++++-- apps/extension/src/sidepanel/sidepanel.ts | 5 +- apps/extension/src/test-extension-pipeline.ts | 122 ++++++++++- apps/web/locales/cs.json | 4 +- apps/web/locales/en.json | 4 +- apps/web/locales/vi.json | 4 +- .../app/api/v1/rate/extension/lookup/route.ts | 2 +- apps/web/src/lib/rate-api.ts | 86 ++++++-- apps/web/src/lib/rate-domain-core.ts | 41 +++- .../__tests__/core-rate-architecture.test.ts | 193 ++++++++++++++++++ apps/web/src/server/rate/extension.ts | 80 ++++++-- apps/web/src/server/rate/item-api.ts | 54 +++-- apps/web/src/server/rate/openapi.ts | 5 +- 18 files changed, 644 insertions(+), 101 deletions(-) diff --git a/apps/extension/CHROMEWEBSTORE.md b/apps/extension/CHROMEWEBSTORE.md index b4eb50c53..ce1ebf103 100644 --- a/apps/extension/CHROMEWEBSTORE.md +++ b/apps/extension/CHROMEWEBSTORE.md @@ -45,7 +45,7 @@ This table lists exactly what `manifest.json` requests; `test-extension-pipeline 1. **Where it runs:** the content script loads on the 22 supported stores listed above (`shopee.vn`, `lazada.vn`, `tiki.vn`, TikTok Shop product pages on `www.tiktok.com` and `shop.tiktok.com`, `cellphones.com.vn`, `thegioididong.com`, `topzone.vn`, `dienmayxanh.com`, `fptshop.com.vn`, `hoanghamobile.com`, `didongviet.vn`, `phongvu.vn`, `gearvn.com`, `nguyenkim.com`, `shopdunk.com`, `hacom.vn`, `clickbuy.com.vn`, `viettelstore.vn`, `pico.vn`, `mediamart.vn`, `memoryzone.com.vn`, `anphatpc.com.vn`). It acts only on pages it recognises as a product page. The extension itself never opens or fetches pages the user did not open, never works around a store's bot checks and never solves captchas. 2. **Lookup (on by default, no opt-in):** on a recognised product page the extension sends `GET /api/v1/rate/extension/lookup` with the store, the product URL with query parameters and tracking tokens (`utm_*`, `sp_atk`, `xptdk`, `fbclid`, `gclid`) stripped locally, the product title, the store's item id and shop id, the selected variant, the listed price and the original price. The request is read-only and carries no account, name, email or cookies. -3. **Opt-in observation (off by default):** only when the user chooses "Có" / "Yes" on the consent page opened once at first install, or turns on "Đóng góp phát hiện sản phẩm mới (chỉ khi bạn bật)" (English: "Help find new products (only when you turn it on)") in the Side Panel, the extension sends an ExtensionObservation v1 to `POST /api/v1/rate/extension/observation`: the store, the cleaned URL (no query), the item and shop ids, the variant id (SKU), the selected variant, the price, the original price, the stock status and quantity, the time the user saw the price and the extension version, with how the page was read (DOS/Rate#1606). It carries a random submitter id for the install, obtained once from `POST /api/v1/rate/extension/submitter`. No title, no ratings, no account data. The toggle's label and the consent page list these same fields; a test ties them to the payload. Observations go to a quarantine, stored with the time received and a salted hash of the network range (never the IP) to tell independent senders apart; the hash is deleted after 28 days and observations after 180 days. Rate.vn's servers may re-check the listing on the store. They never change public prices directly. Turning the opt-in off calls `DELETE /api/v1/rate/extension/submitter`, which deletes the id and every observation sent with it; the extension keeps retrying that erasure until the server confirms it. Uninstalling without turning it off leaves the observations to the 180-day purge. An opt-in given to the older crowd signal is not taken as consent to this: after the update it is off and the consent page asks again. Closing the consent page keeps the opt-in off, and updates or reloads do not open it again (DOS/Rate#1603). +3. **Opt-in observation (off by default):** only when the user chooses "Có" / "Yes" on the consent page opened once at first install, or turns on "Đóng góp phát hiện sản phẩm mới (chỉ khi bạn bật)" (English: "Help find new products (only when you turn it on)") in the Side Panel, the extension sends an ExtensionObservation v1 to `POST /api/v1/rate/extension/observation` on the 10 quarantine-enabled stores (`shopee.vn`, `lazada.vn`, `tiki.vn`, `www.tiktok.com` and `shop.tiktok.com`, `cellphones.com.vn`, `thegioididong.com`, `fptshop.com.vn`, `hoanghamobile.com`, `didongviet.vn`, `phongvu.vn`; the remaining 12 retail chains are read-only lookup-only for now): the store, the cleaned URL (no query), the item and shop ids, the variant id (SKU), the selected variant, the price, the original price, the stock status and quantity, the time the user saw the price and the extension version, with how the page was read (DOS/Rate#1606). It carries a random submitter id for the install, obtained once from `POST /api/v1/rate/extension/submitter`. No title, no ratings, no account data. The toggle's label and the consent page list these same fields; a test ties them to the payload. Observations go to a quarantine, stored with the time received and a salted hash of the network range (never the IP) to tell independent senders apart; the hash is deleted after 28 days and observations after 180 days. Rate.vn's servers may re-check the listing on the store. They never change public prices directly. Turning the opt-in off calls `DELETE /api/v1/rate/extension/submitter`, which deletes the id and every observation sent with it; the extension keeps retrying that erasure until the server confirms it. Uninstalling without turning it off leaves the observations to the 180-day purge. An opt-in given to the older crowd signal is not taken as consent to this: after the update it is off and the consent page asks again. Closing the consent page keeps the opt-in off, and updates or reloads do not open it again (DOS/Rate#1603). 4. **Stored in the browser only:** the server address, the opt-in choice and, while the user contributes, the submitter id (`chrome.storage.local`), and a session-only cache of the products viewed in each tab, the latest side panel search, their lookup results and a lookup wait time after a rate limit (`chrome.storage.session`). 5. **IP address:** like any web request, the Rate.vn server receives the user's IP address. The lookup and observation routes use it in memory for a per-minute request limit; the observation routes also derive the salted network-range hash above from it. Rate.vn's code never stores the IP itself; the hosting provider keeps standard access logs for a short time. 6. **Side panel requests:** text the user types into the side panel search is sent to the same lookup endpoint; the side panel also reads public deals and merchant lists from the Rate.vn API. diff --git a/apps/extension/RELEASE.md b/apps/extension/RELEASE.md index 83a56311d..dd3f7b90c 100644 --- a/apps/extension/RELEASE.md +++ b/apps/extension/RELEASE.md @@ -4,18 +4,18 @@ Release-readiness check of the extension built from `dev` at `fc9b820d` on 2026- ## 1. Readiness check (2026-10-30) -| Check | Result | Evidence | -| :--------------------------------------------- | :------------------------ | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Build (`pnpm --filter @repo/extension build`) | Pass | `dist/` holds 11 files, 936 KB. The manifest is MV3, version `2.0.0`. | -| Extension tests, typecheck, lint | Pass | `test-extension-pipeline.ts` passes, including #1302, #1304 and #1326; `eslint --max-warnings 0` is clean. | -| Manifest permissions match `CHROMEWEBSTORE.md` | Pass | `storage` and `sidePanel`; 11 store host patterns (10 stores, TikTok on two hosts) plus `rate.vn` and `www.rate.vn`. The content-script matches cover the same origins; on `www.tiktok.com` they are limited to product page paths (#1601). The pipeline test enforces this (#1231). | -| `review_risk_score: null` shown as no data | Pass | The live lookup returns `null` for a seller with no analysed review, and the side panel shows `reviewRiskNoData` (#1266). | -| `dosafe_risk_score: null` | Fixed in #1465 (PR #1476) | A seller with no DOSafe score answers null from the API and reads "chưa đủ dữ liệu" in the side panel, never "0". | -| Verdict `messageKey` and the locale catalogue | Pass | All 10 server keys (`apps/web/src/server/rate/extension.ts`) map in `VERDICT_MESSAGES`. Every label and explanation exists in vi, en and cs with the right placeholder count. The live lookup returns `genuine_deal` and `fair_market` with their params. | -| Lookup ranking (#1379) | Pass | Live lookup of "Apple iPhone 16 128GB" matches `apple-iphone-16-128gb`, not the 16e. | -| 429 handling | Fixed in #1466 | After a 429 the extension sends no lookup until `Retry-After` (default 60 s, cap 600 s), the panel says how many seconds to wait, and the pill looks the product up again once the wait is over. | -| No locale sent | Pass | The lookup sends platform, URL, title, mode, ids, variant and prices, but no locale. The verdict is rendered from `messageKey` in the extension's language. | -| Version header | Fixed in #1466 | `X-Rate-Extension-Version` reads `chrome.runtime.getManifest().version`. | +| Check | Result | Evidence | +| :--------------------------------------------- | :------------------------ | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Build (`pnpm --filter @repo/extension build`) | Pass | `dist/` holds 11 files, 936 KB. The manifest is MV3, version `2.0.0`. | +| Extension tests, typecheck, lint | Pass | `test-extension-pipeline.ts` passes, including #1302, #1304 and #1326; `eslint --max-warnings 0` is clean. | +| Manifest permissions match `CHROMEWEBSTORE.md` | Pass | `storage` and `sidePanel`; 36 store host patterns across 22 stores (TikTok on two hosts, 13 retail chains on bare + subdomain patterns) plus `rate.vn` and `www.rate.vn`. The content-script matches cover the same origins; on `www.tiktok.com` they are limited to product page paths (#1601). The pipeline test enforces this (#1231, #1850). | +| `review_risk_score: null` shown as no data | Pass | The live lookup returns `null` for a seller with no analysed review, and the side panel shows `reviewRiskNoData` (#1266). | +| `dosafe_risk_score: null` | Fixed in #1465 (PR #1476) | A seller with no DOSafe score answers null from the API and reads "chưa đủ dữ liệu" in the side panel, never "0". | +| Verdict `messageKey` and the locale catalogue | Pass | All 10 server keys (`apps/web/src/server/rate/extension.ts`) map in `VERDICT_MESSAGES`. Every label and explanation exists in vi, en and cs with the right placeholder count. The live lookup returns `genuine_deal` and `fair_market` with their params. | +| Lookup ranking (#1379) | Pass | Live lookup of "Apple iPhone 16 128GB" matches `apple-iphone-16-128gb`, not the 16e. | +| 429 handling | Fixed in #1466 | After a 429 the extension sends no lookup until `Retry-After` (default 60 s, cap 600 s), the panel says how many seconds to wait, and the pill looks the product up again once the wait is over. | +| No locale sent | Pass | The lookup sends platform, URL, title, mode, ids, variant and prices, but no locale. The verdict is rendered from `messageKey` in the extension's language. | +| Version header | Fixed in #1466 | `X-Rate-Extension-Version` reads `chrome.runtime.getManifest().version`. | ## 2. Release checklist (JOY publishes) @@ -28,6 +28,7 @@ Release-readiness check of the extension built from `dev` at `fc9b820d` on 2026- - **Opt-in:** the crowd opt-in is off by default, and its label names the fields it sends (#1230, #1241). - **Contribution erasure:** with the observation routes on, opt in, open a product page, then turn the opt-in off: the server holds no observation for the install's id afterwards, and with the network off the erasure is retried at the next start (#1606). - **Consent page:** a fresh install opens the consent page once, with "No" focused. Closing it leaves the opt-in off; "Yes" turns on the side panel toggle; reloading or updating the extension does not open it again (#1603). + - **Host-permission upgrade & re-enable:** install the previous packaged release first, then update in place without uninstalling. Confirm Chrome shows the new host-permission prompt when additional store patterns are introduced; in the release notes and support copy, tell existing users whose install Chrome pauses for new permissions to click the puzzle-piece Extensions menu (or open `chrome://extensions`), select Rate.vn, and click "Accept permissions" / re-enable the toggle so store lookup resumes. 5. Update the store listing: - Description and screenshots match the panel as it is now (the price list and the states from #1319). - The changelog below. diff --git a/apps/extension/src/_locales/cs/messages.json b/apps/extension/src/_locales/cs/messages.json index 67767eb1e..d78236e53 100644 --- a/apps/extension/src/_locales/cs/messages.json +++ b/apps/extension/src/_locales/cs/messages.json @@ -514,7 +514,7 @@ } }, "radarPillSpread": { - "message": "Rozdíl ve 22 obchodech $PCT$ %", + "message": "Rozdíl mezi obchody $PCT$ %", "placeholders": { "pct": { "content": "$1" diff --git a/apps/extension/src/_locales/en/messages.json b/apps/extension/src/_locales/en/messages.json index 48b43c973..515e4a6bd 100644 --- a/apps/extension/src/_locales/en/messages.json +++ b/apps/extension/src/_locales/en/messages.json @@ -514,7 +514,7 @@ } }, "radarPillSpread": { - "message": "22-store gap $PCT$%", + "message": "Cross-store gap $PCT$%", "placeholders": { "pct": { "content": "$1" diff --git a/apps/extension/src/_locales/vi/messages.json b/apps/extension/src/_locales/vi/messages.json index c10479e47..c1b7d4401 100644 --- a/apps/extension/src/_locales/vi/messages.json +++ b/apps/extension/src/_locales/vi/messages.json @@ -514,7 +514,7 @@ } }, "radarPillSpread": { - "message": "Lệch 22 sàn $PCT$%", + "message": "Lệch đa sàn $PCT$%", "placeholders": { "pct": { "content": "$1" diff --git a/apps/extension/src/extractors/ecommerce-detector.ts b/apps/extension/src/extractors/ecommerce-detector.ts index 20386e14a..09bdbbb20 100644 --- a/apps/extension/src/extractors/ecommerce-detector.ts +++ b/apps/extension/src/extractors/ecommerce-detector.ts @@ -342,7 +342,7 @@ const MEDIAMART_ALLOWED_CATEGORY_PREFIXES = new Set([ ]); const HACOM_CATEGORY_BRAND_SLUG_REGEX = - /^(?:laptop-(?:asus|dell|acer|lenovo|hp|msi|apple|lg|gigabyte)|may-tinh-nguyen-bo-theo-hang|may-tinh-mini-da-dung)$/i; + /^(?:laptop-(?:asus(?:-(?:vivobook|zenbook|tuf|rog|expertbook|proart))?|dell(?:-(?:inspiron|vostro|xps|latitude|alienware|precision))?|acer(?:-(?:aspire|nitro|swift|predator|travelmate))?|lenovo(?:-(?:thinkpad|thinkbook|ideapad|legion|loq|yoga))?|hp(?:-(?:pavilion|victus|omen|envy|probook|elitebook|omnibook))?|msi(?:-(?:modern|katana|cyborg|prestige|stealth|raider|thin|sword))?|apple(?:-(?:macbook|macbook-air|macbook-pro))?|lg(?:-gram)?|gigabyte(?:-(?:aorus|aero|gaming))?)|may-tinh-nguyen-bo-theo-hang|may-tinh-mini-da-dung)$/i; const CLICKBUY_NON_PRODUCT_SLUG_REGEX = /^(?:dien-thoai-(?:iphone|samsung|xiaomi|oppo|vivo|realme|nokia|honor|asus|tcl|google|sony|tecno|infinix|masstel|itel)|(?:iphone|samsung|dien-thoai|ipad|macbook|apple-watch)-cu|thay-pin|ep-kinh|google-pixel|trang)$/i; @@ -415,6 +415,23 @@ const ANPHAT_EXTRA_NON_PRODUCT_FIRST_SEGMENTS = new Set([ const ANPHAT_INFO_SUFFIX_REGEX = /(?:^|-)(?:he-thong-showroom|tin-khuyen-mai|tin-tuc|khuyen-mai|bao-hanh|chinh-sach|huong-dan|lien-he|tuyen-dung|gioi-thieu|pc-an-phat)$/i; +const ANPHAT_ACTIVE_DEVICE_SLUG_CUE_REGEX = + /(?:^|[-/_])(?:laptop|may-tinh-xach-tay|macbook|ipad|may-tinh-bang|tablet|galaxy-tab|redmi-pad|xiaomi-pad|matepad|lenovo-tab|apple-watch|galaxy-watch|dong-ho|smartwatch|garmin|amazfit|tai-nghe|airpods|earbuds|galaxy-buds|redmi-buds|headphone|headset)(?:[-/_]|$)/i; + +const ANPHAT_SMARTPHONE_SLUG_REGEX = + /(?:^(?:dien-thoai|iphone|smartphone)(?:-|_|$)|(?:^|[-/_])(?:iphone-\d+|galaxy-(?:s\d+|z-(?:fold|flip)|a\d+|m\d+)|redmi-(?:note|\d+)|poco-[xfmc]\d+|oppo-(?:reno|find)|vivo-[vxyt]\d+|realme-(?:c\d+|gt|\d+)|xiaomi-\d+|google-pixel-\d+)(?:[-/_]|$))/i; + +function isExcludedAnPhatPhoneSlug(slugLower: string): boolean { + if (ANPHAT_DESK_PHONE_SLUG_REGEX.test(slugLower)) return true; + if (/^(?:dien-thoai|iphone|smartphone)(?:-|_|$)/i.test(slugLower)) { + return true; + } + return ( + ANPHAT_SMARTPHONE_SLUG_REGEX.test(slugLower) && + !ANPHAT_ACTIVE_DEVICE_SLUG_CUE_REGEX.test(slugLower) + ); +} + function sha1Hex10(input: string): string { const bytes = new TextEncoder().encode(input); const bitLen = bytes.length * 8; @@ -628,7 +645,7 @@ function extractValidRetailItemSlug( rawKey.length < 3 || rawKey.length > 512 || rawKeyLower.includes('..') || - ANPHAT_DESK_PHONE_SLUG_REGEX.test(rawKeyLower) || + isExcludedAnPhatPhoneSlug(rawKeyLower) || RETAIL_AUTH_OR_NON_PRODUCT_SLUG_REGEX.test(rawKeyLower) || ANPHAT_INFO_SUFFIX_REGEX.test(lastClean.toLowerCase()) ) { @@ -673,7 +690,7 @@ function extractValidRetailItemSlug( (VIETTELSTORE_NON_PRODUCT_PREFIXES.has(lastSegLower) || VIETTELSTORE_CATEGORY_SLUG_REGEX.test(lastSegLower))) || (retailPlatform === 'anphatpc' && - (ANPHAT_DESK_PHONE_SLUG_REGEX.test(lastSegLower) || + (isExcludedAnPhatPhoneSlug(lastSegLower) || ANPHAT_INFO_SUFFIX_REGEX.test(lastSegLower))) ) { return null; @@ -1262,7 +1279,7 @@ export function cleanExtractedProductTitle(rawTitle: string): string { if (!normalizedTitle) return ''; const withoutPlatformSuffix = normalizedTitle .replace( - / ?(?:\||[-\u2013\u2014]) ?(?:Shopee(?:\s*Việt\s*Nam|\s*VN)?|Lazada(?:\s*Việt\s*Nam|\s*VN)?|Tiki(?:\.vn)?|TikTok\s*Shop|CellphoneS(?:\.com\.vn)?|Thế\s*Giới\s*Di\s*Động|Thegioididong(?:\.com)?|TopZone(?:\.vn)?|Điện\s*Máy\s*Xanh|Dienmayxanh(?:\.com)?|FPT\s*Shop|Fptshop(?:\.com\.vn)?|Hoàng\s*Hà\s*Mobile|HoangHaMobile(?:\.com)?|Di\s*Động\s*Việt|Didongviet(?:\.vn)?|Phong\s*Vũ|Phongvu(?:\.vn)?|GearVN(?:\.com)?|Nguy\u1ec5n\s*Kim|Nguyenkim(?:\.com)?|ShopDunk(?:\.com)?|HACOM(?:\.vn)?|Hanoicomputer(?:\.vn)?|Clickbuy(?:\.com\.vn)?|Viettel\s*Store|Viettelstore(?:\.vn)?|Si\u00eau\s*th\u1ecb\s*\u0111i\u1ec7n\s*m\u00e1y\s*Pico|Pico(?:\.vn)?|Media\s*Mart|Mediamart(?:\.vn)?|MemoryZone(?:\.com\.vn)?|An\s*Ph\u00e1t(?:\s*Computer|\s*PC)?|Anphatpc(?:\.com\.vn)?).*$/i, + / ?(?:\||[-\u2013\u2014]) ?(?:Shopee(?:\s*Việt\s*Nam|\s*VN)?|Lazada(?:\s*Việt\s*Nam|\s*VN)?|Tiki(?:\.vn)?|TikTok\s*Shop|CellphoneS(?:\.com\.vn)?|Thế\s*Giới\s*Di\s*Động|Thegioididong(?:\.com)?|TopZone(?:\.vn)?|Điện\s*Máy\s*Xanh|Dienmayxanh(?:\.com)?|FPT\s*Shop|Fptshop(?:\.com\.vn)?|Hoàng\s*Hà\s*Mobile|HoangHaMobile(?:\.com)?|Di\s*Động\s*Việt|Didongviet(?:\.vn)?|Phong\s*Vũ|Phongvu(?:\.vn)?|GearVN(?:\.com)?|Nguy\u1ec5n\s*Kim|Nguyenkim(?:\.com)?|ShopDunk(?:\.com)?|HACOM(?:\.vn)?|Hanoicomputer(?:\.vn)?|Clickbuy(?:\.com\.vn)?|Viettel\s*Store|Viettelstore(?:\.vn)?|Si\u00eau\s*th\u1ecb\s*\u0111i\u1ec7n\s*m\u00e1y\s*Pico|Pico(?:\.vn)?|Media\s*Mart|Mediamart(?:\.vn)?|MemoryZone(?:\.com\.vn)?|An\s*Ph\u00e1t(?:\s*Computer|\s*PC)?|Anphatpc(?:\.com\.vn)?)(?: ?(?:\||[-\u2013\u2014(:]).*)?$/i, '' ) .replace(/\s+/g, ' ') @@ -1441,6 +1458,71 @@ export function extractSelectedVariantFromDom(doc: Document): string | null { return null; } +const NON_PDP_PRICE_ANCESTOR_SELECTOR = + '[hidden], [aria-hidden="true"], .hidden, .d-none, .related-products, .product-related, .similar-products, .viewed-products, .cross-sell, .upsell, .product-list, .product-grid, .product-item, .product-card, .product-box, .p-item, .item-product, .owl-item, .swiper-slide, header, footer, nav, aside'; + +function isExcludedDomPriceNode(el: Element | null | undefined): boolean { + if (!el) return true; + if (typeof el.hasAttribute === 'function' && el.hasAttribute('hidden')) { + return true; + } + if ((el as unknown as { hidden?: boolean }).hidden === true) { + return true; + } + if ( + typeof el.closest === 'function' && + el.closest(NON_PDP_PRICE_ANCESTOR_SELECTOR) + ) { + return true; + } + let ancestor = ( + el as unknown as { + parentElement?: { + hidden?: boolean; + hasAttribute?: (name: string) => boolean; + parentElement?: unknown; + } | null; + } + ).parentElement; + let depth = 0; + while (ancestor && depth < 16) { + if ( + ancestor.hidden === true || + (typeof ancestor.hasAttribute === 'function' && + ancestor.hasAttribute('hidden')) + ) { + return true; + } + ancestor = ancestor.parentElement as typeof ancestor; + depth++; + } + return false; +} + +function queryFirstActivePdpPriceNode( + doc: Document, + selector: string +): Element | null { + if (typeof doc.querySelectorAll === 'function') { + const nodes = Array.from(doc.querySelectorAll(selector)); + if (nodes.length > 0) { + for (const node of nodes) { + if (!isExcludedDomPriceNode(node)) { + return node; + } + } + return null; + } + } + if (typeof doc.querySelector === 'function') { + const single = doc.querySelector(selector); + if (single && !isExcludedDomPriceNode(single)) { + return single; + } + } + return null; +} + /** * Extract product signal from the current DOM + JSON-LD structured data without blocking the main thread. */ @@ -1538,11 +1620,13 @@ export function extractProductSignalFromDom( '[data-testid="pdp-product-price"]', '.pdp-price_type_normal', '.product-price__current-price', + '.product-detail .product-price .pro-price', '.product-price .pro-price', '.product_info_price_value-final', '.overview .prices .actual-price', '.pdp-price-online', '.product-detail-price .price-sale', + '.cb-pbox:not([hidden]) .cb-pbox__now:not([hidden])', '.cb-pbox__now:not([hidden])', '.wrap-price .new-price', '.special-price .price:not(.related-products *):not(.product-item *):not(.product-card *):not(.product-box *):not(header *):not(footer *)', @@ -1551,7 +1635,7 @@ export function extractProductSignalFromDom( ]; if (!price) { for (const sel of priceSelectors) { - const el = doc.querySelector(sel); + const el = queryFirstActivePdpPriceNode(doc, sel); const parsed = parseVndPriceText(el?.textContent); if (parsed) { price = parsed; @@ -1565,11 +1649,13 @@ export function extractProductSignalFromDom( '.ZA5sW5', '.pdp-price_type_deleted', '.product-price__original-price', + '.product-detail .product-price .pro-price-del', '.product-price .pro-price-del', '.product_info_price_value-real', '.overview .old-product-price', '.pdp-price-old', '.product-detail-price .price-old', + '.cb-pbox:not([hidden]) .cb-pbox__old:not([hidden])', '.cb-pbox__old:not([hidden])', '.wrap-price .old-price', '.product-price-regular:not(.related-products *):not(.product-item *):not(.product-card *):not(.product-box *):not(header *):not(footer *)', @@ -1578,13 +1664,15 @@ export function extractProductSignalFromDom( '.box-price-old', 'del', ]; - for (const sel of originalPriceSelectors) { - const el = doc.querySelector(sel); - const parsed = parseVndPriceText(el?.textContent); - if (parsed && (!price || parsed > price)) { - originalPrice = parsed; - originalFromDom = true; - break; + if (!originalPrice) { + for (const sel of originalPriceSelectors) { + const el = queryFirstActivePdpPriceNode(doc, sel); + const parsed = parseVndPriceText(el?.textContent); + if (parsed && (!price || parsed > price)) { + originalPrice = parsed; + originalFromDom = true; + break; + } } } diff --git a/apps/extension/src/sidepanel/sidepanel.ts b/apps/extension/src/sidepanel/sidepanel.ts index 7b7c2315f..bc6f959d8 100644 --- a/apps/extension/src/sidepanel/sidepanel.ts +++ b/apps/extension/src/sidepanel/sidepanel.ts @@ -351,7 +351,10 @@ function renderPanelContent(
${escapeHtml(t('noProductTitle'))}

${tHtml('noProductBody', [ - `${contentTextHtml(t('noProductStores'))}`, + `${t('noProductStores') + .split(', ') + .map((s) => contentTextHtml(s)) + .join(', ')}`, `${contentTextHtml(t('noProductLastStore'))}`, `${escapeHtml(t('quickLookupBoxName'))}`, ])} diff --git a/apps/extension/src/test-extension-pipeline.ts b/apps/extension/src/test-extension-pipeline.ts index 74352d385..0bdfae899 100644 --- a/apps/extension/src/test-extension-pipeline.ts +++ b/apps/extension/src/test-extension-pipeline.ts @@ -12065,6 +12065,14 @@ async function runTests() { 'anphatpc', 'https://www.anphatpc.com.vn/dien-thoai-ban-panasonic-kx-ts500_id1234.html', ], + [ + 'anphatpc', + 'https://www.anphatpc.com.vn/iphone-16-pro-max_id49201.html', + ], + [ + 'anphatpc', + 'https://www.anphatpc.com.vn/dien-thoai-apple-iphone-16-pro-max_id49201.html', + ], ['anphatpc', 'https://www.anphatpc.com.vn/laptop-asus-without-html-ext'], ] as const) { assert.equal( @@ -12547,6 +12555,7 @@ async function runTests() { for (const [plat, nonPdp] of [ ['mediamart', 'https://mediamart.vn/tu-van-tieu-dung/top-5-iphone-16'], ['hacom', 'https://hacom.vn/laptop-asus'], + ['hacom', 'https://hacom.vn/laptop-asus-vivobook'], ['clickbuy', 'https://clickbuy.com.vn/dien-thoai-iphone'], ['clickbuy', 'https://clickbuy.com.vn/iphone-cu'], ['clickbuy', 'https://clickbuy.com.vn/thay-pin'], @@ -12559,18 +12568,119 @@ async function runTests() { nonPdp ); } + assert.equal( + extractIdsFromUrl( + 'hacom', + 'https://hacom.vn/laptop-asus-vivobook-x1407ca-ly008w-ltau1066' + ).externalItemId, + 'laptop-asus-vivobook-x1407ca-ly008w-ltau1066' + ); + assert.equal( + extractIdsFromUrl( + 'anphatpc', + 'https://www.anphatpc.com.vn/tai-nghe-bluetooth-airpods-4-dung-cho-iphone-16_id49202.html' + ).externalItemId, + 'tai-nghe-bluetooth-airpods-4-dung-cho-iphone-16_id49202' + ); - // O(N) title cleaning on pathological whitespace input & An Phát Vietnamese detection - const t0 = performance.now(); + // Long-input title cleaning, PicoPix model preservation & An Phát Vietnamese detection const cleanedAdversarial = cleanExtractedProductTitle( `iPhone 16 Pro${' '.repeat(20_000)}|NotAStore` ); - assert.ok( - performance.now() - t0 < 50, - 'cleanExtractedProductTitle must run in O(N)' - ); assert.ok(cleanedAdversarial.startsWith('iPhone 16 Pro')); + assert.equal( + cleanExtractedProductTitle('Máy chiếu Philips - PicoPix Max | ShopDunk'), + 'Máy chiếu Philips - PicoPix Max' + ); + assert.equal( + cleanExtractedProductTitle('Kính thực tế ảo - Pico 4 Ultra | CellphoneS'), + 'Kính thực tế ảo - Pico 4 Ultra' + ); assert.equal(isVietnameseText('An Phát Computer'), true); + + // Clickbuy hidden ancestor price container skipped in favor of visible container + const hiddenClickbuyPriceNode = { + textContent: '19.990.000₫', + parentElement: { + hidden: true, + hasAttribute: (attr: string) => attr === 'hidden', + }, + closest: (sel: string) => (sel.includes('[hidden]') ? {} : null), + }; + const visibleClickbuyPriceNode = { + textContent: '24.990.000₫', + parentElement: { hidden: false, hasAttribute: () => false }, + closest: () => null, + }; + const clickbuyHiddenFixtureDoc = { + title: 'iPhone 16 128GB Chính hãng - Clickbuy.com.vn', + querySelectorAll: (sel: string) => { + if (sel === 'script[type="application/ld+json"]') return []; + if (sel.includes('.cb-pbox__now')) { + return [hiddenClickbuyPriceNode, visibleClickbuyPriceNode]; + } + return []; + }, + querySelector: (sel: string) => { + if (sel === 'h1') { + return { textContent: 'iPhone 16 128GB Chính hãng' }; + } + if (sel.includes('.cb-pbox__now')) return hiddenClickbuyPriceNode; + return null; + }, + } as unknown as Document; + const clickbuyHiddenSig = extractProductSignalFromDom( + clickbuyHiddenFixtureDoc, + 'https://clickbuy.com.vn/apple-iphone-16-128gb.html' + ); + assert.ok(clickbuyHiddenSig); + assert.equal( + clickbuyHiddenSig.price, + 24_990_000, + 'must skip hidden Clickbuy price container and read active visible price' + ); + + // Related-product .pro-price-del must never overwrite structured JSON-LD originalPrice + const relatedDelNode = { + textContent: '24.990.000₫', + closest: (sel: string) => (sel.includes('.related-products') ? {} : null), + }; + const structuredListPriceDoc = { + title: 'iPad Gen 10 64GB | GearVN.com', + querySelectorAll: (sel: string) => { + if (sel === 'script[type="application/ld+json"]') { + return [ + { + textContent: JSON.stringify({ + '@type': 'Product', + name: 'iPad Gen 10 64GB', + offers: { + '@type': 'AggregateOffer', + lowPrice: '12990000', + highPrice: '14990000', + availability: 'https://schema.org/InStock', + }, + }), + }, + ]; + } + if (sel.includes('.pro-price-del')) return [relatedDelNode]; + return []; + }, + querySelector: (sel: string) => + sel.includes('.pro-price-del') ? relatedDelNode : null, + } as unknown as Document; + const structuredListSig = extractProductSignalFromDom( + structuredListPriceDoc, + 'https://gearvn.com/products/ipad-gen-10-64gb' + ); + assert.ok(structuredListSig); + assert.equal(structuredListSig.price, 12_990_000); + assert.equal( + structuredListSig.originalPrice, + 14_990_000, + 'related-product .pro-price-del must not replace JSON-LD originalPrice' + ); } console.log('🎉 All Rate Browser Extension MV3 v2 tests passed!'); } diff --git a/apps/web/locales/cs.json b/apps/web/locales/cs.json index 8d205bf79..ea5b02d30 100644 --- a/apps/web/locales/cs.json +++ b/apps/web/locales/cs.json @@ -1600,7 +1600,7 @@ "privacyS4Title": "4. Soukromé údaje prodejců", "privacyS4Desc": "Soukromé údaje prodejce (telefonní číslo, bankovní účet) jsou v polích, která veřejnost nemůže číst. Web i API mohou číst jen veřejná pole.", "privacyS5Title": "5. Rozšíření prohlížeče Rate.vn", - "privacyS5Desc": "Na stránkách produktů 22 podporovaných obchodů rozšíření posílá Rate.vn obchod, URL produktu bez parametrů, název produktu, ID položky a obchodu, zvolenou variantu, cenu a původní cenu, aby vyhledalo historii cen; toto vyhledávání je zapnuté ve výchozím stavu, jen čte a nepotřebuje účet. Text, který napíšete do vyhledávacího pole rozšíření, se také odešle k vyhledání. Jen když zvolíte \"Ano\" na stránce zobrazené při instalaci nebo zapnete \"Pomoc s hledáním nových produktů (jen když ji zapnete)\" v bočním panelu (ve výchozím stavu vypnuto), posílá také do fronty ke kontrole záznam o dané nabídce: obchod, URL bez parametrů, ID položky a obchodu, ID varianty (SKU), zvolenou variantu, cenu, původní cenu, stav a počet kusů skladem, čas, kdy jste cenu viděli, a verzi rozšíření, spolu s náhodným ID přispěvatele této instalace. Server jej ukládá s časem přijetí a s osoleným otiskem rozsahu vaší sítě (ne IP adresou), aby rozlišil nezávislé odesílatele; otisk se maže po 28 dnech a záznam po 180 dnech. Servery Rate.vn mohou nabídku v obchodě znovu ověřit a tato data sama veřejné ceny nemění. Vypnutím přispívání se ID přispěvatele i všechny odeslané záznamy smažou; pokud rozšíření odinstalujete bez vypnutí, smažou se po 180 dnech. Rozšíření neposílá účet, jméno, e-mail ani cookies, neotevírá stránky, které jste neotevřeli, a ve vašem prohlížeči ukládá jen adresu serveru, volbu opt-in, ID přispěvatele této instalace, dokud přispíváte, a mezipaměť platnou po dobu relace s produkty, které jste si prohlédli, vaším posledním hledáním, výsledky vyhledávání a dobou čekání na další vyhledání. Jako u každého webového požadavku server obdrží vaši IP adresu: kód Rate.vn ji používá v paměti pro limit požadavků za minutu a při přispívání k odvození výše uvedeného otisku rozsahu sítě; samotná IP adresa se nikdy neukládá a náš poskytovatel hostingu uchovává běžné přístupové záznamy po krátkou dobu.", + "privacyS5Desc": "Na stránkách produktů 22 podporovaných obchodů rozšíření posílá Rate.vn obchod, URL produktu bez parametrů, název produktu, ID položky a obchodu, zvolenou variantu, cenu a původní cenu, aby vyhledalo historii cen; toto vyhledávání je zapnuté ve výchozím stavu, jen čte a nepotřebuje účet. Text, který napíšete do vyhledávacího pole rozšíření, se také odešle k vyhledání. Jen když zvolíte \"Ano\" na stránce zobrazené při instalaci nebo zapnete \"Pomoc s hledáním nových produktů (jen když ji zapnete)\" v bočním panelu (ve výchozím stavu vypnuto), posílá také do fronty ke kontrole záznam o dané nabídce v 10 obchodech se zapnutou kontrolní frontou (12 novějších řetězců je zatím pouze pro čtecí vyhledávání): obchod, URL bez parametrů, ID položky a obchodu, ID varianty (SKU), zvolenou variantu, cenu, původní cenu, stav a počet kusů skladem, čas, kdy jste cenu viděli, a verzi rozšíření, spolu s náhodným ID přispěvatele této instalace. Server jej ukládá s časem přijetí a s osoleným otiskem rozsahu vaší sítě (ne IP adresou), aby rozlišil nezávislé odesílatele; otisk se maže po 28 dnech a záznam po 180 dnech. Servery Rate.vn mohou nabídku v obchodě znovu ověřit a tato data sama veřejné ceny nemění. Vypnutím přispívání se ID přispěvatele i všechny odeslané záznamy smažou; pokud rozšíření odinstalujete bez vypnutí, smažou se po 180 dnech. Rozšíření neposílá účet, jméno, e-mail ani cookies, neotevírá stránky, které jste neotevřeli, a ve vašem prohlížeči ukládá jen adresu serveru, volbu opt-in, ID přispěvatele této instalace, dokud přispíváte, a mezipaměť platnou po dobu relace s produkty, které jste si prohlédli, vaším posledním hledáním, výsledky vyhledávání a dobou čekání na další vyhledání. Jako u každého webového požadavku server obdrží vaši IP adresu: kód Rate.vn ji používá v paměti pro limit požadavků za minutu a při přispívání k odvození výše uvedeného otisku rozsahu sítě; samotná IP adresa se nikdy neukládá a náš poskytovatel hostingu uchovává běžné přístupové záznamy po krátkou dobu.", "privacySide1Title": "Ověřte si otevřený kód", "privacySide1Desc": "Pravidla přístupu k datům a způsob ukládání hlasů jsou veřejné v repozitáři na GitHubu.", "privacySide1Btn": "Technická a API dokumentace", @@ -1634,7 +1634,7 @@ "contactSeoDesc": "Nahlaste falešné slevy nebo falešné recenze, nebo požádejte o přezkoumání důvěryhodnosti prodejce na Rate.vn.", "contactHeroBadge": "Kontakt a zpětná vazba", "contactHeroTitle": "Rychlá inspekce a nahlášení podezřelého obchodu", - "contactHeroDesc": "Vložte níže odkaz na produkt nebo obchod ze 22 podporovaných obchodů (Shopee, Lazada, Tiki, TikTok Shop, CellphoneS, TGDD, Dien May Xanh, TopZone, FPT Shop, Hoang Ha, Di Dong Viet, Phong Vu, GearVN, Nguyen Kim, ShopDunk, HACOM, Clickbuy, Viettel Store, Pico, MediaMart, MemoryZone, An Phat) a zobrazte historii cen, nebo odkaz pošlete Rate.vn ke kontrole.", + "contactHeroDesc": "Vložte níže odkaz na produkt nebo obchod ze 22 podporovaných obchodů (Shopee, Lazada, Tiki, TikTok Shop, CellphoneS, TGDD, Dien May Xanh, TopZone, FPT Shop, Hoang Ha, Di Dong Viet, Phong Vu, GearVN, Nguyen Kim, ShopDunk, HACOM, Clickbuy, Viettel Store, Pico, MediaMart, MemoryZone, An Phat) pro okamžité zobrazení historie cen, nebo odešlete odkaz z 10 obchodů se zapnutou kontrolní frontou ke kontrole Rate.vn.", "contactCard1Title": "1. Nahlášení falešných slev a falešných recenzí", "contactCard1Desc": "Když uvidíte původní cenu navýšenou před výprodejem, vložte odkaz na produkt do kontroly na této stránce. Když uvidíte falešné účty opakující šablonové recenze, přihlaste se a u té recenze na stránce produktu klikněte na \"Nahlásit\".", "contactCard1Btn": "Přejít do katalogu produktů →", diff --git a/apps/web/locales/en.json b/apps/web/locales/en.json index dab328403..4fb58a61f 100644 --- a/apps/web/locales/en.json +++ b/apps/web/locales/en.json @@ -1600,7 +1600,7 @@ "privacyS4Title": "4. Sellers' private details", "privacyS4Desc": "A seller's private details (phone number, bank account) are kept in fields the public cannot read. The website and the API can only read the public fields.", "privacyS5Title": "5. The Rate.vn browser extension", - "privacyS5Desc": "On product pages of the 22 supported stores, the extension sends Rate.vn the store, the product URL without its parameters, the product title, the item and shop ids, the selected variant, the price and the original price to look up price history; this lookup is on by default, read-only and needs no account. Text you type into the extension's search box is also sent to look it up. Only if you choose \"Yes\" on the page shown at install or turn on \"Help find new products (only when you turn it on)\" in the side panel (off by default) does it also send an observation of that listing to a moderation queue: the store, the URL without its parameters, the item and shop ids, the variant ID (SKU), the selected variant, the price, the original price, the stock status and quantity, the time you saw the price and the extension version, with a random contributor ID for this install. The server stores it with the time it was received and a salted hash of your network range (not your IP) to tell independent senders apart; the hash is deleted after 28 days and the observation after 180 days. Rate.vn's servers may re-check that listing on the store, and this data does not change public prices by itself. Turning contributions off deletes the contributor ID and every observation sent with it; if you uninstall without turning it off, they are deleted after 180 days. The extension sends no account, name, email or cookies, opens no page you did not open, and keeps only the server address, the opt-in choice, the contributor ID while you contribute, and a session-only cache of the products you viewed, your latest search, their lookup results and a lookup wait time in your browser. Like any web request, the server receives your IP address: Rate.vn's code uses it in memory for a per-minute request limit and, when you contribute, to derive the network-range hash above; the IP itself is never stored, and our hosting provider keeps standard access logs for a short time.", + "privacyS5Desc": "On product pages of the 22 supported stores, the extension sends Rate.vn the store, the product URL without its parameters, the product title, the item and shop ids, the selected variant, the price and the original price to look up price history; this lookup is on by default, read-only and needs no account. Text you type into the extension's search box is also sent to look it up. Only if you choose \"Yes\" on the page shown at install or turn on \"Help find new products (only when you turn it on)\" in the side panel (off by default) does it also send an observation of that listing to a moderation queue on the 10 stores with queue support enabled (the 12 newer retail chains are currently read-only lookup-only): the store, the URL without its parameters, the item and shop ids, the variant ID (SKU), the selected variant, the price, the original price, the stock status and quantity, the time you saw the price and the extension version, with a random contributor ID for this install. The server stores it with the time it was received and a salted hash of your network range (not your IP) to tell independent senders apart; the hash is deleted after 28 days and the observation after 180 days. Rate.vn's servers may re-check that listing on the store, and this data does not change public prices by itself. Turning contributions off deletes the contributor ID and every observation sent with it; if you uninstall without turning it off, they are deleted after 180 days. The extension sends no account, name, email or cookies, opens no page you did not open, and keeps only the server address, the opt-in choice, the contributor ID while you contribute, and a session-only cache of the products you viewed, your latest search, their lookup results and a lookup wait time in your browser. Like any web request, the server receives your IP address: Rate.vn's code uses it in memory for a per-minute request limit and, when you contribute, to derive the network-range hash above; the IP itself is never stored, and our hosting provider keeps standard access logs for a short time.", "privacySide1Title": "Check the open code", "privacySide1Desc": "The data access rules and how votes are stored are public in the GitHub repository.", "privacySide1Btn": "Technical and API docs", @@ -1634,7 +1634,7 @@ "contactSeoDesc": "Report fake discounts or fake reviews, or ask for a seller trust review on Rate.vn.", "contactHeroBadge": "Contact & feedback", "contactHeroTitle": "Quick URL inspection & suspicious merchant reporting", - "contactHeroDesc": "Paste a product or shop link from 22 supported marketplaces and retailers (Shopee, Lazada, Tiki, TikTok Shop, CellphoneS, TGDD, Dien May Xanh, TopZone, FPT Shop, Hoang Ha, Di Dong Viet, Phong Vu, GearVN, Nguyen Kim, ShopDunk, HACOM, Clickbuy, Viettel Store, Pico, MediaMart, MemoryZone, An Phat) below to see its price history, or send the link for Rate.vn to check.", + "contactHeroDesc": "Paste a product or shop link from 22 supported marketplaces and retailers (Shopee, Lazada, Tiki, TikTok Shop, CellphoneS, TGDD, Dien May Xanh, TopZone, FPT Shop, Hoang Ha, Di Dong Viet, Phong Vu, GearVN, Nguyen Kim, ShopDunk, HACOM, Clickbuy, Viettel Store, Pico, MediaMart, MemoryZone, An Phat) below to see its price history right away, or submit a link from the 10 queue-enabled stores for Rate.vn to check.", "contactCard1Title": "1. Report fake discounts and fake reviews", "contactCard1Desc": "If you see a list price inflated before a sale, paste the product link into the checker on this page. If you see fake accounts repeating template reviews, sign in and click \"Report\" on that review on the product page.", "contactCard1Btn": "Go to product catalog →", diff --git a/apps/web/locales/vi.json b/apps/web/locales/vi.json index f720595be..72f4ea0eb 100644 --- a/apps/web/locales/vi.json +++ b/apps/web/locales/vi.json @@ -1600,7 +1600,7 @@ "privacyS4Title": "4. Thông tin riêng của gian hàng", "privacyS4Desc": "Thông tin riêng của gian hàng (số điện thoại, tài khoản ngân hàng) nằm ở các trường mà công chúng không đọc được. Trang web và API chỉ đọc được các trường công khai.", "privacyS5Title": "5. Tiện ích trình duyệt Rate.vn", - "privacyS5Desc": "Trên trang sản phẩm của 22 sàn được hỗ trợ, tiện ích gửi cho Rate.vn sàn, URL sản phẩm đã bỏ tham số, tên sản phẩm, mã sản phẩm và mã gian hàng, phiên bản đang chọn, giá bán và giá gốc để tra lịch sử giá; việc tra cứu này bật sẵn, chỉ đọc và không cần tài khoản. Nội dung bạn gõ vào ô tìm kiếm của tiện ích cũng được gửi để tra cứu. Chỉ khi bạn chọn \"Có\" ở trang hiện ra lúc cài đặt hoặc bật \"Đóng góp phát hiện sản phẩm mới (chỉ khi bạn bật)\" trong bảng bên cạnh (mặc định tắt), tiện ích còn gửi vào hàng đợi kiểm duyệt một quan sát về tin bán đó: sàn, URL đã bỏ tham số, mã sản phẩm, mã gian hàng, mã SKU của phân loại, phiên bản đang chọn, giá bán, giá gốc, tình trạng và số lượng còn hàng, thời điểm bạn thấy giá và phiên bản tiện ích, kèm một mã người đóng góp ngẫu nhiên của lượt cài này. Máy chủ lưu kèm thời điểm nhận và một mã băm có muối của dải mạng (không phải IP) để phân biệt người gửi độc lập; mã băm được xóa sau 28 ngày, quan sát sau 180 ngày. Máy chủ Rate.vn có thể kiểm tra lại tin bán đó trên sàn, và dữ liệu này không tự đổi giá công khai. Tắt đóng góp là xóa mã người đóng góp cùng mọi quan sát đã gửi; nếu gỡ tiện ích mà chưa tắt, chúng tự xóa sau 180 ngày. Tiện ích không gửi tài khoản, tên, email hay cookie, không mở trang bạn không mở, và chỉ lưu trên trình duyệt của bạn địa chỉ máy chủ, lựa chọn có đóng góp hay không, mã người đóng góp khi bạn đóng góp, cùng bộ nhớ tạm theo phiên gồm các sản phẩm bạn vừa xem, lần tìm kiếm gần nhất, kết quả tra cứu và thời gian chờ khi bị giới hạn tra cứu. Như mọi yêu cầu web, máy chủ nhận địa chỉ IP của bạn: mã của Rate.vn dùng nó trong bộ nhớ để giới hạn số yêu cầu mỗi phút và, khi bạn đóng góp, để tính mã băm dải mạng nói trên; bản thân IP không bao giờ được lưu, còn nhà cung cấp hosting giữ nhật ký truy cập thông thường trong thời gian ngắn.", + "privacyS5Desc": "Trên trang sản phẩm của 22 sàn được hỗ trợ, tiện ích gửi cho Rate.vn sàn, URL sản phẩm đã bỏ tham số, tên sản phẩm, mã sản phẩm và mã gian hàng, phiên bản đang chọn, giá bán và giá gốc để tra lịch sử giá; việc tra cứu này bật sẵn, chỉ đọc và không cần tài khoản. Nội dung bạn gõ vào ô tìm kiếm của tiện ích cũng được gửi để tra cứu. Chỉ khi bạn chọn \"Có\" ở trang hiện ra lúc cài đặt hoặc bật \"Đóng góp phát hiện sản phẩm mới (chỉ khi bạn bật)\" trong bảng bên cạnh (mặc định tắt), tiện ích còn gửi vào hàng đợi kiểm duyệt một quan sát về tin bán đó trên 10 sàn đã mở hàng đợi kiểm duyệt (12 chuỗi bán lẻ mới hiện chỉ tra cứu một chiều): sàn, URL đã bỏ tham số, mã sản phẩm, mã gian hàng, mã SKU của phân loại, phiên bản đang chọn, giá bán, giá gốc, tình trạng và số lượng còn hàng, thời điểm bạn thấy giá và phiên bản tiện ích, kèm một mã người đóng góp ngẫu nhiên của lượt cài này. Máy chủ lưu kèm thời điểm nhận và một mã băm có muối của dải mạng (không phải IP) để phân biệt người gửi độc lập; mã băm được xóa sau 28 ngày, quan sát sau 180 ngày. Máy chủ Rate.vn có thể kiểm tra lại tin bán đó trên sàn, và dữ liệu này không tự đổi giá công khai. Tắt đóng góp là xóa mã người đóng góp cùng mọi quan sát đã gửi; nếu gỡ tiện ích mà chưa tắt, chúng tự xóa sau 180 ngày. Tiện ích không gửi tài khoản, tên, email hay cookie, không mở trang bạn không mở, và chỉ lưu trên trình duyệt của bạn địa chỉ máy chủ, lựa chọn có đóng góp hay không, mã người đóng góp khi bạn đóng góp, cùng bộ nhớ tạm theo phiên gồm các sản phẩm bạn vừa xem, lần tìm kiếm gần nhất, kết quả tra cứu và thời gian chờ khi bị giới hạn tra cứu. Như mọi yêu cầu web, máy chủ nhận địa chỉ IP của bạn: mã của Rate.vn dùng nó trong bộ nhớ để giới hạn số yêu cầu mỗi phút và, khi bạn đóng góp, để tính mã băm dải mạng nói trên; bản thân IP không bao giờ được lưu, còn nhà cung cấp hosting giữ nhật ký truy cập thông thường trong thời gian ngắn.", "privacySide1Title": "Kiểm tra mã nguồn công khai", "privacySide1Desc": "Quy tắc phân quyền dữ liệu và cách lưu bình chọn đều công khai trong repository trên GitHub.", "privacySide1Btn": "Xem tài liệu kỹ thuật và API", @@ -1634,7 +1634,7 @@ "contactSeoDesc": "Gửi link sản phẩm hoặc gian hàng Shopee, Lazada, Tiki có dấu hiệu nâng khống giá gốc hoặc đánh giá ảo để Rate.vn kiểm tra.", "contactHeroBadge": "Liên hệ & phản hồi", "contactHeroTitle": "Kiểm tra nhanh và báo cáo gian hàng bất thường", - "contactHeroDesc": "Dán link sản phẩm hoặc gian hàng từ 22 sàn và chuỗi bán lẻ (Shopee, Lazada, Tiki, TikTok Shop, CellphoneS, TGDĐ, Điện Máy Xanh, TopZone, FPT Shop, Hoàng Hà, Di Động Việt, Phong Vũ, GearVN, Nguyễn Kim, ShopDunk, HACOM, Clickbuy, Viettel Store, Pico, MediaMart, MemoryZone, An Phát) vào ô bên dưới để xem lịch sử giá, hoặc gửi link để Rate.vn kiểm tra.", + "contactHeroDesc": "Dán link sản phẩm hoặc gian hàng từ 22 sàn và chuỗi bán lẻ (Shopee, Lazada, Tiki, TikTok Shop, CellphoneS, TGDĐ, Điện Máy Xanh, TopZone, FPT Shop, Hoàng Hà, Di Động Việt, Phong Vũ, GearVN, Nguyễn Kim, ShopDunk, HACOM, Clickbuy, Viettel Store, Pico, MediaMart, MemoryZone, An Phát) vào ô bên dưới để xem lịch sử giá tức thì, hoặc gửi link từ 10 sàn đã mở hàng đợi kiểm duyệt để Rate.vn kiểm tra.", "contactCard1Title": "1. Báo cáo giảm giá ảo và đánh giá ảo", "contactCard1Desc": "Khi thấy giá gốc bị nâng trước ngày sale, hãy dán link sản phẩm vào ô kiểm tra ở trang này. Khi thấy tài khoản ảo lặp lại bình luận mẫu để đẩy sao, hãy đăng nhập rồi bấm \"Báo cáo\" ngay tại đánh giá đó trên trang sản phẩm.", "contactCard1Btn": "Tới danh mục sản phẩm →", diff --git a/apps/web/src/app/api/v1/rate/extension/lookup/route.ts b/apps/web/src/app/api/v1/rate/extension/lookup/route.ts index bcf42bc08..1946182d4 100644 --- a/apps/web/src/app/api/v1/rate/extension/lookup/route.ts +++ b/apps/web/src/app/api/v1/rate/extension/lookup/route.ts @@ -64,7 +64,7 @@ export async function GET(request: NextRequest) { const sp = request.nextUrl.searchParams; const platform = parseBoundedStringParam(sp.get('platform'), 32); - const externalId = parseBoundedStringParam(sp.get('externalId'), 120); + const externalId = parseBoundedStringParam(sp.get('externalId'), 128); const shopId = parseBoundedStringParam(sp.get('shopId'), 120); const url = parseBoundedStringParam(sp.get('url'), 1024); const title = parseBoundedStringParam(sp.get('title'), 320); diff --git a/apps/web/src/lib/rate-api.ts b/apps/web/src/lib/rate-api.ts index b772084dc..d45f871b0 100644 --- a/apps/web/src/lib/rate-api.ts +++ b/apps/web/src/lib/rate-api.ts @@ -4632,18 +4632,33 @@ export async function inspectProductOrShopUrl( const rawItemId = parsedUrl.platformItemId; const lowerItemId = rawItemId.toLowerCase(); const candidateIds = new Set([rawItemId, lowerItemId]); - if (parsedUrl.platformShopId) { - candidateIds.add(`${parsedUrl.platformShopId}_${rawItemId}`); - } const prefix = parsedUrl.platform ? PLATFORM_ITEM_ID_PREFIX[parsedUrl.platform] : undefined; + const isOverlongRetailSlug = (slug: string): boolean => + Boolean(prefix && parsedUrl.platform !== 'anphatpc' && slug.length > 120); + const barePrefixedInput = + prefix && + lowerItemId.startsWith(prefix) && + rawItemId.length > prefix.length + ? rawItemId.slice(prefix.length) + : rawItemId; + if (!isOverlongRetailSlug(barePrefixedInput)) { + candidateIds.add(rawItemId); + candidateIds.add(lowerItemId); + } else { + candidateIds.clear(); + } + if (!prefix && parsedUrl.platformShopId && !rawItemId.includes('_')) { + candidateIds.add(`${parsedUrl.platformShopId}_${rawItemId}`); + } if (prefix) { const rawSlugs = [rawItemId]; if (lowerItemId.startsWith(prefix) && rawItemId.length > prefix.length) { rawSlugs.push(rawItemId.slice(prefix.length)); } for (const slugCandidate of rawSlugs) { + if (isOverlongRetailSlug(slugCandidate)) continue; const lowerSlug = slugCandidate.toLowerCase(); if (`${prefix}${slugCandidate}`.length <= 128) { candidateIds.add(`${prefix}${slugCandidate}`); @@ -4672,29 +4687,66 @@ export async function inspectProductOrShopUrl( parsedUrl.platform === 'dienmayxanh' ) { const bareMwg = rawItemId.replace(/^(?:tz|dmx|tgdd)-/i, ''); - if (bareMwg) { + if (bareMwg && bareMwg.length <= 120) { + if (prefix && /^tgdd-/i.test(rawItemId)) { + candidateIds.add(`${prefix}${bareMwg}`); + candidateIds.add(`${prefix}${bareMwg.toLowerCase()}`); + } candidateIds.add(`tgdd-${bareMwg}`); candidateIds.add(`tgdd-${bareMwg.toLowerCase()}`); } } - const { data: prodRow, error: prodErr } = await supabase - .from('products') - .select('id, cluster_id, merchant_id, platform_item_id') - .in('platform_item_id', Array.from(candidateIds)) - .limit(1) - .maybeSingle(); - - if (prodErr) { - throw new RateDataUnavailableError('URL product listing lookup', prodErr); - } - - const matchedProd = prodRow as { + type ListingLookupRow = { id: string; cluster_id: string | null; merchant_id: string; + platform?: string | null; platform_item_id: string; - } | null; + }; + const orderedCandidates = Array.from(candidateIds); + let matchedProd: ListingLookupRow | null = null; + + if (orderedCandidates.length > 0) { + let prodQuery = supabase + .from('products') + .select('id, cluster_id, merchant_id, platform, platform_item_id') + .in('platform_item_id', orderedCandidates); + if (parsedUrl.platform && parsedUrl.platform !== 'rate') { + prodQuery = prodQuery.eq('platform', parsedUrl.platform); + } + const { data: prodData, error: prodErr } = await prodQuery.limit(10); + + if (prodErr) { + throw new RateDataUnavailableError( + 'URL product listing lookup', + prodErr + ); + } + + const rawProdRows: ListingLookupRow[] = Array.isArray(prodData) + ? (prodData as ListingLookupRow[]) + : prodData + ? [prodData as ListingLookupRow] + : []; + const scopedProdRows = rawProdRows + .filter( + (r) => + !parsedUrl.platform || + parsedUrl.platform === 'rate' || + !r.platform || + r.platform === parsedUrl.platform + ) + .sort((a, b) => { + const ai = orderedCandidates.indexOf(a.platform_item_id); + const bi = orderedCandidates.indexOf(b.platform_item_id); + return (ai === -1 ? 999 : ai) - (bi === -1 ? 999 : bi); + }); + matchedProd = + scopedProdRows.find((r) => Boolean(r.cluster_id)) ?? + scopedProdRows[0] ?? + null; + } if (matchedProd?.cluster_id) { // A draft master has no product page (DOS/Rate#769). The listing is diff --git a/apps/web/src/lib/rate-domain-core.ts b/apps/web/src/lib/rate-domain-core.ts index 990f24e43..4437560c7 100644 --- a/apps/web/src/lib/rate-domain-core.ts +++ b/apps/web/src/lib/rate-domain-core.ts @@ -1866,7 +1866,7 @@ const MEDIAMART_ALLOWED_CATEGORY_PREFIXES = new Set([ ]); const HACOM_CATEGORY_BRAND_SLUG_REGEX = - /^(?:laptop-(?:asus|dell|acer|lenovo|hp|msi|apple|lg|gigabyte)|may-tinh-nguyen-bo-theo-hang|may-tinh-mini-da-dung)$/i; + /^(?:laptop-(?:asus(?:-(?:vivobook|zenbook|tuf|rog|expertbook|proart))?|dell(?:-(?:inspiron|vostro|xps|latitude|alienware|precision))?|acer(?:-(?:aspire|nitro|swift|predator|travelmate))?|lenovo(?:-(?:thinkpad|thinkbook|ideapad|legion|loq|yoga))?|hp(?:-(?:pavilion|victus|omen|envy|probook|elitebook|omnibook))?|msi(?:-(?:modern|katana|cyborg|prestige|stealth|raider|thin|sword))?|apple(?:-(?:macbook|macbook-air|macbook-pro))?|lg(?:-gram)?|gigabyte(?:-(?:aorus|aero|gaming))?)|may-tinh-nguyen-bo-theo-hang|may-tinh-mini-da-dung)$/i; const CLICKBUY_NON_PRODUCT_SLUG_REGEX = /^(?:dien-thoai-(?:iphone|samsung|xiaomi|oppo|vivo|realme|nokia|honor|asus|tcl|google|sony|tecno|infinix|masstel|itel)|(?:iphone|samsung|dien-thoai|ipad|macbook|apple-watch)-cu|thay-pin|ep-kinh|google-pixel|trang)$/i; @@ -1939,6 +1939,23 @@ const ANPHAT_EXTRA_NON_PRODUCT_FIRST_SEGMENTS = new Set([ const ANPHAT_INFO_SUFFIX_REGEX = /(?:^|-)(?:he-thong-showroom|tin-khuyen-mai|tin-tuc|khuyen-mai|bao-hanh|chinh-sach|huong-dan|lien-he|tuyen-dung|gioi-thieu|pc-an-phat)$/i; +const ANPHAT_ACTIVE_DEVICE_SLUG_CUE_REGEX = + /(?:^|[-/_])(?:laptop|may-tinh-xach-tay|macbook|ipad|may-tinh-bang|tablet|galaxy-tab|redmi-pad|xiaomi-pad|matepad|lenovo-tab|apple-watch|galaxy-watch|dong-ho|smartwatch|garmin|amazfit|tai-nghe|airpods|earbuds|galaxy-buds|redmi-buds|headphone|headset)(?:[-/_]|$)/i; + +const ANPHAT_SMARTPHONE_SLUG_REGEX = + /(?:^(?:dien-thoai|iphone|smartphone)(?:-|_|$)|(?:^|[-/_])(?:iphone-\d+|galaxy-(?:s\d+|z-(?:fold|flip)|a\d+|m\d+)|redmi-(?:note|\d+)|poco-[xfmc]\d+|oppo-(?:reno|find)|vivo-[vxyt]\d+|realme-(?:c\d+|gt|\d+)|xiaomi-\d+|google-pixel-\d+)(?:[-/_]|$))/i; + +function isExcludedAnPhatPhoneSlug(slugLower: string): boolean { + if (ANPHAT_DESK_PHONE_SLUG_REGEX.test(slugLower)) return true; + if (/^(?:dien-thoai|iphone|smartphone)(?:-|_|$)/i.test(slugLower)) { + return true; + } + return ( + ANPHAT_SMARTPHONE_SLUG_REGEX.test(slugLower) && + !ANPHAT_ACTIVE_DEVICE_SLUG_CUE_REGEX.test(slugLower) + ); +} + function sha1Hex10(input: string): string { const bytes = new TextEncoder().encode(input); const bitLen = bytes.length * 8; @@ -2155,7 +2172,7 @@ function extractValidRetailItemSlug( rawKey.length < 3 || rawKey.length > 512 || rawKeyLower.includes('..') || - ANPHAT_DESK_PHONE_SLUG_REGEX.test(rawKeyLower) || + isExcludedAnPhatPhoneSlug(rawKeyLower) || RETAIL_AUTH_OR_NON_PRODUCT_SLUG_REGEX.test(rawKeyLower) || ANPHAT_INFO_SUFFIX_REGEX.test(lastClean.toLowerCase()) ) { @@ -2200,7 +2217,7 @@ function extractValidRetailItemSlug( (VIETTELSTORE_NON_PRODUCT_PREFIXES.has(lastSegLower) || VIETTELSTORE_CATEGORY_SLUG_REGEX.test(lastSegLower))) || (retailPlatform === 'anphatpc' && - (ANPHAT_DESK_PHONE_SLUG_REGEX.test(lastSegLower) || + (isExcludedAnPhatPhoneSlug(lastSegLower) || ANPHAT_INFO_SUFFIX_REGEX.test(lastSegLower))) ) { return null; @@ -2210,7 +2227,7 @@ function extractValidRetailItemSlug( return sanitizeAnPhatItemId(lastSeg) || null; } - return lastSeg; + return lastSeg.length <= 120 ? lastSeg : null; } export function parseEcommerceUrlOrQuery(raw: string): ParsedEcommerceUrl { @@ -2608,6 +2625,9 @@ export function extractProductKeywordFromUrl(rawUrl?: string | null): string { rawSegments.length === 4 && firstSegLower === 'collections' && rawSegments[2]?.toLowerCase() === 'products'; + const rawLeaf = rawSegments[rawSegments.length - 1] || ''; + const vtsLeafLower = rawLeaf.toLowerCase().replace(/\.html?$/i, ''); + const vtsLeafHasPid = /(?:^|-)pid[1-9]\d{1,14}$/i.test(vtsLeafLower); if ( (!isCollectionProductPath && RETAIL_NON_PRODUCT_FIRST_SEGMENTS.has(firstSegLower)) || @@ -2618,15 +2638,20 @@ export function extractProductKeywordFromUrl(rawUrl?: string | null): string { (rawSegments.length !== 2 || !MEDIAMART_ALLOWED_CATEGORY_PREFIXES.has(firstSegLower))) || (isDomainOrSubdomain(parsedHostLower, 'viettelstore.vn') && - rawSegments.length === 2 && - VIETTELSTORE_NON_PRODUCT_PREFIXES.has(firstSegLower)) || + (rawSegments.length > 2 || + (rawSegments.length === 2 && + (VIETTELSTORE_NON_PRODUCT_PREFIXES.has(firstSegLower) || + (!VIETTELSTORE_PRODUCT_CATEGORY_SEGMENTS.has(firstSegLower) && + !vtsLeafHasPid))) || + (!vtsLeafHasPid && + (VIETTELSTORE_NON_PRODUCT_PREFIXES.has(vtsLeafLower) || + VIETTELSTORE_CATEGORY_SLUG_REGEX.test(vtsLeafLower))))) || (isDomainOrSubdomain(parsedHostLower, 'anphatpc.com.vn') && (ANPHAT_EXTRA_NON_PRODUCT_FIRST_SEGMENTS.has(firstSegLower) || rawSegments.some((s) => /_dm\d+(?:\.html?)?$/i.test(s)))) ) { return ''; } - const rawLeaf = rawSegments[rawSegments.length - 1] || ''; if ( RETAIL_STATIC_ASSET_EXT_REGEX.test(rawLeaf) || /\.(?:c|b)$/i.test(rawLeaf) || @@ -2678,6 +2703,8 @@ export function extractProductKeywordFromUrl(rawUrl?: string | null): string { HACOM_CATEGORY_BRAND_SLUG_REGEX.test(lastSegLower) || CLICKBUY_NON_PRODUCT_SLUG_REGEX.test(lastSegLower) || ANPHAT_DESK_PHONE_SLUG_REGEX.test(lastSegLower) || + (isDomainOrSubdomain(parsedHostLower, 'anphatpc.com.vn') && + isExcludedAnPhatPhoneSlug(lastSegLower)) || /^(?:search|tim-kiem|result|product|products|view)$/.test(lastSegLower) ) { return ''; diff --git a/apps/web/src/server/rate/__tests__/core-rate-architecture.test.ts b/apps/web/src/server/rate/__tests__/core-rate-architecture.test.ts index 19be261eb..66e7ecbe3 100644 --- a/apps/web/src/server/rate/__tests__/core-rate-architecture.test.ts +++ b/apps/web/src/server/rate/__tests__/core-rate-architecture.test.ts @@ -15232,6 +15232,199 @@ async function runCoreArchitectureSuite() { ).platformItemId, null ); + assert.equal( + extractProductKeywordFromUrl( + 'https://viettelstore.vn/dtdd/apple/iphone-16' + ), + '' + ); + assert.ok( + extractProductKeywordFromUrl( + 'https://viettelstore.vn/dien-thoai/iphone-16-256gb-pid339615.html' + ).includes('iphone 16') + ); + assert.equal( + parseEcommerceUrlOrQuery('https://hacom.vn/laptop-asus-vivobook') + .platformItemId, + null + ); + assert.equal( + parseEcommerceUrlOrQuery( + 'https://hacom.vn/laptop-asus-vivobook-x1407ca-ly008w-ltau1066' + ).platformItemId, + 'laptop-asus-vivobook-x1407ca-ly008w-ltau1066' + ); + assert.equal( + parseEcommerceUrlOrQuery( + 'https://www.anphatpc.com.vn/iphone-16-pro-max_id49201.html' + ).platformItemId, + null + ); + assert.equal( + parseEcommerceUrlOrQuery(`https://hacom.vn/${'a'.repeat(121)}`) + .platformItemId, + null, + 'web HACOM slug bound must match extension 120-char bound' + ); + + // Legacy tgdd- input on topzone/dienmayxanh generates canonical tz-/dmx- first + const tzFromLegacy = buildCandidateExternalItemIds({ + externalId: 'tgdd-iphone-16-pro-max', + platform: 'topzone', + }); + assert.ok( + tzFromLegacy.includes('tz-iphone-16-pro-max') && + tzFromLegacy.indexOf('tz-iphone-16-pro-max') < + tzFromLegacy.indexOf('tgdd-iphone-16-pro-max'), + 'canonical tz- candidate must precede legacy tgdd- fallback' + ); + + // Cross-platform guard: a TGDD row (`platform = tgdd`, `tgdd-iphone-16-pro-max`) + // must NEVER match a TopZone URL, and canonical `tz-` beats same-platform `tgdd-` + const { inspectProductOrShopUrl, lookupExtensionProduct: lookupExt1850 } = + await import('../index'); + const origFetch1850 = globalThis.fetch; + try { + const tzMaster = { + id: 'master-tz-1850', + slug: 'apple-iphone-16-pro-max-256gb-tz', + brand: 'Apple', + name: 'Apple iPhone 16 Pro Max 256GB', + model: 'iPhone 16 Pro Max', + status: 'published', + min_price: 29_990_000, + max_price: 30_990_000, + merchant_count: 1, + criteria_scores: {}, + key_specs: {}, + specifications: {}, + spec_provenance: {}, + }; + const tgddWrongMaster = { + ...tzMaster, + id: 'master-tgdd-wrong-1850', + slug: 'wrong-tgdd-cluster-1850', + name: 'Wrong TGDD Cluster', + }; + let scenario: 'cross_platform_only' | 'both_same_platform' = + 'cross_platform_only'; + globalThis.fetch = (async (input: RequestInfo | URL) => { + const reqUrl = decodeURIComponent( + typeof input === 'string' + ? input + : input instanceof URL + ? input.toString() + : input.url + ); + const json1850 = (body: unknown) => + new Response(JSON.stringify(body), { + status: 200, + headers: { 'content-type': 'application/json' }, + }); + if ( + reqUrl.includes('/rest/v1/products') && + reqUrl.includes('platform_item_id=in.') + ) { + const allRows = + scenario === 'cross_platform_only' + ? [ + { + id: 'prod-tgdd-only', + cluster_id: tgddWrongMaster.id, + merchant_id: 'merch-tgdd', + platform: 'tgdd', + platform_item_id: 'tgdd-iphone-16-pro-max', + }, + ] + : [ + { + id: 'prod-tz-legacy', + cluster_id: tgddWrongMaster.id, + merchant_id: 'merch-tz', + platform: 'topzone', + platform_item_id: 'tgdd-iphone-16-pro-max', + }, + { + id: 'prod-tz-canonical', + cluster_id: tzMaster.id, + merchant_id: 'merch-tz', + platform: 'topzone', + platform_item_id: 'tz-iphone-16-pro-max', + }, + ]; + const filtered = reqUrl.includes('platform=eq.topzone') + ? allRows.filter((r) => r.platform === 'topzone') + : allRows; + return json1850(filtered); + } + if (reqUrl.includes(`/rest/v1/master_products`)) { + if (reqUrl.includes(`id=eq.${tzMaster.id}`)) + return json1850(tzMaster); + if (reqUrl.includes(`id=eq.${tgddWrongMaster.id}`)) { + return json1850(tgddWrongMaster); + } + return json1850([]); + } + if (reqUrl.includes('/rest/v1/merchants')) { + return json1850([ + { + id: 'merch-tz', + platform: 'topzone', + platform_shop_id: 'tz-mwg-vn', + name: 'TopZone', + slug: 'topzone', + is_official: true, + metadata: {}, + }, + ]); + } + return json1850([]); + }) as typeof fetch; + + const crossInspected = await inspectProductOrShopUrl( + 'https://www.topzone.vn/iphone/iphone-16-pro-max' + ); + assert.notEqual( + crossInspected.masterProduct?.id, + tgddWrongMaster.id, + 'TopZone URL inspection must never match a TGDD listing row' + ); + const crossExt = await lookupExt1850({ + platform: 'topzone', + url: 'https://www.topzone.vn/iphone/iphone-16-pro-max', + title: 'Unknown Nonmatching Title', + mode: 'pill', + }); + assert.notEqual( + crossExt.masterProduct?.id, + tgddWrongMaster.id, + 'TopZone extension lookup must never match a TGDD listing row' + ); + + scenario = 'both_same_platform'; + const sameInspected = await inspectProductOrShopUrl( + 'https://www.topzone.vn/iphone/iphone-16-pro-max' + ); + assert.equal( + sameInspected.masterProduct?.id, + tzMaster.id, + 'Canonical tz- listing must take precedence over legacy tgdd- fallback on TopZone' + ); + const sameExt = await lookupExt1850({ + platform: 'topzone', + url: 'https://www.topzone.vn/iphone/iphone-16-pro-max', + title: 'Unknown Nonmatching Title', + mode: 'pill', + }); + assert.equal( + sameExt.masterProduct?.id, + tzMaster.id, + 'Extension lookup must prefer canonical tz- listing over legacy tgdd- fallback' + ); + } finally { + globalThis.fetch = origFetch1850; + } + console.log( ' ✅ DOS/Rate#1850 Wave 1-3 12 retail platforms web & API parity passed' ); diff --git a/apps/web/src/server/rate/extension.ts b/apps/web/src/server/rate/extension.ts index 9a98ad634..3b677ea3c 100644 --- a/apps/web/src/server/rate/extension.ts +++ b/apps/web/src/server/rate/extension.ts @@ -1285,9 +1285,40 @@ export function buildCandidateExternalItemIds(params: { 'memoryzone', ]); const prefix = params.platform ? prefixMap[params.platform] : undefined; + const lowerCleanExternalId = cleanExternalId.toLowerCase(); + const isOverlongRetailSlug = (slug: string): boolean => + Boolean(prefix && params.platform !== 'anphatpc' && slug.length > 120); + const barePrefixedExternal = + prefix && + lowerCleanExternalId.startsWith(prefix) && + cleanExternalId.length > prefix.length + ? cleanExternalId.slice(prefix.length) + : cleanExternalId; + if (isOverlongRetailSlug(barePrefixedExternal)) { + return []; + } + + // When a legacy `tgdd-` externalId is queried on `topzone` or `dienmayxanh`, + // enqueue the canonical `tz-` / `dmx-` IDs first so canonical listings win. + if ( + prefix && + (params.platform === 'topzone' || params.platform === 'dienmayxanh') && + /^tgdd-/i.test(cleanExternalId) + ) { + const bareMwg = cleanExternalId.replace(/^tgdd-/i, ''); + if (bareMwg && bareMwg.length <= 120) { + for (const canonicalCandidate of [ + `${prefix}${bareMwg}`, + `${prefix}${bareMwg.toLowerCase()}`, + ]) { + if (isValidExternalEntityId(canonicalCandidate)) { + candidateItemIds.add(canonicalCandidate); + } + } + } + } candidateItemIds.add(cleanExternalId); - const lowerCleanExternalId = cleanExternalId.toLowerCase(); if (isValidExternalEntityId(lowerCleanExternalId)) { candidateItemIds.add(lowerCleanExternalId); } @@ -1311,6 +1342,7 @@ export function buildCandidateExternalItemIds(params: { rawSlugs.push(cleanExternalId.slice(prefix.length)); } for (const slugCandidate of rawSlugs) { + if (isOverlongRetailSlug(slugCandidate)) continue; const lowerSlug = slugCandidate.toLowerCase(); const prefixed = `${prefix}${slugCandidate}`; if (isValidExternalEntityId(prefixed)) { @@ -1340,12 +1372,14 @@ export function buildCandidateExternalItemIds(params: { } if (params.platform === 'topzone' || params.platform === 'dienmayxanh') { const bareMwg = cleanExternalId.replace(/^(?:tz|dmx|tgdd)-/i, ''); - for (const mwgCandidate of [ - `tgdd-${bareMwg}`, - `tgdd-${bareMwg.toLowerCase()}`, - ]) { - if (bareMwg && isValidExternalEntityId(mwgCandidate)) { - candidateItemIds.add(mwgCandidate); + if (bareMwg && bareMwg.length <= 120) { + for (const mwgCandidate of [ + `tgdd-${bareMwg}`, + `tgdd-${bareMwg.toLowerCase()}`, + ]) { + if (isValidExternalEntityId(mwgCandidate)) { + candidateItemIds.add(mwgCandidate); + } } } } @@ -1531,15 +1565,19 @@ export async function lookupExtensionProduct( if (!matchedMaster && candidateItemIds.size > 0) { const client = getRateClient(); if (client) { - const { data: prodRows, error: prodErr } = await client + const orderedCandidates = Array.from(candidateItemIds); + let prodQuery = client .from('products') - .select('cluster_id, platform_item_id') - .in('platform_item_id', Array.from(candidateItemIds)) - .not('cluster_id', 'is', null) - .limit(5); + .select('cluster_id, platform, platform_item_id') + .in('platform_item_id', orderedCandidates) + .not('cluster_id', 'is', null); + if (platform) { + prodQuery = prodQuery.eq('platform', platform); + } + const { data: prodRows, error: prodErr } = await prodQuery.limit(10); if (prodErr) { log.error('extension_lookup_products_failed', { - candidateItemIds: Array.from(candidateItemIds), + candidateItemIds: orderedCandidates, message: prodErr.message, code: prodErr.code, }); @@ -1548,9 +1586,20 @@ export async function lookupExtensionProduct( const matchedProd = ( (prodRows || []) as Array<{ cluster_id: string | null; + platform?: string | null; platform_item_id: string; }> - ).find((r) => Boolean(r.cluster_id)); + ) + .filter( + (r) => + Boolean(r.cluster_id) && + (!platform || !r.platform || r.platform === platform) + ) + .sort((a, b) => { + const ai = orderedCandidates.indexOf(a.platform_item_id); + const bi = orderedCandidates.indexOf(b.platform_item_id); + return (ai === -1 ? 999 : ai) - (bi === -1 ? 999 : bi); + })[0]; if (matchedProd?.cluster_id) { // A draft master has no product page (DOS/Rate#769). The listing is // then known to be that model, so no catalogue guess either. @@ -1591,7 +1640,8 @@ export async function lookupExtensionProduct( candidateItemIds.size > 0 ) { const listingItem = await resolveListingItemContext( - Array.from(candidateItemIds) + Array.from(candidateItemIds), + platform ); if (listingItem === 'no_variant') { // The listing's Item is known but has no page yet: no catalogue guess. diff --git a/apps/web/src/server/rate/item-api.ts b/apps/web/src/server/rate/item-api.ts index 1427d156a..de1db8949 100644 --- a/apps/web/src/server/rate/item-api.ts +++ b/apps/web/src/server/rate/item-api.ts @@ -248,13 +248,25 @@ export function chooseItemVariant( * such listing exists. */ export async function resolveListingItemContext( - platformItemIds: readonly string[] + platformItemIds: readonly string[], + platform?: string | null ): Promise { if (!isItemModelOn() || platformItemIds.length === 0) return null; const client = getRateClient(); if (!client) return null; // `item_id` is not in the generated types until #1150 lands. - const { data, error } = await ( + type ListingItemQuery = { + eq: (col: string, val: string) => ListingItemQuery; + limit: (n: number) => PromiseLike<{ + data: Array<{ + item_id: string | null; + platform?: string | null; + platform_item_id?: string; + }> | null; + error: { message: string; code?: string } | null; + }>; + }; + let query = ( client.from('products') as unknown as { select: (cols: string) => { in: ( @@ -265,26 +277,20 @@ export async function resolveListingItemContext( col: string, value: null ) => { - not: ( - col: string, - op: string, - value: null - ) => { - limit: (n: number) => PromiseLike<{ - data: Array<{ item_id: string | null }> | null; - error: { message: string; code?: string } | null; - }>; - }; + not: (col: string, op: string, value: null) => ListingItemQuery; }; }; }; } ) - .select('item_id, platform_item_id') + .select('item_id, platform, platform_item_id') .in('platform_item_id', platformItemIds) .is('cluster_id', null) - .not('item_id', 'is', null) - .limit(5); + .not('item_id', 'is', null); + if (platform) { + query = query.eq('platform', platform); + } + const { data, error } = await query.limit(10); if (error) { if (error.code && MISSING_SCHEMA_CODES.has(error.code)) { log.warn('item model on but products.item_id is missing', { @@ -295,9 +301,21 @@ export async function resolveListingItemContext( log.error('listing item lookup failed', { message: error.message }); throw new RateDataUnavailableError('products', error); } - const itemId = (data ?? []).find( - (r) => typeof r.item_id === 'string' - )?.item_id; + const itemId = (data ?? []) + .filter( + (r) => + typeof r.item_id === 'string' && + (!platform || !r.platform || r.platform === platform) + ) + .sort((a, b) => { + const ai = a.platform_item_id + ? platformItemIds.indexOf(a.platform_item_id) + : -1; + const bi = b.platform_item_id + ? platformItemIds.indexOf(b.platform_item_id) + : -1; + return (ai === -1 ? 999 : ai) - (bi === -1 ? 999 : bi); + })[0]?.item_id; if (!itemId) return null; return orUnavailable('listing item', async () => { const item = await getItemById(itemId); diff --git a/apps/web/src/server/rate/openapi.ts b/apps/web/src/server/rate/openapi.ts index 77eb7ae46..033975f40 100644 --- a/apps/web/src/server/rate/openapi.ts +++ b/apps/web/src/server/rate/openapi.ts @@ -15,6 +15,7 @@ export interface OpenApiParameter { format?: string; enum?: string[]; default?: string | number | boolean; + maxLength?: number; }; } @@ -1172,7 +1173,7 @@ function buildBaseRateOpenApiSpec( name: 'externalId', in: 'query', description: 'Platform item ID or shopId_itemId', - schema: { type: 'string' }, + schema: { type: 'string', maxLength: 128 }, }, { name: 'shopId', @@ -2146,7 +2147,7 @@ function buildBaseRateOpenApiSpec( externalItemId: { type: 'string', minLength: 1, - maxLength: 120, + maxLength: 128, example: '29512841920', description: 'Optional; derived from `url` when omitted.', },