diff --git a/apps/web/locales/cs.json b/apps/web/locales/cs.json index 6ad69152..9899e8c8 100644 --- a/apps/web/locales/cs.json +++ b/apps/web/locales/cs.json @@ -822,7 +822,16 @@ "radarBadgeSpread": "📊 +{pct} % rozdíl mezi e-shopy", "radarNoGenuine": "V této kategorii nejsou žádné nabídky pod tržním mediánem.", "radarNoTraps": "V této kategorii nebyly zjištěny žádné navýšené původní ceny.", - "showMoreDeals": "Zobrazit další nabídky ({count, plural, one {zbývá #} few {zbývají #} other {zbývá #}})" + "showMoreDeals": "Zobrazit další nabídky ({count, plural, one {zbývá #} few {zbývají #} other {zbývá #}})", + "campaignFilterLabel": "Filtr sezónních slev:", + "campaignAll": "Všechna zařízení", + "campaignGenuineDrops": "Skutečné sezónní slevy ({count})", + "campaignInflatedTraps": "Varování: navýšené ceny před slevou ({count})", + "campaignEmptyGenuine": "Žádné zařízení se skutečnou slevou pod tržním mediánem neodpovídá zvoleným filtrům.", + "campaignEmptyTraps": "Ve zvolených filtrech nebyly zjištěny žádné uměle navýšené přeškrtnuté ceny.", + "campaignResetBtn": "Zobrazit všechna zařízení", + "campaignCardTrapNote": "Varování na {platform}: přeškrtnutá cena {claimed} (+{pct} % nad mediánem) - nakupte v nejlevnějším ověřeném obchodě", + "campaignCardGenuineNote": "Skutečná sleva na {platform}: úspora {savings} (-{pct} % oproti mediánu obchodů)" }, "inspect": { "metaTitle": "Kontrola odkazu na produkt a falešných slev | Rate.vn", @@ -903,7 +912,9 @@ "errInspectFailed": "Tento odkaz se nepodařilo zkontrolovat.", "errNetwork": "Chyba sítě, zkuste to znovu.", "loading": "Načítání...", - "reviewRiskNoData": "nedostatek dat" + "reviewRiskNoData": "nedostatek dat", + "omnibusScopeListing": "Kontrola vybrané nabídky: {merchant} ({platform})", + "omnibusScopeProduct": "Kontrola nejnižší ověřené ceny skladem napříč obchody" }, "merchants": { "dirMetaTitle": "Důvěryhodnost prodejců | Rate.vn", @@ -2074,7 +2085,32 @@ "explainSuspicious": "Inzerovaná sleva (-{claimed} %) je výrazně vyšší než skutečná sleva (-{real} %) podle historie cen ({median}).", "explainGenuine": "Aktuální cena je o {pct} % nižší než historický medián ({median}).", "explainHistoricLow": "Nejnižší zaznamenaná cena ({current}, maximum {max}).", - "explainNormal": "Aktuální cena ({current}) odpovídá historickému mediánu ({median})." + "explainNormal": "Aktuální cena ({current}) odpovídá historickému mediánu ({median}).", + "oTitle": "Kontrola 30d minima (EU) a 90d cyklus", + "oOk": "30denní minimum EU", + "oPart": "Sledované minimum ({days} d)", + "oGap": "Výpadek v 30d záznamu", + "oPend": "Sběr historie (pod 30 dní)", + "oFlr": "Zaznamenané minimum", + "oCur": "Prodejní a přeškrtnutá cena", + "oClaim": "-{pct} % z {original}", + "oNoOrig": "Bez přeškrtnuté ceny", + "oMarkup": "Přeškrtnutá o {markup} (+{pct} %) nad minimem", + "oAlign": "Odpovídá předchozí historii", + "oDrop": "Reálný pokles: -{pct} % (-{amount})", + "oFake": "Falešná sleva: +{amount} (+{pct} %) vs 30d min", + "oUp": "Nad minimem: +{pct} % (+{amount})", + "oFlat": "Shodné s minimem (0 %)", + "oNeed": "Málo dnů měření", + "oNoteP": "{days}/30 d: 30d EU nepotvrzeno", + "oNoteG": "Výpadek v 30d okně: EU nevydáno", + "oCyc": "90d cyklus (koupit, či počkat)", + "oBuy": "90d minimum (nejnižších {pct} %) - koupit", + "oFair": "Běžné pásmo ({pct} % 90d cyklu)", + "oWait": "O {gap} nad 90d minimem - počkat", + "oRng": "Rozpětí 90 d: {low} - {high}", + "oCycP": "Sběr 90d cyklu", + "oCycN": "{points}/5 dnů za {days} d (min. 14 d)" }, "analyzerCopy": { "reasonAuthentic": "Podrobná, platná recenze od skutečného uživatele.", diff --git a/apps/web/locales/en.json b/apps/web/locales/en.json index de00af66..9a6e5107 100644 --- a/apps/web/locales/en.json +++ b/apps/web/locales/en.json @@ -822,7 +822,16 @@ "radarBadgeSpread": "📊 +{pct}% cross-platform spread", "radarNoGenuine": "No offers below the market median in this category.", "radarNoTraps": "No inflated list prices detected in this category.", - "showMoreDeals": "Show more deals ({count} left)" + "showMoreDeals": "Show more deals ({count} left)", + "campaignFilterLabel": "Sale campaign filter:", + "campaignAll": "All devices", + "campaignGenuineDrops": "Top genuine sale drops ({count})", + "campaignInflatedTraps": "Pre-sale inflated strikethrough alerts ({count})", + "campaignEmptyGenuine": "No devices with verified below-median sale drops match your current filters.", + "campaignEmptyTraps": "No pre-sale inflated strikethrough listings detected in your current filters.", + "campaignResetBtn": "Show all devices", + "campaignCardTrapNote": "Alert on {platform}: claimed list price {claimed} (+{pct}% vs median) - compare stores for the lowest verified price", + "campaignCardGenuineNote": "Verified drop on {platform}: save {savings} (-{pct}% vs cross-store median)" }, "inspect": { "metaTitle": "Check a product link and fake discounts | Rate.vn", @@ -903,7 +912,9 @@ "errInspectFailed": "Could not check this link.", "errNetwork": "Network error, please try again.", "loading": "Loading...", - "reviewRiskNoData": "not enough data" + "reviewRiskNoData": "not enough data", + "omnibusScopeListing": "Checking matched listing: {merchant} ({platform})", + "omnibusScopeProduct": "Checking lowest verified in-stock price across tracked stores" }, "merchants": { "dirMetaTitle": "Seller trust directory | Rate.vn", @@ -2074,7 +2085,32 @@ "explainSuspicious": "The advertised discount (-{claimed}%) is well above the real discount (-{real}%) against the price history ({median}).", "explainGenuine": "The current price is {pct}% below the historical median ({median}).", "explainHistoricLow": "At the lowest price recorded ({current}, against a high of {max}).", - "explainNormal": "The current price ({current}) matches the historical median ({median})." + "explainNormal": "The current price ({current}) matches the historical median ({median}).", + "oTitle": "30-day EU floor check and 90-day cycle", + "oOk": "30-day EU prior floor", + "oPart": "{days}-day observed floor", + "oGap": "Gapped log (30d incomplete)", + "oPend": "Collecting history (under 30d)", + "oFlr": "Observed prior floor", + "oCur": "Selling vs list price", + "oClaim": "-{pct}% from {original}", + "oNoOrig": "No strikethrough price", + "oMarkup": "List price +{markup} (+{pct}%) above floor", + "oAlign": "List price matches prior history", + "oDrop": "Real drop: -{pct}% (-{amount})", + "oFake": "Fake sale: +{amount} (+{pct}%) vs 30d floor", + "oUp": "Above floor: +{pct}% (+{amount})", + "oFlat": "Matches prior floor (0%)", + "oNeed": "Need multi-day history", + "oNoteP": "{days}/30d observed: EU 30d uncertified", + "oNoteG": "Gap in 30d window: EU status withheld", + "oCyc": "90-day cycle (buy or wait)", + "oBuy": "90d floor (lowest {pct}%) - buy now", + "oFair": "Fair range ({pct}% of 90d cycle)", + "oWait": "Above 90d low by +{gap} - wait", + "oRng": "90d range: {low} - {high}", + "oCycP": "Collecting 90-day cycle", + "oCycN": "{points}/5 days across {days}d (14d min)" }, "analyzerCopy": { "reasonAuthentic": "Detailed, valid review from a real user.", diff --git a/apps/web/locales/vi.json b/apps/web/locales/vi.json index e16f32ef..8a60f41c 100644 --- a/apps/web/locales/vi.json +++ b/apps/web/locales/vi.json @@ -822,7 +822,16 @@ "radarBadgeSpread": "📊 Lệch giá +{pct}% đa sàn", "radarNoGenuine": "Chưa có nơi bán nào có giá thấp hơn trung vị thị trường trong danh mục này.", "radarNoTraps": "Chưa phát hiện giá gốc bị nâng khống trong danh mục này.", - "showMoreDeals": "Xem thêm deal (còn {count})" + "showMoreDeals": "Xem thêm deal (còn {count})", + "campaignFilterLabel": "Chiến dịch mùa sale:", + "campaignAll": "Tất cả thiết bị", + "campaignGenuineDrops": "Top giảm thật đợt sale ({count})", + "campaignInflatedTraps": "Cảnh báo tăng giá đệm trước sale ({count})", + "campaignEmptyGenuine": "Chưa có thiết bị nào đang giảm thực chất dưới trung vị thị trường trong bộ lọc hiện tại.", + "campaignEmptyTraps": "Không phát hiện tin bán nâng khống giá gạch ngang trước sale trong bộ lọc hiện tại.", + "campaignResetBtn": "Xem lại tất cả thiết bị", + "campaignCardTrapNote": "Cảnh báo trên {platform}: kê giá gạch ngang {claimed} (+{pct}% so trung vị) - hãy đối chiếu để mua ở nơi bán thấp nhất", + "campaignCardGenuineNote": "Giảm thật tại {platform}: tiết kiệm {savings} (-{pct}% so trung vị các sàn)" }, "inspect": { "metaTitle": "Kiểm tra link sản phẩm và giảm giá ảo | Rate.vn", @@ -903,7 +912,9 @@ "errInspectFailed": "Không kiểm tra được link này.", "errNetwork": "Lỗi mạng, vui lòng thử lại.", "loading": "Đang tải...", - "reviewRiskNoData": "chưa đủ dữ liệu" + "reviewRiskNoData": "chưa đủ dữ liệu", + "omnibusScopeListing": "Đối chiếu trực tiếp tin bán: {merchant} ({platform})", + "omnibusScopeProduct": "Đối chiếu mức giá thấp nhất đang còn hàng của mẫu máy này" }, "merchants": { "dirMetaTitle": "Độ tin cậy gian hàng trên các sàn | Rate.vn", @@ -2074,7 +2085,32 @@ "explainSuspicious": "Mức giảm công bố (-{claimed}%) cao hơn đáng kể so với mức giảm thực tế (-{real}%) khi đối chiếu lịch sử giá ({median}).", "explainGenuine": "Giá hiện tại thấp hơn {pct}% so với mức trung vị lịch sử ({median}).", "explainHistoricLow": "Đang ở vùng giá thấp nhất ghi nhận được ({current} so với đỉnh {max}).", - "explainNormal": "Giá bán hiện tại ({current}) khớp với mức trung vị lịch sử ({median})." + "explainNormal": "Giá bán hiện tại ({current}) khớp với mức trung vị lịch sử ({median}).", + "oTitle": "Đối chiếu đáy giá 30 ngày (EU) và chu kỳ 90 ngày", + "oOk": "Đáy 30 ngày chuẩn EU", + "oPart": "Đáy quan sát {days} ngày", + "oGap": "Ngắt quãng (chưa đủ 30 ngày)", + "oPend": "Đang tích lũy (dưới 30 ngày)", + "oFlr": "Đáy quan sát trước đó", + "oCur": "Giá bán và giá gạch ngang", + "oClaim": "-{pct}% từ {original}", + "oNoOrig": "Không treo giá gạch ngang", + "oMarkup": "Giá gốc cao hơn đáy +{markup} (+{pct}%)", + "oAlign": "Giá gốc khớp lịch sử trước đó", + "oDrop": "Giảm thật: -{pct}% (-{amount})", + "oFake": "Giảm ảo: so với đáy 30d +{amount} (+{pct}%)", + "oUp": "Cao hơn đáy: +{pct}% (+{amount})", + "oFlat": "Bằng đáy trước đó (0%)", + "oNeed": "Chưa đủ ngày đo trước đó", + "oNoteP": "Mới có {days}/30 ngày: chưa chứng nhận EU", + "oNoteG": "Ngắt quãng 30 ngày: chưa kết luận EU", + "oCyc": "Chu kỳ 90 ngày (mua hay chờ)", + "oBuy": "Đáy 90d (nhóm {pct}% thấp nhất) - mua ngay", + "oFair": "Giá hợp lý (mức {pct}% chu kỳ 90d)", + "oWait": "Cao hơn đáy 90d +{gap} - chờ giảm", + "oRng": "Biên độ 90d: {low} - {high}", + "oCycP": "Đang tích lũy chu kỳ 90d", + "oCycN": "{points}/5 ngày đo trong {days}d (cần 14d)" }, "analyzerCopy": { "reasonAuthentic": "Đánh giá chi tiết, hợp lệ từ người dùng thực tế.", diff --git a/apps/web/src/components/deals/DealFinderWorkspace.tsx b/apps/web/src/components/deals/DealFinderWorkspace.tsx index 1f94c4fe..46c432da 100644 --- a/apps/web/src/components/deals/DealFinderWorkspace.tsx +++ b/apps/web/src/components/deals/DealFinderWorkspace.tsx @@ -35,6 +35,11 @@ import { } from '@/lib/deal-radar'; import RadarBadge from '@/components/radar/RadarBadge'; import { useDealRadarIndex } from '@/components/radar/use-deal-radar'; +import { + countSeasonalSaleCampaignDeals, + matchesSeasonalSaleFilter, + type SeasonalSaleFilterMode, +} from '@/lib/omnibus-price-audit'; import { escapeCsvCell } from '@/lib/csv-safe'; import { formatDecimal, @@ -569,10 +574,13 @@ export default function DealFinderWorkspace({ const locale = useLocale(); const categoryLabelId = useId(); const personaLabelId = useId(); + const campaignLabelId = useId(); const [categoryFilter, setCategoryFilter] = useState< CanonicalCategorySlug | 'all' >(initialCategory); const [chosenPersona, setPersona] = useState('value_hunter'); + const [campaignFilter, setCampaignFilter] = + useState('all'); const [maxBudgetVnd, setMaxBudgetVnd] = useState(65_000_000); const [searchQuery, setSearchQuery] = useState(''); const [copiedMarkdown, setCopiedMarkdown] = useState(false); @@ -588,7 +596,7 @@ export default function DealFinderWorkspace({ ? chosenPersona : 'default'; // Paging restarts whenever a filter changes the ranking. - const filterKey = `${categoryFilter}|${persona}|${maxBudgetVnd}|${searchQuery}`; + const filterKey = `${categoryFilter}|${persona}|${campaignFilter}|${maxBudgetVnd}|${searchQuery}`; const [paging, setPaging] = useState({ key: filterKey, count: DEALS_PAGE_SIZE, @@ -739,7 +747,7 @@ export default function DealFinderWorkspace({ URL.revokeObjectURL(url); }; - const rankedDeals = useMemo( + const baseRankedDeals = useMemo( () => rankProductsForDealFinder(products, { categoryFilter, @@ -750,6 +758,29 @@ export default function DealFinderWorkspace({ [products, categoryFilter, persona, maxBudgetVnd, searchQuery] ); + const seasonalCampaignCounts = useMemo( + () => + countSeasonalSaleCampaignDeals(baseRankedDeals, (slug) => + getRadarSignal(radarIndex, slug) + ), + [baseRankedDeals, radarIndex] + ); + + const rankedDeals = useMemo(() => { + if (campaignFilter === 'all') return baseRankedDeals; + return baseRankedDeals + .filter((d) => + matchesSeasonalSaleFilter( + getRadarSignal(radarIndex, d.slug), + campaignFilter + ) + ) + .map((d, idx) => ({ + ...d, + rank: idx + 1, + })); + }, [baseRankedDeals, campaignFilter, radarIndex]); + const handleCopyDealsMarkdown = async () => { if (typeof window === 'undefined' || rankedDeals.length === 0) return; try { @@ -951,6 +982,56 @@ export default function DealFinderWorkspace({ )} + {/* Seasonal Sale Campaign Filter Chips (#1863) */} +
+ + {t('campaignFilterLabel')} + + {( + [ + { + key: 'all', + label: t('campaignAll'), + }, + { + key: 'genuine_sale_drops', + label: t('campaignGenuineDrops', { + count: seasonalCampaignCounts.genuineSaleCount, + }), + }, + { + key: 'inflated_presale_warnings', + label: t('campaignInflatedTraps', { + count: seasonalCampaignCounts.inflatedWarningCount, + }), + }, + ] as const + ).map((chip) => ( + + ))} +
+ {/* Budget Slider & Search */}
@@ -1035,133 +1116,152 @@ export default function DealFinderWorkspace({
-
-

-

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

    +

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

    {t('radarNoGenuine')}

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

{t('radarNoGenuine')}

+ )} +
+ )} -
-

-

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

    +

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

    {t('radarNoTraps')}

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

{t('radarNoTraps')}

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

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

) : ( <>
- {rankedDeals.slice(0, visibleCount).map((deal) => ( -
-
-
-
-
- - {t('rankDealBadge', { rank: deal.rank })} - - {deal.brand} - - - {deal.expertScore10 != null - ? `Lab ${formatDecimal(deal.expertScore10, locale, 1)}/10` - : t('labNoScore')} - - + {rankedDeals.slice(0, visibleCount).map((deal) => { + const dealSignal = getRadarSignal(radarIndex, deal.slug); + const trapOrig = dealSignal.fakeSaleTrap + ? resolveClaimedOriginalPriceVnd( + dealSignal.fakeSaleTrap.priceOriginal, + dealSignal.fakeSaleTrap.priceCurrent + ) + : null; + const genuineSavingsVnd = dealSignal.genuineDeal + ? sanitizeDealRadarPriceVnd( + dealSignal.genuineDeal.savingsVsMedianVnd + ) + : null; + return ( +
+
+
+
+
+ + {t('rankDealBadge', { rank: deal.rank })} + + {deal.brand} + + + {deal.expertScore10 != null + ? `Lab ${formatDecimal(deal.expertScore10, locale, 1)}/10` + : t('labNoScore')} + + +
+ {deal.spreadSavingsVnd > 0 && ( + + {t('spreadSavingsBadge', { + amount: formatNumber( + deal.spreadSavingsVnd, + locale + ), + })} + + )}
- {deal.spreadSavingsVnd > 0 && ( - - {t('spreadSavingsBadge', { - amount: formatNumber(deal.spreadSavingsVnd, locale), - })} - - )} -
-
- {deal.name} -
- - {deal.name} - -
- {formatPriceVnd(deal.minPrice, locale)}{' '} - {deal.costPerPointVnd > 0 && ( - - {t('costPerPointSub', { - cost: formatNumber( - deal.costPerPointVnd, - locale - ), - })} - - )} +
+ {deal.name} +
+ + {deal.name} + +
+ {formatPriceVnd(deal.minPrice, locale)}{' '} + {deal.costPerPointVnd > 0 && ( + + {t('costPerPointSub', { + cost: formatNumber( + deal.costPerPointVnd, + locale + ), + })} + + )} +
+ + {campaignFilter === 'inflated_presale_warnings' && + dealSignal.fakeSaleTrap && + trapOrig != null && ( +
+ {t('campaignCardTrapNote', { + platform: + dealSignal.fakeSaleTrap.platform.toUpperCase(), + claimed: formatPriceVnd(trapOrig, locale), + pct: formatPlainNumber( + dealSignal.fakeSaleTrap.fakeMarkupPct, + locale + ), + })} +
+ )} + + {campaignFilter === 'genuine_sale_drops' && + dealSignal.genuineDeal && + genuineSavingsVnd != null && ( +
+ {t('campaignCardGenuineNote', { + platform: + dealSignal.genuineDeal.platform.toUpperCase(), + savings: formatPriceVnd( + genuineSavingsVnd, + locale + ), + pct: formatPlainNumber( + dealSignal.genuineDeal.savingsVsMedianPct, + locale + ), + })} +
+ )}
-
-
- - - {t('audit10PlatformsLink')} - +
+ + + {t('audit10PlatformsLink')} + +
-
- ))} + ); + })}
{rankedDeals.length > visibleCount && (
diff --git a/apps/web/src/components/inspect/DeepInspectWorkspace.tsx b/apps/web/src/components/inspect/DeepInspectWorkspace.tsx index 7f2fa602..2c48dd4a 100644 --- a/apps/web/src/components/inspect/DeepInspectWorkspace.tsx +++ b/apps/web/src/components/inspect/DeepInspectWorkspace.tsx @@ -12,12 +12,19 @@ import { discountVerdictCopy, type VerdictTranslator, } from '@/lib/discount-verdict-copy'; +import { + evaluateOmnibusPriceAudit, + formatOmnibusAuditCopy, + type OmnibusPriceAuditResult, + type OmnibusVerdictTranslator, +} from '@/lib/omnibus-price-audit'; import { formatScoreFixed, roundScore } from '@/lib/rating-display'; import AnalyzerText from '@/components/reviews/AnalyzerText'; import { useDetailsDismiss } from '@/components/elementary/use-details-dismiss'; import { Link, useRouter } from '@/lib/navigation'; import { MAX_VALID_VND_PRICE, + getMasterProductCategorySlug, getMasterProductHref, resolveCompareBatteryMah, resolveCompareEffectiveUserRating, @@ -66,9 +73,11 @@ import { SAMPLE_AUDIT_URLS } from '@/lib/inspect-samples'; import { IMPLAUSIBLY_LOW_RATIO, MINIMUM_EARBUDS_PRICE_FLOOR_VND, + hasImplausiblyLowOfferId, implausiblyLowIndexes, isImplausiblyLowPrice, isOfferImplausiblyLowAgainstInStock, + minimumListingPriceVnd, normalizeOfferId, plausibleMinPrice, plausibleOffers, @@ -1318,6 +1327,174 @@ export default function DeepInspectWorkspace({ ? resolveCompareExpertRating10(master) : null; + const inspectOmnibusState = useMemo<{ + audit: OmnibusPriceAuditResult; + listingScoped: boolean; + } | null>(() => { + if ( + offerImplausiblyLow || + matchedOfferUnavailable || + verdictPrices.currentPriceVnd <= 0 || + !priceHistory || + !Array.isArray(priceHistory.points) || + priceHistory.points.length === 0 + ) { + return null; + } + + const minValidPriceVnd = + master && getMasterProductCategorySlug(master) === 'earbuds' + ? MINIMUM_EARBUDS_PRICE_FLOOR_VND + : minimumListingPriceVnd([ + master?.name ?? '', + matchedOffer?.title ?? '', + queryInput, + ]); + + const unavailableAnchorIds = new Set(); + if (Array.isArray(result?.allOffers)) { + for (const off of result.allOffers) { + if (off && isOfferUnavailable(off)) { + unavailableAnchorIds.add(off.id); + const cId = normalizeOfferId(off.id); + if (cId) unavailableAnchorIds.add(cId); + } + } + } + + let latestMs = 0; + for (const pt of priceHistory.points) { + if (pt.source === 'live_listing') continue; + if (hasImplausiblyLowOfferId(implausibleOfferIds, pt.product_id)) { + continue; + } + if ( + unavailableAnchorIds.has(pt.product_id) || + unavailableAnchorIds.has(normalizeOfferId(pt.product_id)) + ) { + continue; + } + const ms = new Date(pt.recorded_at).getTime(); + if (Number.isFinite(ms) && ms > latestMs) latestMs = ms; + } + const anchorMs = latestMs > 0 ? latestMs : null; + + if (matchedOffer?.id) { + const targetCanon = normalizeOfferId(matchedOffer.id); + const offerPts = priceHistory.points.filter((pt) => { + if (pt.source === 'live_listing') return false; + if (pt.product_id === matchedOffer.id) return true; + return Boolean( + targetCanon && normalizeOfferId(pt.product_id) === targetCanon + ); + }); + // Evaluate the 90-day market cycle AT the matched listing's own selling + // price (`verdictPrices.currentPriceVnd`) so an overpriced seller never + // receives a green "Buy now" badge from a cheaper competitor's floor. + const marketCycleForListing = evaluateOmnibusPriceAudit({ + points: priceHistory.points, + currentPriceVnd: verdictPrices.currentPriceVnd, + claimedOriginalPriceVnd: + verdictPrices.claimedOriginalVnd > 0 + ? verdictPrices.claimedOriginalVnd + : null, + currentInStockPriceVnd: verdictPrices.currentPriceVnd, + mode: 'market', + referenceOffers: result?.allOffers, + implausibleOfferIds, + minValidPriceVnd, + referenceTimestampMs: anchorMs, + }); + // Always evaluate the 30-day EU prior floor strictly on `matchedOffer`'s + // own history (`offerPts`, even if < 2 points -> `insufficient_history`), + // never accusing a newly tracked shop using another shop's 30-day floor. + const offerAudit = evaluateOmnibusPriceAudit({ + points: offerPts, + currentPriceVnd: verdictPrices.currentPriceVnd, + claimedOriginalPriceVnd: + verdictPrices.claimedOriginalVnd > 0 + ? verdictPrices.claimedOriginalVnd + : null, + currentInStockPriceVnd: verdictPrices.currentPriceVnd, + mode: 'offer', + referenceOffers: result?.allOffers, + implausibleOfferIds, + minValidPriceVnd, + referenceTimestampMs: anchorMs, + }); + return { + audit: { + ...offerAudit, + cycle90d: + marketCycleForListing.cycle90d.signal !== 'insufficient_data' + ? marketCycleForListing.cycle90d + : offerAudit.cycle90d, + }, + listingScoped: true, + }; + } + + const inStockFloorVnd = + safeMasterMinPriceVnd > 0 + ? safeMasterMinPriceVnd + : verdictPrices.currentPriceVnd; + let bestInStockOrig: number | null = null; + for (const off of inStockOffers) { + if (isInspectOfferBait(off, implausibleOfferIds, plausibilityOffers)) { + continue; + } + if (sanitizeInspectPriceVnd(off.price_current) !== inStockFloorVnd) { + continue; + } + const orig = sanitizeInspectOriginalPriceVnd( + off.price_original, + inStockFloorVnd + ); + if (orig > 0 && (bestInStockOrig == null || orig > bestInStockOrig)) { + bestInStockOrig = orig; + } + } + + const marketAudit = evaluateOmnibusPriceAudit({ + points: priceHistory.points, + currentPriceVnd: inStockFloorVnd, + claimedOriginalPriceVnd: bestInStockOrig, + currentInStockPriceVnd: + safeMasterMinPriceVnd > 0 ? safeMasterMinPriceVnd : null, + mode: 'market', + referenceOffers: result?.allOffers, + implausibleOfferIds, + minValidPriceVnd, + referenceTimestampMs: anchorMs, + }); + + return { + audit: marketAudit, + listingScoped: false, + }; + }, [ + implausibleOfferIds, + inStockOffers, + master, + matchedOffer, + matchedOfferUnavailable, + offerImplausiblyLow, + plausibilityOffers, + priceHistory, + queryInput, + result?.allOffers, + safeMasterMinPriceVnd, + verdictPrices.claimedOriginalVnd, + verdictPrices.currentPriceVnd, + ]); + + const tOmnibus: OmnibusVerdictTranslator = (key, values) => + tVerdict(key, values); + const inspectOmnibusCopy = + inspectOmnibusState && inspectOmnibusState.audit.currentPriceVnd != null + ? formatOmnibusAuditCopy(inspectOmnibusState.audit, tOmnibus, locale) + : null; + const handleCopyAuditMarkdown = async () => { if (typeof window === 'undefined') return; try { @@ -1755,6 +1932,156 @@ export default function DeepInspectWorkspace({
)} + {/* 3-Column EU Omnibus 30-Day Floor Audit & 90-Day Cycle (#1863) */} + {inspectOmnibusCopy && inspectOmnibusState && ( +
+
+
+

+

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

+

+ + {omnibusCopy.statusBadgeText} + +
+ +
+
+
+
+ {omnibusCopy.colCurrentTitle} +
+
+ + {omnibusCopy.currentPriceText} + + {omnibusCopy.claimedBadgeText && ( + + {omnibusCopy.claimedBadgeText} + + )} +
+
+ {omnibusCopy.currentSubText} +
+
+
+ +
+
+
+ {omnibusCopy.colFloorTitle} +
+
+ {omnibusCopy.floorPriceText} +
+
+ {omnibusCopy.floorDeltaText} +
+ {omnibusCopy.floorDisclaimerText && ( +
+ {omnibusCopy.floorDisclaimerText} +
+ )} +
+
+ +
+
+
+ {omnibusCopy.colCycleTitle} +
+
+ {omnibusCopy.cycleValueText} +
+
+ {omnibusCopy.cycleSubText} +
+
+
+
+
+ )} + {/* Controls: Merchant Filter & Time Range. Single-select groups that expose the pressed choice, not only its colour (DOS/Rate#1069). */}
@@ -1276,6 +1645,33 @@ export default function PriceHistorySection({ {formatVnd(oa.historical_max_price, locale)} + {(() => { + const offerOmnibus = omnibusByOffer.get(oa.product_id); + if ( + !offerOmnibus || + offerOmnibus.priorFloorPriceVnd == null || + (offerOmnibus.windowStatus !== + 'omnibus_30d_certified' && + offerOmnibus.windowStatus !== 'partial_window') + ) { + return null; + } + const floorFormatted = formatVnd( + offerOmnibus.priorFloorPriceVnd, + locale + ); + return ( + + {offerOmnibus.windowStatus === 'omnibus_30d_certified' + ? tOmnibus('oOk') + : tOmnibus('oPart', { + days: offerOmnibus.windowDaysUsed, + })} + {': '} + {floorFormatted} + + ); + })()}

diff --git a/apps/web/src/lib/__tests__/discount-verdict-copy.test.ts b/apps/web/src/lib/__tests__/discount-verdict-copy.test.ts index 7f618956..e8040eae 100644 --- a/apps/web/src/lib/__tests__/discount-verdict-copy.test.ts +++ b/apps/web/src/lib/__tests__/discount-verdict-copy.test.ts @@ -5,6 +5,12 @@ import { discountVerdictCopy, type VerdictTranslator, } from '../discount-verdict-copy'; +import { + evaluateOmnibusPriceAudit, + formatOmnibusAuditCopy, + type OmnibusVerdictTranslator, +} from '../omnibus-price-audit'; +import { NBSP } from '../locale-format'; import type { OfferDiscountAnalysis } from '../rate-api'; const LOCALES = ['vi', 'en', 'cs'] as const; @@ -141,6 +147,246 @@ function main() { ); assert.equal(fallbackNull.label, messages.en.labelNormal); + // ========================================================================= + // EU Omnibus 30-Day Price-Floor Audit & Locale Parity (#1863) + // ========================================================================= + const DAY_MS = 86_400_000; + const ANCHOR_MS = Date.UTC(2026, 10, 22, 12, 0, 0); + const isoDaysAgo = (days: number) => + new Date(ANCHOR_MS - days * DAY_MS).toISOString(); + + const omnibusTranslator = ( + dict: Record + ): OmnibusVerdictTranslator => { + return (key, values = {}) => { + const msg = dict[key]; + assert.ok(msg, `missing priceVerdict.${key}`); + return msg.replace(/\{(\w+)\}/g, (_, name: string) => { + assert.ok(name in values, `${key} missing {${name}}`); + return String(values[name]); + }); + }; + }; + + // 1. Key parity & zero em/en-dash check across deals, inspect, priceVerdict + const fullCatalogs = Object.fromEntries( + LOCALES.map((loc) => [ + loc, + JSON.parse( + readFileSync( + join(__dirname, '..', '..', '..', 'locales', `${loc}.json`), + 'utf8' + ) + ) as Record>, + ]) + ) as Record<(typeof LOCALES)[number], Record>>; + + for (const ns of ['deals', 'inspect', 'priceVerdict'] as const) { + const viKeys = Object.keys(fullCatalogs.vi[ns]!).sort(); + for (const loc of LOCALES) { + assert.deepEqual( + Object.keys(fullCatalogs[loc][ns]!).sort(), + viKeys, + `${loc}.${ns} key parity` + ); + for (const [k, v] of Object.entries(fullCatalogs[loc][ns]!)) { + assert.ok( + !/[\u2013\u2014]/.test(String(v)), + `${loc}.${ns}.${k} must not contain en-dash or em-dash` + ); + } + } + } + + // 2. Proposal real flash-sale scenario: 27.49M prior 30d floor -> 27.19M today + // while seller claims -22.3% from 34.99M. + const flashSaleAudit = evaluateOmnibusPriceAudit({ + points: [ + { product_id: 'o1', price: 27_490_000, recorded_at: isoDaysAgo(35) }, + { product_id: 'o1', price: 27_990_000, recorded_at: isoDaysAgo(24) }, + { product_id: 'o1', price: 27_490_000, recorded_at: isoDaysAgo(14) }, + { product_id: 'o1', price: 27_690_000, recorded_at: isoDaysAgo(6) }, + { product_id: 'o1', price: 27_190_000, recorded_at: isoDaysAgo(1) }, + { product_id: 'o1', price: 27_190_000, recorded_at: isoDaysAgo(0) }, + ], + currentPriceVnd: 27_190_000, + claimedOriginalPriceVnd: 34_990_000, + referenceTimestampMs: ANCHOR_MS, + }); + assert.equal(flashSaleAudit.isOmnibusCertified, true); + assert.equal(flashSaleAudit.windowStatus, 'omnibus_30d_certified'); + assert.equal(flashSaleAudit.priorFloorPriceVnd, 27_490_000); + assert.equal(flashSaleAudit.deltaVsPriorFloorVnd, -300_000); + assert.equal(flashSaleAudit.deltaVsPriorFloorPct, -1.1); + assert.equal(flashSaleAudit.verdict, 'exaggerated_strikethrough'); + + for (const loc of LOCALES) { + const copy = formatOmnibusAuditCopy( + flashSaleAudit, + omnibusTranslator(messages[loc]), + loc + ); + assert.equal(copy.statusBadgeTone, 'good'); + assert.equal(copy.floorDeltaTone, 'good'); + if (loc === 'cs') { + assert.ok(copy.floorDeltaText.includes(`-1,1${NBSP}%`)); + assert.ok(copy.floorDeltaText.includes(`300${NBSP}000${NBSP}₫`)); + } else { + assert.ok(copy.floorDeltaText.includes('-1.1%')); + assert.ok(copy.floorDeltaText.includes('300.000 ₫')); + } + } + + // 3. Hlidac shopu pre-sale bump / fake strikethrough trap: + // Sold at 24.99M 25 days ago, bumped to 34.99M 10 days ago, now 25.19M. + const preSaleBumpAudit = evaluateOmnibusPriceAudit({ + points: [ + { product_id: 'o1', price: 24_990_000, recorded_at: isoDaysAgo(32) }, + { product_id: 'o1', price: 24_990_000, recorded_at: isoDaysAgo(22) }, + { product_id: 'o1', price: 34_990_000, recorded_at: isoDaysAgo(10) }, + { product_id: 'o1', price: 25_190_000, recorded_at: isoDaysAgo(0) }, + ], + currentPriceVnd: 25_190_000, + claimedOriginalPriceVnd: 34_990_000, + referenceTimestampMs: ANCHOR_MS, + }); + assert.equal(preSaleBumpAudit.isOmnibusCertified, true); + assert.equal(preSaleBumpAudit.priorFloorPriceVnd, 24_990_000); + assert.equal(preSaleBumpAudit.deltaVsPriorFloorVnd, 200_000); + assert.equal(preSaleBumpAudit.deltaVsPriorFloorPct, 0.8); + assert.equal(preSaleBumpAudit.verdict, 'fake_strikethrough_above_floor'); + const bumpEnCopy = formatOmnibusAuditCopy( + preSaleBumpAudit, + omnibusTranslator(messages.en), + 'en' + ); + assert.equal(bumpEnCopy.statusBadgeTone, 'bad'); + assert.equal(bumpEnCopy.floorDeltaTone, 'bad'); + assert.ok(bumpEnCopy.floorDeltaText.includes('+200.000 ₫')); + assert.ok(bumpEnCopy.floorDeltaText.includes('+0.8%')); + + // 4. Strict < 30d window honesty: 18 days of history never claims 30d Omnibus + const shortWindowAudit = evaluateOmnibusPriceAudit({ + points: [ + { product_id: 'o1', price: 24_990_000, recorded_at: isoDaysAgo(18) }, + { product_id: 'o1', price: 26_990_000, recorded_at: isoDaysAgo(10) }, + { product_id: 'o1', price: 25_490_000, recorded_at: isoDaysAgo(4) }, + { product_id: 'o1', price: 25_490_000, recorded_at: isoDaysAgo(0) }, + ], + currentPriceVnd: 25_490_000, + claimedOriginalPriceVnd: 32_990_000, + referenceTimestampMs: ANCHOR_MS, + }); + assert.equal(shortWindowAudit.isOmnibusCertified, false); + assert.equal(shortWindowAudit.windowStatus, 'partial_window'); + assert.equal(shortWindowAudit.windowDaysUsed, 18); + assert.equal(shortWindowAudit.verdict, 'unverified_window'); + for (const loc of LOCALES) { + const shortCopy = formatOmnibusAuditCopy( + shortWindowAudit, + omnibusTranslator(messages[loc]), + loc + ); + assert.ok(shortCopy.statusBadgeText.includes('18')); + assert.ok(shortCopy.floorDisclaimerText?.includes('18/30')); + assert.equal(shortCopy.statusBadgeTone, 'warn'); + } + + // 5. Blackout gap (> 18d inside 30d window) withholds 30d Omnibus certification + const gappedAudit = evaluateOmnibusPriceAudit({ + points: [ + { product_id: 'o1', price: 24_990_000, recorded_at: isoDaysAgo(35) }, + { product_id: 'o1', price: 26_990_000, recorded_at: isoDaysAgo(2) }, + { product_id: 'o1', price: 25_990_000, recorded_at: isoDaysAgo(0) }, + ], + currentPriceVnd: 25_990_000, + claimedOriginalPriceVnd: 29_990_000, + referenceTimestampMs: ANCHOR_MS, + }); + assert.equal(gappedAudit.hasBlackoutGap, true); + assert.equal(gappedAudit.isOmnibusCertified, false); + assert.equal(gappedAudit.windowStatus, 'blackout_gap'); + assert.equal(gappedAudit.verdict, 'unverified_window'); + + // 6. Step-function boundary: an expired 40-day-old flash low superseded at d=31 + // does not leak into the 30-day window. + const supersededAudit = evaluateOmnibusPriceAudit({ + points: [ + { product_id: 'o1', price: 19_990_000, recorded_at: isoDaysAgo(40) }, + { product_id: 'o1', price: 27_990_000, recorded_at: isoDaysAgo(31) }, + { product_id: 'o1', price: 27_990_000, recorded_at: isoDaysAgo(20) }, + { product_id: 'o1', price: 27_990_000, recorded_at: isoDaysAgo(10) }, + { product_id: 'o1', price: 26_990_000, recorded_at: isoDaysAgo(0) }, + ], + currentPriceVnd: 26_990_000, + claimedOriginalPriceVnd: 27_990_000, + referenceTimestampMs: ANCHOR_MS, + }); + assert.equal(supersededAudit.isOmnibusCertified, true); + assert.equal(supersededAudit.priorFloorPriceVnd, 27_990_000); + assert.equal(supersededAudit.verdict, 'verified_omnibus_reduction'); + + // 7. Insufficient (< 1d) history with claimed strikethrough never claims alignment + const brandNewListingAudit = evaluateOmnibusPriceAudit({ + points: [ + { product_id: 'o1', price: 25_990_000, recorded_at: isoDaysAgo(0) }, + ], + currentPriceVnd: 25_990_000, + claimedOriginalPriceVnd: 31_990_000, + referenceTimestampMs: ANCHOR_MS, + }); + assert.equal(brandNewListingAudit.windowStatus, 'insufficient_history'); + const brandNewCopy = formatOmnibusAuditCopy( + brandNewListingAudit, + omnibusTranslator(messages.en), + 'en' + ); + assert.equal(brandNewCopy.currentSubTone, 'neutral'); + assert.equal(brandNewCopy.currentSubText, messages.en.oNeed); + + // 8. Round-1 regressions: trailing unobserved silence (`seriesSpanMs < 30d`), + // blackout_gap windowDaysUsed = 0, and sub-0.05% precision without -0%/+0%. + const trailingSilenceAudit = evaluateOmnibusPriceAudit({ + points: [ + { product_id: 'o1', price: 24_990_000, recorded_at: isoDaysAgo(32) }, + { product_id: 'o1', price: 25_490_000, recorded_at: isoDaysAgo(22) }, + { product_id: 'o1', price: 25_490_000, recorded_at: isoDaysAgo(12) }, + { product_id: 'o1', price: 25_490_000, recorded_at: isoDaysAgo(8) }, + ], + currentPriceVnd: 25_490_000, + claimedOriginalPriceVnd: 29_990_000, + referenceTimestampMs: ANCHOR_MS, + }); + assert.equal(trailingSilenceAudit.observedSpanDays, 24); + assert.equal(trailingSilenceAudit.isOmnibusCertified, false); + assert.equal(trailingSilenceAudit.windowStatus, 'partial_window'); + assert.equal(trailingSilenceAudit.windowDaysUsed, 24); + + assert.equal(gappedAudit.windowDaysUsed, 0); + + const microStepAudit = evaluateOmnibusPriceAudit({ + points: [ + { product_id: 'o1', price: 25_000_000, recorded_at: isoDaysAgo(32) }, + { product_id: 'o1', price: 25_000_000, recorded_at: isoDaysAgo(20) }, + { product_id: 'o1', price: 25_000_000, recorded_at: isoDaysAgo(10) }, + { product_id: 'o1', price: 24_990_000, recorded_at: isoDaysAgo(0) }, + ], + currentPriceVnd: 24_990_000, + claimedOriginalPriceVnd: 25_000_000, + referenceTimestampMs: ANCHOR_MS, + }); + assert.equal(microStepAudit.deltaVsPriorFloorPct, -0.04); + assert.equal(microStepAudit.claimedDiscountPct, 0.04); + assert.equal(microStepAudit.verdict, 'verified_omnibus_reduction'); + const microStepCopy = formatOmnibusAuditCopy( + microStepAudit, + omnibusTranslator(messages.en), + 'en' + ); + assert.ok(!microStepCopy.floorDeltaText.includes('-0%')); + assert.ok(microStepCopy.floorDeltaText.includes('-0.04%')); + assert.equal(microStepCopy.currentSubTone, 'good'); + console.warn('✅ Discount verdict copy suite passed'); } diff --git a/apps/web/src/lib/__tests__/sale-state.test.ts b/apps/web/src/lib/__tests__/sale-state.test.ts index f68438fe..255c736c 100644 --- a/apps/web/src/lib/__tests__/sale-state.test.ts +++ b/apps/web/src/lib/__tests__/sale-state.test.ts @@ -1,5 +1,8 @@ import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; +import React from 'react'; +import { renderToStaticMarkup } from 'react-dom/server'; +import { NextIntlClientProvider } from 'next-intl'; import { SALE_STATES, listingCountForSaleState, @@ -7,6 +10,20 @@ import { saleStateLabelKey, saleStateOfMaster, } from '../sale-state'; +import { + countSeasonalSaleCampaignDeals, + evaluateOmnibusPriceAudit, + matchesSeasonalSaleFilter, +} from '../omnibus-price-audit'; +import { pickClientMessages } from '../client-messages'; +import { parseEcommerceUrlOrQuery } from '../rate-domain'; +import { + AppRouterContext, + type AppRouterInstance, +} from 'next/dist/shared/lib/app-router-context.shared-runtime'; +import PriceHistorySection from '../../components/price-history/PriceHistorySection'; +import DealFinderWorkspace from '../../components/deals/DealFinderWorkspace'; +import DeepInspectWorkspace from '../../components/inspect/DeepInspectWorkspace'; function main() { console.warn('🧪 Sale state suite (DOS/Rate#1188)'); @@ -123,6 +140,778 @@ function main() { assert.ok(messages.saleState[`${key}Hint`], `${locale} ${key}Hint`); } } + + // ========================================================================= + // 90-Day Buy-vs-Wait Percentile, Plausibility/Availability & SSR (#1863) + // ========================================================================= + const DAY_MS = 86_400_000; + const ANCHOR_MS = Date.UTC(2026, 10, 22, 12, 0, 0); + const isoDaysAgo = (days: number) => + new Date(ANCHOR_MS - days * DAY_MS).toISOString(); + + // 1. <= P15 buy_now_floor: 1 dip day at 23.99M vs 9 days at 27.99M..28.99M + const buyNowAudit = evaluateOmnibusPriceAudit({ + points: [ + { product_id: 'o1', price: 28_990_000, recorded_at: isoDaysAgo(80) }, + { product_id: 'o1', price: 28_490_000, recorded_at: isoDaysAgo(70) }, + { product_id: 'o1', price: 27_990_000, recorded_at: isoDaysAgo(60) }, + { product_id: 'o1', price: 28_290_000, recorded_at: isoDaysAgo(50) }, + { product_id: 'o1', price: 27_990_000, recorded_at: isoDaysAgo(40) }, + { product_id: 'o1', price: 28_190_000, recorded_at: isoDaysAgo(30) }, + { product_id: 'o1', price: 27_990_000, recorded_at: isoDaysAgo(20) }, + { product_id: 'o1', price: 27_890_000, recorded_at: isoDaysAgo(12) }, + { product_id: 'o1', price: 27_990_000, recorded_at: isoDaysAgo(5) }, + { product_id: 'o1', price: 23_990_000, recorded_at: isoDaysAgo(0) }, + ], + currentPriceVnd: 23_990_000, + referenceTimestampMs: ANCHOR_MS, + }); + assert.equal(buyNowAudit.cycle90d.signal, 'buy_now_floor'); + assert.equal(buyNowAudit.cycle90d.percentile, 5); + assert.equal(buyNowAudit.cycle90d.low90dVnd, 23_990_000); + + // 2. Flat 90d price -> P50 fair_market (never falsely buy_now_floor or wait) + const flat90dAudit = evaluateOmnibusPriceAudit({ + points: [0, 7, 14, 21, 28, 35].map((d) => ({ + product_id: 'o1', + price: 25_000_000, + recorded_at: isoDaysAgo(d), + })), + currentPriceVnd: 25_000_000, + referenceTimestampMs: ANCHOR_MS, + }); + assert.equal(flat90dAudit.cycle90d.signal, 'fair_market'); + assert.equal(flat90dAudit.cycle90d.percentile, 50); + + // 3. > P70 above_recent_floor: exact VND gap above 90d low + const waitAudit = evaluateOmnibusPriceAudit({ + points: [ + { product_id: 'o1', price: 24_000_000, recorded_at: isoDaysAgo(45) }, + { product_id: 'o1', price: 24_500_000, recorded_at: isoDaysAgo(36) }, + { product_id: 'o1', price: 25_000_000, recorded_at: isoDaysAgo(27) }, + { product_id: 'o1', price: 25_500_000, recorded_at: isoDaysAgo(18) }, + { product_id: 'o1', price: 26_000_000, recorded_at: isoDaysAgo(9) }, + { product_id: 'o1', price: 27_500_000, recorded_at: isoDaysAgo(0) }, + ], + currentPriceVnd: 27_500_000, + referenceTimestampMs: ANCHOR_MS, + }); + assert.equal(waitAudit.cycle90d.signal, 'above_recent_floor'); + assert.ok((waitAudit.cycle90d.percentile ?? 0) > 70); + assert.equal(waitAudit.cycle90d.aboveFloorVnd, 3_500_000); + + // 4. Sufficiency guards: < 5 days, < 14d span, and same-day burst crawls + const fourDaysOnly = evaluateOmnibusPriceAudit({ + points: [0, 7, 14, 30].map((d) => ({ + product_id: 'o1', + price: 25_000_000 + d * 100_000, + recorded_at: isoDaysAgo(d), + })), + currentPriceVnd: 25_000_000, + referenceTimestampMs: ANCHOR_MS, + }); + assert.equal(fourDaysOnly.cycle90d.signal, 'insufficient_data'); + assert.equal(fourDaysOnly.cycle90d.observedPointDays, 4); + + const burstSameDay = evaluateOmnibusPriceAudit({ + points: [ + ...Array.from({ length: 15 }, (_, idx) => ({ + product_id: 'o1', + price: 25_000_000, + recorded_at: new Date(ANCHOR_MS - idx * 60_000).toISOString(), + })), + { product_id: 'o1', price: 26_000_000, recorded_at: isoDaysAgo(10) }, + { product_id: 'o1', price: 26_500_000, recorded_at: isoDaysAgo(20) }, + ], + currentPriceVnd: 25_000_000, + referenceTimestampMs: ANCHOR_MS, + }); + assert.equal(burstSameDay.cycle90d.signal, 'insufficient_data'); + assert.equal(burstSameDay.cycle90d.observedPointDays, 3); + + // 5. Bait-price, unavailable (out_of_stock / discontinued), and live_listing exclusions + const baitAndSoldOutAudit = evaluateOmnibusPriceAudit({ + points: [ + // Bait offer at 1.25M (< 40% of 26M..27M median) + ...[0, 7, 14, 21, 28, 35].map((d) => ({ + product_id: 'offer-bait', + price: 1_250_000, + recorded_at: isoDaysAgo(d), + })), + // Out-of-stock offer at 18M + ...[0, 7, 14, 21, 28, 35].map((d) => ({ + product_id: 'offer-soldout', + price: 18_000_000, + recorded_at: isoDaysAgo(d), + })), + // Valid in-stock peers at 26M..27M + ...[0, 7, 14, 21, 28, 35].map((d) => ({ + product_id: 'offer-good-a', + price: 26_000_000 + (d > 0 ? 500_000 : 0), + recorded_at: isoDaysAgo(d), + })), + ...[0, 7, 14, 21, 28, 35].map((d) => ({ + product_id: 'offer-good-b', + price: 27_000_000, + recorded_at: isoDaysAgo(d), + })), + // Synthetic fallback row must be ignored + { + product_id: 'offer-good-a', + price: 19_000_000, + recorded_at: isoDaysAgo(15), + source: 'live_listing', + }, + ], + currentPriceVnd: 26_000_000, + mode: 'market', + referenceOffers: [ + { id: 'offer-bait', price_current: 1_250_000, availability: 'in_stock' }, + { + id: 'offer-soldout', + price_current: 18_000_000, + availability: 'out_of_stock', + }, + { + id: 'offer-good-a', + price_current: 26_000_000, + availability: 'in_stock', + }, + { + id: 'offer-good-b', + price_current: 27_000_000, + availability: 'in_stock', + }, + ], + referenceTimestampMs: ANCHOR_MS, + }); + assert.equal(baitAndSoldOutAudit.priorFloorPriceVnd, 26_500_000); + assert.equal(baitAndSoldOutAudit.cycle90d.low90dVnd, 26_000_000); + assert.equal(baitAndSoldOutAudit.cycle90d.signal, 'buy_now_floor'); + + // Out-of-stock current product suppresses Buy-Now signal + const soldOutProductCycle = evaluateOmnibusPriceAudit({ + points: [0, 7, 14, 21, 28, 35].map((d) => ({ + product_id: 'offer-good-a', + price: 26_000_000, + recorded_at: isoDaysAgo(d), + })), + currentPriceVnd: 26_000_000, + currentInStockPriceVnd: null, + referenceTimestampMs: ANCHOR_MS, + }); + assert.equal(soldOutProductCycle.cycle90d.signal, 'insufficient_data'); + + // Micro-spread (< 1%) stays fair_market rather than Wait/Buy-Now on +1,000 VND + const microSpread90d = evaluateOmnibusPriceAudit({ + points: [7, 14, 21, 28, 35].map((d) => ({ + product_id: 'offer-good-a', + price: 25_000_000, + recorded_at: isoDaysAgo(d), + })), + currentPriceVnd: 25_001_000, + referenceTimestampMs: ANCHOR_MS, + }); + assert.equal(microSpread90d.cycle90d.signal, 'fair_market'); + + // Live price drop below historical low clamps low90dVnd to live price + const liveDropBelowHist = evaluateOmnibusPriceAudit({ + points: [2, 9, 16, 23, 30].map((d) => ({ + product_id: 'offer-good-a', + price: 26_000_000 + d * 50_000, + recorded_at: isoDaysAgo(d), + })), + currentPriceVnd: 24_500_000, + referenceTimestampMs: ANCHOR_MS, + }); + assert.equal(liveDropBelowHist.cycle90d.low90dVnd, 24_500_000); + assert.equal(liveDropBelowHist.cycle90d.signal, 'buy_now_floor'); + + // 6. Seasonal campaign filter helper & SSR rendering across vi, en, cs + const mockGenuineSig = { + verdict: 'genuine_deal' as const, + savingsPct: 12.5, + fakeMarkupPct: 0, + spreadPct: 14, + genuineDeal: { + id: 'g1', + verdict: 'genuine_all_time_low' as const, + verdictBadgeVi: 'Đáy giá', + productSlug: 'phone-a', + productName: 'Phone A', + brand: 'Apple', + categorySlug: 'smartphones' as const, + productHref: '/smartphones/phone-a', + imageUrl: null, + platform: 'shopee', + merchantId: 'm1', + merchantName: 'Shop A', + isOfficialMall: true, + merchantRiskScore: 4, + offerUrl: 'https://shopee.vn/a', + priceCurrent: 24_000_000, + priceOriginal: null, + marketMedianPrice: 27_400_000, + marketMinPrice: 24_000_000, + marketMaxPrice: 28_000_000, + savingsVsMedianVnd: 3_400_000, + savingsVsMedianPct: 12.5, + marketOfferCount: 3, + claimedDiscountPct: 0, + fakeMarkupPct: 0, + jreviewsScore10: 8.8, + explanationVi: 'Tốt', + }, + fakeSaleTrap: null, + priceSpread: null, + }; + const mockTrapSig = { + verdict: 'fake_sale_trap' as const, + savingsPct: 0, + fakeMarkupPct: 26.4, + spreadPct: 0, + genuineDeal: null, + fakeSaleTrap: { + ...mockGenuineSig.genuineDeal, + id: 't1', + verdict: 'inflated_fake_sale' as const, + productSlug: 'phone-b', + productName: 'Phone B', + priceCurrent: 27_400_000, + priceOriginal: 34_630_000, + savingsVsMedianVnd: 0, + savingsVsMedianPct: 0, + claimedDiscountPct: 20.9, + fakeMarkupPct: 26.4, + }, + priceSpread: null, + }; + assert.equal( + matchesSeasonalSaleFilter(mockGenuineSig, 'genuine_sale_drops'), + true + ); + assert.equal( + matchesSeasonalSaleFilter(mockGenuineSig, 'inflated_presale_warnings'), + false + ); + assert.equal( + matchesSeasonalSaleFilter(mockTrapSig, 'inflated_presale_warnings'), + true + ); + assert.equal( + matchesSeasonalSaleFilter( + { + ...mockTrapSig, + fakeSaleTrap: { + ...mockTrapSig.fakeSaleTrap, + priceOriginal: 20_000_000, + }, + }, + 'inflated_presale_warnings' + ), + false + ); + assert.equal( + matchesSeasonalSaleFilter( + { + ...mockGenuineSig, + genuineDeal: { + ...mockGenuineSig.genuineDeal, + savingsVsMedianVnd: 0, + }, + }, + 'genuine_sale_drops' + ), + false + ); + assert.deepEqual( + countSeasonalSaleCampaignDeals( + [{ slug: 'phone-a' }, { slug: 'phone-b' }, { slug: 'phone-c' }], + (slug) => + slug === 'phone-a' + ? mockGenuineSig + : slug === 'phone-b' + ? mockTrapSig + : null + ), + { genuineSaleCount: 1, inflatedWarningCount: 1 } + ); + + const IntlProvider = NextIntlClientProvider as React.ComponentType<{ + locale: string; + messages: Record; + timeZone: string; + children?: React.ReactNode; + }>; + + for (const locale of ['vi', 'en', 'cs'] as const) { + const rawCatalog = JSON.parse( + readFileSync( + new URL(`../../../locales/${locale}.json`, import.meta.url), + 'utf8' + ) + ) as Record; + + const historyHtml = renderToStaticMarkup( + React.createElement( + IntlProvider, + { + locale, + messages: pickClientMessages(rawCatalog, 'productDetail'), + timeZone: 'Asia/Ho_Chi_Minh', + }, + React.createElement(PriceHistorySection, { + productName: 'iPhone 16 Pro Max', + history: { + points: [0, 7, 14, 21, 28, 35].map((d, idx) => ({ + id: idx + 1, + product_id: 'offer-1', + merchant_name: 'Apple Flagship Store', + platform: 'shopee', + is_official: true, + price: d === 0 ? 27_190_000 : 27_490_000, + price_original: 34_990_000, + recorded_at: isoDaysAgo(d), + source: 'crawler', + })), + byOffer: { + 'offer-1': { + product_id: 'offer-1', + merchant_name: 'Apple Flagship Store', + platform: 'shopee', + price_current: 27_190_000, + price_original: 34_990_000, + claimed_discount_pct: 22.3, + real_discount_vs_median_pct: 1.1, + historical_min_price: 27_190_000, + historical_max_price: 27_490_000, + historical_median_price: 27_490_000, + observation_count: 6, + verdict: 'genuine_deal', + badge_label: 'Deal', + explanation: 'Deal', + }, + }, + lowestEverPrice: 27_190_000, + lowestEverDate: isoDaysAgo(0), + lowestEverMerchant: 'Apple Flagship Store', + highestEverPrice: 27_490_000, + currentMinPrice: 27_190_000, + fakeDiscountCount: 0, + genuineDealCount: 1, + }, + }) + ) + ); + assert.ok( + historyHtml.includes('data-testid="omnibus-price-audit-card"'), + `${locale}: PriceHistorySection renders omnibus card` + ); + assert.ok( + historyHtml.includes('data-testid="omnibus-cycle-signal"'), + `${locale}: PriceHistorySection renders 90d cycle signal` + ); + + const dealsHtml = renderToStaticMarkup( + React.createElement( + IntlProvider, + { + locale, + messages: pickClientMessages(rawCatalog, 'deals'), + timeZone: 'Asia/Ho_Chi_Minh', + }, + React.createElement(DealFinderWorkspace, { + products: [ + { + id: 'p1', + slug: 'phone-a', + name: 'Phone A', + brand: 'Apple', + model: 'Phone A', + model_key: 'apple_phone_a', + min_price: 24_000_000, + max_price: 28_000_000, + merchant_count: 3, + user_rating_weighted: 4.7, + authentic_review_count: 10, + total_reviews: 10, + status: 'published', + metadata: { category_slug: 'smartphones' }, + } as never, + ], + dealRadar: { + generatedAt: isoDaysAgo(0), + categoryFilter: 'all', + totalClustersAnalyzed: 1, + totalOffersAnalyzed: 3, + totalMerchantsAnalyzed: 3, + genuineDeals: [mockGenuineSig.genuineDeal], + fakeSaleTraps: [mockTrapSig.fakeSaleTrap], + priceSpreadLeaders: [], + }, + }) + ) + ); + assert.ok( + dealsHtml.includes('data-testid="deals-seasonal-campaign-filter"'), + `${locale}: DealFinderWorkspace renders seasonal campaign filter` + ); + + const mockRouter: AppRouterInstance = { + back: () => {}, + forward: () => {}, + refresh: () => {}, + push: () => {}, + replace: () => {}, + prefetch: () => {}, + bfcacheId: 'test', + }; + + const inspectValidHtml = renderToStaticMarkup( + React.createElement( + AppRouterContext.Provider, + { value: mockRouter }, + React.createElement( + IntlProvider, + { + locale, + messages: pickClientMessages(rawCatalog, 'inspect'), + timeZone: 'Asia/Ho_Chi_Minh', + }, + React.createElement(DeepInspectWorkspace, { + initialQuery: 'https://shopee.vn/item-1', + initialInspection: { + query: 'https://shopee.vn/item-1', + matchedType: 'product_listing', + parsedUrl: parseEcommerceUrlOrQuery('https://shopee.vn/item-1'), + masterProduct: { + id: 'mp-1', + slug: 'iphone-16-pro-max-256gb', + name: 'iPhone 16 Pro Max 256GB', + brand: 'Apple', + model: 'iPhone 16 Pro Max', + model_key: 'apple_iphone_16_pro_max_256gb', + min_price: 27_190_000, + max_price: 28_990_000, + merchant_count: 2, + status: 'published', + } as never, + matchedOffer: { + id: 'offer-1', + platform: 'shopee', + title: 'iPhone 16 Pro Max 256GB VN/A', + price_current: 27_190_000, + price_original: 34_990_000, + stock: 5, + rating_star: 4.9, + rating_count: 20, + url: 'https://shopee.vn/item-1', + availability: 'in_stock', + merchant: { + id: 'm-1', + name: 'Apple Flagship Store', + platform: 'shopee', + is_official: true, + rating_star: 4.9, + follower_count: 1000, + location: 'VN', + risk_score: 4, + dosafe_risk_score: 4, + review_risk_score: 4, + review_risk_breakdown: null, + }, + }, + allOffers: [], + discountAnalysis: null, + priceHistory: { + points: [0, 7, 14, 21, 28, 35].map((d, idx) => ({ + id: idx + 1, + product_id: 'offer-1', + merchant_name: 'Apple Flagship Store', + platform: 'shopee', + is_official: true, + price: d === 0 ? 27_190_000 : 27_490_000, + price_original: 34_990_000, + recorded_at: isoDaysAgo(d), + source: 'crawler', + })), + byOffer: {}, + lowestEverPrice: 27_190_000, + lowestEverDate: isoDaysAgo(0), + lowestEverMerchant: 'Apple Flagship Store', + highestEverPrice: 27_490_000, + currentMinPrice: 27_190_000, + fakeDiscountCount: 0, + genuineDealCount: 1, + }, + reviewSummary: null, + merchantProfile: null, + suggestions: [], + }, + }) + ) + ) + ); + assert.ok( + inspectValidHtml.includes('data-testid="inspect-omnibus-audit-card"'), + `${locale}: DeepInspectWorkspace renders Omnibus audit card on valid in-stock listing` + ); + + const inspectBaitHtml = renderToStaticMarkup( + React.createElement( + AppRouterContext.Provider, + { value: mockRouter }, + React.createElement( + IntlProvider, + { + locale, + messages: pickClientMessages(rawCatalog, 'inspect'), + timeZone: 'Asia/Ho_Chi_Minh', + }, + React.createElement(DeepInspectWorkspace, { + initialQuery: 'https://shopee.vn/bait', + initialInspection: { + query: 'https://shopee.vn/bait', + matchedType: 'product_listing', + parsedUrl: parseEcommerceUrlOrQuery('https://shopee.vn/bait'), + masterProduct: { + id: 'mp-1', + slug: 'iphone-16-pro-max-256gb', + name: 'iPhone 16 Pro Max 256GB', + brand: 'Apple', + model: 'iPhone 16 Pro Max', + model_key: 'apple_iphone_16_pro_max_256gb', + min_price: 27_190_000, + max_price: 28_990_000, + merchant_count: 2, + status: 'published', + } as never, + matchedOffer: { + id: 'offer-bait', + platform: 'shopee', + title: 'Ốp lưng iPhone 16', + price_current: 50_000, + price_original: 25_000_000, + stock: 5, + rating_star: 4.9, + rating_count: 20, + url: 'https://shopee.vn/bait', + availability: 'in_stock', + merchant: { + id: 'm-bait', + name: 'Bait Shop', + platform: 'shopee', + is_official: false, + rating_star: 4.0, + follower_count: 10, + location: 'VN', + risk_score: 60, + dosafe_risk_score: 60, + review_risk_score: 60, + review_risk_breakdown: null, + }, + }, + allOffers: [], + discountAnalysis: null, + priceHistory: { + points: [0, 10, 20, 32].map((d, idx) => ({ + id: idx + 1, + product_id: 'offer-1', + merchant_name: 'Shop', + platform: 'shopee', + is_official: true, + price: 27_190_000, + price_original: null, + recorded_at: isoDaysAgo(d), + source: 'crawler', + })), + byOffer: {}, + lowestEverPrice: 27_190_000, + lowestEverDate: isoDaysAgo(0), + lowestEverMerchant: 'Shop', + highestEverPrice: 27_190_000, + currentMinPrice: 27_190_000, + fakeDiscountCount: 0, + genuineDealCount: 0, + }, + reviewSummary: null, + merchantProfile: null, + suggestions: [], + }, + }) + ) + ) + ); + assert.equal( + inspectBaitHtml.includes('data-testid="inspect-omnibus-audit-card"'), + false, + `${locale}: DeepInspectWorkspace suppresses Omnibus audit card on bait listing` + ); + + // Overpriced listing with 0 own history points naast cheaper peer: + // - Never falsely gets green "buy now" (gets Wait signal for 31.99M vs 26.99M) + // - Never falsely accuses 0-day shop of 30d EU Omnibus violation + // - Marks Vietnamese shop name with lang="vi" on en/cs pages (WCAG 3.1.2) + const inspectOverpricedNewShopHtml = renderToStaticMarkup( + React.createElement( + AppRouterContext.Provider, + { value: mockRouter }, + React.createElement( + IntlProvider, + { + locale, + messages: pickClientMessages(rawCatalog, 'inspect'), + timeZone: 'Asia/Ho_Chi_Minh', + }, + React.createElement(DeepInspectWorkspace, { + initialQuery: 'https://shopee.vn/new-shop', + initialInspection: { + query: 'https://shopee.vn/new-shop', + matchedType: 'product_listing', + parsedUrl: parseEcommerceUrlOrQuery('https://shopee.vn/new-shop'), + masterProduct: { + id: 'mp-1', + slug: 'iphone-16-pro-max-256gb', + name: 'iPhone 16 Pro Max 256GB', + brand: 'Apple', + model: 'iPhone 16 Pro Max', + model_key: 'apple_iphone_16_pro_max_256gb', + min_price: 26_990_000, + max_price: 31_990_000, + merchant_count: 2, + status: 'published', + } as never, + matchedOffer: { + id: 'offer-new-expensive', + platform: 'shopee', + title: 'iPhone 16 Pro Max 256GB VN/A', + price_current: 31_990_000, + price_original: 34_990_000, + stock: 3, + rating_star: 4.8, + rating_count: 5, + url: 'https://shopee.vn/new-shop', + availability: 'in_stock', + merchant: { + id: 'm-vn', + name: 'Cửa Hàng Điện Thoại Hà Nội', + platform: 'shopee', + is_official: false, + rating_star: 4.8, + follower_count: 500, + location: 'VN', + risk_score: 12, + dosafe_risk_score: 12, + review_risk_score: 12, + review_risk_breakdown: null, + }, + }, + allOffers: [ + { + id: 'offer-cheap-peer', + platform: 'tiki', + title: 'iPhone 16 Pro Max 256GB', + price_current: 26_990_000, + price_original: null, + stock: 10, + rating_star: 4.9, + rating_count: 40, + url: 'https://tiki.vn/peer', + availability: 'in_stock', + merchant: { + id: 'm-peer', + name: 'Tiki Trading', + platform: 'tiki', + is_official: true, + rating_star: 4.9, + follower_count: 50000, + location: 'VN', + risk_score: 2, + dosafe_risk_score: 2, + review_risk_score: 2, + review_risk_breakdown: null, + }, + }, + { + id: 'offer-new-expensive', + platform: 'shopee', + title: 'iPhone 16 Pro Max 256GB VN/A', + price_current: 31_990_000, + price_original: 34_990_000, + stock: 3, + rating_star: 4.8, + rating_count: 5, + url: 'https://shopee.vn/new-shop', + availability: 'in_stock', + merchant: { + id: 'm-vn', + name: 'Cửa Hàng Điện Thoại Hà Nội', + platform: 'shopee', + is_official: false, + rating_star: 4.8, + follower_count: 500, + location: 'VN', + risk_score: 12, + dosafe_risk_score: 12, + review_risk_score: 12, + review_risk_breakdown: null, + }, + }, + ], + discountAnalysis: null, + priceHistory: { + points: [0, 7, 14, 21, 28, 35].map((d, idx) => ({ + id: idx + 1, + product_id: 'offer-cheap-peer', + merchant_name: 'Tiki Trading', + platform: 'tiki', + is_official: true, + price: 26_990_000 + (d > 0 ? 500_000 : 0), + price_original: null, + recorded_at: isoDaysAgo(d), + source: 'crawler', + })), + byOffer: {}, + lowestEverPrice: 26_990_000, + lowestEverDate: isoDaysAgo(0), + lowestEverMerchant: 'Tiki Trading', + highestEverPrice: 27_490_000, + currentMinPrice: 26_990_000, + fakeDiscountCount: 0, + genuineDealCount: 1, + }, + reviewSummary: null, + merchantProfile: null, + suggestions: [], + }, + }) + ) + ) + ); + const pvDict = (rawCatalog as { priceVerdict: Record }) + .priceVerdict; + assert.ok( + inspectOverpricedNewShopHtml.includes(pvDict.oPend!) && + inspectOverpricedNewShopHtml.includes(pvDict.oNeed!) && + !inspectOverpricedNewShopHtml.includes(pvDict.oOk!), + `${locale}: 0-history matchedOffer shows insufficient history, not competitor 30d floor` + ); + assert.ok( + inspectOverpricedNewShopHtml.includes( + 'data-testid="inspect-omnibus-cycle-signal" class="fw-bold mb-1 text-danger"' + ), + `${locale}: overpriced 31.99M listing renders danger Wait signal, never green Buy-Now` + ); + if (locale !== 'vi') { + assert.ok( + inspectOverpricedNewShopHtml.includes( + 'Cửa Hàng Điện Thoại Hà Nội' + ), + `${locale}: Vietnamese seller name in omnibusScopeListing carries lang="vi"` + ); + } + } + console.warn('✅ Sale state suite passed'); } diff --git a/apps/web/src/lib/omnibus-price-audit.ts b/apps/web/src/lib/omnibus-price-audit.ts new file mode 100644 index 00000000..0d3151c6 --- /dev/null +++ b/apps/web/src/lib/omnibus-price-audit.ts @@ -0,0 +1,1239 @@ +/** + * EU Omnibus 30-Day Prior Price-Floor Audit & 90-Day Cycle Buy-vs-Wait Engine + * (Package 8A Feature F1, DOS/Rate#1863). + * + * Inspired by Hlidac shopu (EU Directive 2019/2161 Article 6a) and Keepa/Prisjakt + * 90-day price-cycle percentiles. Pure, deterministic, client-safe TypeScript: + * zero database DDL, zero server-only imports, and strict window honesty. + */ +import { + IMPLAUSIBLY_LOW_RATIO, + MAX_VALID_VND_PRICE, + MINIMUM_EARBUDS_PRICE_FLOOR_VND, + implausiblyLowIndexes, + implausiblyLowOfferIds, + isImplausiblyLowPrice, + isOfferImplausiblyLowAgainstInStock, + normalizeOfferId, + plausibleOffers, +} from '@repo/shared-data/rules'; +import type { RadarSignal } from '@/lib/deal-radar'; +import { formatPlainNumber, formatPriceVnd } from '@/lib/locale-format'; +import { + isOfferUnavailable, + type OfferAvailability, +} from '@/lib/product-market-stats'; + +const DAY_MS = 86_400_000; +const CONTROL_CHAR_RE = /\p{Cc}+/gu; + +/** Full days required before certifying EU Omnibus Article 6a 30-day prior floor. */ +export const OMNIBUS_WINDOW_DAYS = 30; +/** Minimum distinct observed day buckets required to certify a 30-day floor. */ +export const MIN_OMNIBUS_OBSERVATION_DAYS = 3; +/** Maximum allowed gap (in days) inside the 30-day window before withholding certification. */ +export const MAX_OMNIBUS_BLACKOUT_GAP_DAYS = 18; +/** Maximum duration (in days) of a new trailing price change treated as the current sale event. */ +export const MAX_CURRENT_EVENT_TAIL_DAYS = 7; + +/** Reference lookback window for Buy-Now vs Wait percentile analysis. */ +export const CYCLE_90D_WINDOW_DAYS = 90; +/** Minimum distinct observed days required to emit a 90-day percentile call. */ +export const MIN_CYCLE_90D_POINTS = 5; +/** Minimum observed span (in days) required to emit a 90-day percentile call. */ +export const MIN_CYCLE_90D_SPAN_DAYS = 14; +/** <= P15 marks the 90-day floor zone ("Buy now"). */ +export const CYCLE_BUY_NOW_MAX_PERCENTILE = 15; +/** P16..P70 marks stable fair-market pricing; > P70 marks elevated ("Wait for sale"). */ +export const CYCLE_FAIR_MARKET_MAX_PERCENTILE = 70; +/** Minimum relative 90d price spread (1%) required before calling Buy-Now or Wait. */ +export const MIN_CYCLE_90D_RELATIVE_SPREAD = 0.01; + +export type OmnibusWindowStatus = + | 'omnibus_30d_certified' + | 'partial_window' + | 'blackout_gap' + | 'insufficient_history'; + +export type OmnibusAuditVerdict = + | 'fake_strikethrough_above_floor' + | 'exaggerated_strikethrough' + | 'verified_omnibus_reduction' + | 'below_30d_floor' + | 'at_or_above_30d_floor' + | 'unverified_window'; + +export type Cycle90dSignalKind = + 'buy_now_floor' | 'fair_market' | 'above_recent_floor' | 'insufficient_data'; + +export type SeasonalSaleFilterMode = + 'all' | 'genuine_sale_drops' | 'inflated_presale_warnings'; + +export interface OmnibusAuditPointInput { + readonly product_id?: string | null; + readonly price: unknown; + readonly price_original?: unknown; + readonly recorded_at: unknown; + readonly source?: string | null; + readonly availability?: OfferAvailability | null; + readonly implausiblyLow?: boolean | null; +} + +export interface OmnibusReferenceOfferInput { + readonly id?: string | null; + readonly price_current: number; + readonly availability?: OfferAvailability | null; + readonly implausiblyLow?: boolean | null; +} + +export interface EvaluateOmnibusPriceAuditParams { + readonly points: readonly OmnibusAuditPointInput[] | null | undefined; + /** Current selling price of the listing or best verified offer. */ + readonly currentPriceVnd: unknown; + /** Seller-claimed strikethrough original/list price, if any. */ + readonly claimedOriginalPriceVnd?: unknown; + /** + * Verified in-stock non-bait price used for the 90-day Buy-Now vs Wait call. + * Defaults to `currentPriceVnd` unless `currentOfferUnavailable` is true; + * pass `null` explicitly when no verified in-stock offer exists. + */ + readonly currentInStockPriceVnd?: unknown; + /** `'offer'` evaluates a single listing series; `'market'` computes daily floor across offers. */ + readonly mode?: 'offer' | 'market'; + readonly currentOfferUnavailable?: boolean; + readonly currentOfferImplausiblyLow?: boolean; + readonly referenceOffers?: readonly OmnibusReferenceOfferInput[] | null; + readonly unavailableOfferIds?: ReadonlySet | null; + readonly implausibleOfferIds?: ReadonlySet | null; + readonly minValidPriceVnd?: number; + /** Optional deterministic anchor timestamp in ms; defaults to latest valid point timestamp. */ + readonly referenceTimestampMs?: number | null; +} + +export interface Cycle90dEvaluation { + readonly signal: Cycle90dSignalKind; + readonly percentile: number | null; + readonly topPercentileDisplay: number | null; + readonly low90dVnd: number | null; + readonly high90dVnd: number | null; + readonly median90dVnd: number | null; + readonly aboveFloorVnd: number | null; + readonly aboveFloorPct: number | null; + readonly observedPointDays: number; + readonly observedSpanDays90d: number; +} + +export interface OmnibusPriceAuditResult { + readonly currentPriceVnd: number | null; + readonly claimedOriginalPriceVnd: number | null; + readonly claimedDiscountVnd: number | null; + readonly claimedDiscountPct: number | null; + readonly priorFloorPriceVnd: number | null; + readonly observedSpanDays: number; + readonly windowDaysUsed: number; + readonly isOmnibusCertified: boolean; + readonly hasBlackoutGap: boolean; + readonly windowStatus: OmnibusWindowStatus; + readonly verdict: OmnibusAuditVerdict; + readonly deltaVsPriorFloorVnd: number | null; + readonly deltaVsPriorFloorPct: number | null; + readonly claimedVsPriorFloorMarkupVnd: number | null; + readonly claimedVsPriorFloorMarkupPct: number | null; + readonly validObservationCount: number; + readonly cycle90d: Cycle90dEvaluation; +} + +export type OmnibusVerdictMessageKey = + | 'oTitle' + | 'oOk' + | 'oPart' + | 'oGap' + | 'oPend' + | 'oFlr' + | 'oCur' + | 'oClaim' + | 'oNoOrig' + | 'oMarkup' + | 'oAlign' + | 'oDrop' + | 'oFake' + | 'oUp' + | 'oFlat' + | 'oNeed' + | 'oNoteP' + | 'oNoteG' + | 'oCyc' + | 'oBuy' + | 'oFair' + | 'oWait' + | 'oRng' + | 'oCycP' + | 'oCycN'; + +export type OmnibusVerdictTranslator = ( + key: OmnibusVerdictMessageKey, + values?: Record +) => string; + +export interface FormattedOmnibusAuditCopy { + readonly cardTitle: string; + readonly statusBadgeText: string; + readonly statusBadgeTone: 'good' | 'warn' | 'bad' | 'neutral'; + readonly colCurrentTitle: string; + readonly currentPriceText: string; + readonly claimedBadgeText: string | null; + readonly currentSubText: string; + readonly currentSubTone: 'bad' | 'good' | 'neutral'; + readonly colFloorTitle: string; + readonly floorPriceText: string; + readonly floorDeltaText: string; + readonly floorDeltaTone: 'good' | 'bad' | 'neutral'; + readonly floorDisclaimerText: string | null; + readonly colCycleTitle: string; + readonly cycleValueText: string; + readonly cycleValueTone: 'good' | 'bad' | 'neutral'; + readonly cycleSubText: string; +} + +function parseStrictFiniteNumber(raw: unknown): number | null { + if (typeof raw === 'number') { + return Number.isFinite(raw) ? raw : null; + } + if (typeof raw === 'string') { + const cleaned = raw.replace(CONTROL_CHAR_RE, '').trim(); + if (!cleaned || cleaned.length > 32 || /^[+-]?0[xbo]/i.test(cleaned)) { + return null; + } + const num = Number(cleaned); + return Number.isFinite(num) ? num : null; + } + return null; +} + +export function sanitizeOmnibusPriceVnd( + raw: unknown, + minFloorVnd = MINIMUM_EARBUDS_PRICE_FLOOR_VND +): number | null { + const parsed = parseStrictFiniteNumber(raw); + if (parsed == null || parsed <= 0 || parsed > MAX_VALID_VND_PRICE) { + return null; + } + const rounded = Math.round(parsed); + const safeFloor = + Number.isFinite(minFloorVnd) && minFloorVnd > 0 + ? Math.round(minFloorVnd) + : MINIMUM_EARBUDS_PRICE_FLOOR_VND; + if (rounded < safeFloor || rounded > MAX_VALID_VND_PRICE) { + return null; + } + return rounded; +} + +function parseRecordedAtMs(raw: unknown): number | null { + if (typeof raw === 'number') { + return Number.isFinite(raw) && raw > 0 ? Math.round(raw) : null; + } + if (raw instanceof Date) { + const ms = raw.getTime(); + return Number.isFinite(ms) && ms > 0 ? ms : null; + } + if (typeof raw === 'string') { + const cleaned = raw.replace(CONTROL_CHAR_RE, '').trim(); + if (!cleaned || cleaned.length > 64) return null; + const ms = Date.parse(cleaned); + return Number.isFinite(ms) && ms > 0 ? ms : null; + } + return null; +} + +function roundDisplayPct(value: number): number { + if (!Number.isFinite(value) || value === 0) return 0; + const abs = Math.abs(value); + if (abs < 0.1) { + const rounded2 = Math.round(abs * 100) / 100; + const nonZero = Math.max(0.01, rounded2); + return value < 0 ? -nonZero : nonZero; + } + const rounded1 = Math.round(value * 10) / 10; + return Object.is(rounded1, -0) ? 0 : rounded1; +} + +function computeSortedMedian(sortedAsc: readonly number[]): number | null { + if (sortedAsc.length === 0) return null; + const mid = Math.floor(sortedAsc.length / 2); + if (sortedAsc.length % 2 === 1) { + return sortedAsc[mid] ?? null; + } + return Math.round(((sortedAsc[mid - 1] ?? 0) + (sortedAsc[mid] ?? 0)) / 2); +} + +interface CleanHistoryPoint { + readonly offerKey: string; + readonly priceVnd: number; + readonly recordedMs: number; +} + +interface SeriesPoint { + readonly priceVnd: number; + readonly recordedMs: number; +} + +function buildOfferExclusionSets(params: { + readonly referenceOffers?: readonly OmnibusReferenceOfferInput[] | null; + readonly unavailableOfferIds?: ReadonlySet | null; + readonly implausibleOfferIds?: ReadonlySet | null; + readonly minFloorVnd: number; +}): { + excludedIds: Set; + inStockPlausibleOffers: { id: string; price_current: number }[]; +} { + const excludedIds = new Set(); + if (params.unavailableOfferIds) { + for (const id of params.unavailableOfferIds) { + const clean = normalizeOfferId(id); + if (clean) excludedIds.add(clean); + if (typeof id === 'string' && id.trim()) excludedIds.add(id.trim()); + } + } + if (params.implausibleOfferIds) { + for (const id of params.implausibleOfferIds) { + const clean = normalizeOfferId(id); + if (clean) excludedIds.add(clean); + if (typeof id === 'string' && id.trim()) excludedIds.add(id.trim()); + } + } + + const safeRefOffers = Array.isArray(params.referenceOffers) + ? params.referenceOffers.filter((o): o is OmnibusReferenceOfferInput => + Boolean(o && typeof o === 'object' && !Array.isArray(o)) + ) + : []; + + const inStockSized: { id: string; price_current: number }[] = []; + for (const off of safeRefOffers) { + const rawId = typeof off.id === 'string' ? off.id.trim() : ''; + const canonId = normalizeOfferId(rawId); + const unavailable = isOfferUnavailable(off); + const price = sanitizeOmnibusPriceVnd( + off.price_current, + params.minFloorVnd + ); + if (unavailable || off.implausiblyLow === true || price == null) { + if (canonId) excludedIds.add(canonId); + if (rawId) excludedIds.add(rawId); + continue; + } + inStockSized.push({ + id: canonId || rawId, + price_current: price, + }); + } + + const baitIdsFromInStock = implausiblyLowOfferIds(inStockSized); + for (const bId of baitIdsFromInStock) { + excludedIds.add(bId); + } + for (const off of safeRefOffers) { + const rawId = typeof off.id === 'string' ? off.id.trim() : ''; + const canonId = normalizeOfferId(rawId); + const price = sanitizeOmnibusPriceVnd( + off.price_current, + params.minFloorVnd + ); + if ( + price != null && + inStockSized.length > 0 && + isOfferImplausiblyLowAgainstInStock( + { id: canonId || rawId, price_current: price }, + inStockSized, + baitIdsFromInStock + ) + ) { + if (canonId) excludedIds.add(canonId); + if (rawId) excludedIds.add(rawId); + } + } + + const inStockPlausibleOffers = plausibleOffers(inStockSized); + return { excludedIds, inStockPlausibleOffers }; +} + +/** + * Builds an ascending time series of verified prices: + * - In `'offer'` mode, collapses identical timestamps to the lowest valid price. + * - In `'market'` mode, computes the step-function market floor across active + * plausible offers at each observation timestamp (carrying each offer forward + * up to `MAX_OMNIBUS_BLACKOUT_GAP_DAYS` so staggered store crawls never create + * artificial spikes). + */ +function buildEffectiveSeries( + points: readonly CleanHistoryPoint[], + mode: 'offer' | 'market' +): SeriesPoint[] { + if (points.length === 0) return []; + const sorted = [...points].sort( + (a, b) => a.recordedMs - b.recordedMs || a.priceVnd - b.priceVnd + ); + + // When multiple offers are present without explicit referenceOffers, run + // cross-offer outlier detection on each offer's latest observed price so a + // bait listing inside raw points cannot set the 30d or 90d floor. + const latestByOffer = new Map(); + for (const pt of sorted) { + latestByOffer.set(pt.offerKey, pt.priceVnd); + } + const offerEntries = Array.from(latestByOffer.entries()); + const autoBaitKeys = new Set(); + if (offerEntries.length >= 3) { + const flagged = implausiblyLowIndexes(offerEntries.map(([, p]) => p)); + for (const idx of flagged) { + const key = offerEntries[idx]?.[0]; + if (key) autoBaitKeys.add(key); + } + } + + const filtered = + autoBaitKeys.size > 0 + ? sorted.filter((pt) => !autoBaitKeys.has(pt.offerKey)) + : sorted; + if (filtered.length === 0) return []; + + if (mode === 'offer' || latestByOffer.size <= 1) { + const out: SeriesPoint[] = []; + for (const pt of filtered) { + const prev = out[out.length - 1]; + if (prev && prev.recordedMs === pt.recordedMs) { + if (pt.priceVnd < prev.priceVnd) { + out[out.length - 1] = { + recordedMs: pt.recordedMs, + priceVnd: pt.priceVnd, + }; + } + } else { + out.push({ recordedMs: pt.recordedMs, priceVnd: pt.priceVnd }); + } + } + return out; + } + + const carryLimitMs = MAX_OMNIBUS_BLACKOUT_GAP_DAYS * DAY_MS; + const activeOffers = new Map< + string, + { priceVnd: number; recordedMs: number } + >(); + const out: SeriesPoint[] = []; + + let i = 0; + while (i < filtered.length) { + const tMs = filtered[i]!.recordedMs; + while (i < filtered.length && filtered[i]!.recordedMs === tMs) { + const pt = filtered[i]!; + const existing = activeOffers.get(pt.offerKey); + if ( + !existing || + existing.recordedMs < tMs || + pt.priceVnd < existing.priceVnd + ) { + activeOffers.set(pt.offerKey, { + priceVnd: pt.priceVnd, + recordedMs: tMs, + }); + } + i++; + } + let minActive = Number.POSITIVE_INFINITY; + for (const [key, state] of activeOffers.entries()) { + if (tMs - state.recordedMs > carryLimitMs) { + activeOffers.delete(key); + continue; + } + if (state.priceVnd < minActive) { + minActive = state.priceVnd; + } + } + if (Number.isFinite(minActive)) { + out.push({ recordedMs: tMs, priceVnd: minActive }); + } + } + return out; +} + +function evaluate90dCycleFromSeries(params: { + readonly series: readonly SeriesPoint[]; + readonly anchorMs: number; + readonly currentInStockPriceVnd: number | null; +}): Cycle90dEvaluation { + const { series, anchorMs, currentInStockPriceVnd } = params; + const cutoff90dMs = anchorMs - CYCLE_90D_WINDOW_DAYS * DAY_MS; + const in90d = series.filter( + (pt) => pt.recordedMs >= cutoff90dMs && pt.recordedMs <= anchorMs + ); + if (in90d.length === 0) { + return { + signal: 'insufficient_data', + percentile: null, + topPercentileDisplay: null, + low90dVnd: null, + high90dVnd: null, + median90dVnd: null, + aboveFloorVnd: null, + aboveFloorPct: null, + observedPointDays: 0, + observedSpanDays90d: 0, + }; + } + + const earliest90dMs = in90d[0]!.recordedMs; + const latest90dMs = in90d[in90d.length - 1]!.recordedMs; + const observedSpanDays90d = Math.max( + 0, + Math.floor((latest90dMs - earliest90dMs) / DAY_MS) + ); + + // Bucket into 24-hour day slots anchored at `anchorMs` so burst crawls on a + // single day never overweight one day in the 90-day empirical distribution. + const dailyMinByBucket = new Map(); + for (const pt of in90d) { + const dayBucket = Math.max( + 0, + Math.floor((anchorMs - pt.recordedMs) / DAY_MS) + ); + const prev = dailyMinByBucket.get(dayBucket); + if (prev == null || pt.priceVnd < prev) { + dailyMinByBucket.set(dayBucket, pt.priceVnd); + } + } + + const observedPointDays = dailyMinByBucket.size; + const sortedDailyPrices = Array.from(dailyMinByBucket.values()).sort( + (a, b) => a - b + ); + const rawLow90d = sortedDailyPrices[0] ?? null; + const rawHigh90d = sortedDailyPrices[sortedDailyPrices.length - 1] ?? null; + const low90dVnd = + rawLow90d != null && currentInStockPriceVnd != null + ? Math.min(rawLow90d, currentInStockPriceVnd) + : rawLow90d; + const high90dVnd = + rawHigh90d != null && currentInStockPriceVnd != null + ? Math.max(rawHigh90d, currentInStockPriceVnd) + : rawHigh90d; + const median90dVnd = computeSortedMedian(sortedDailyPrices); + + if ( + currentInStockPriceVnd == null || + observedPointDays < MIN_CYCLE_90D_POINTS || + observedSpanDays90d < MIN_CYCLE_90D_SPAN_DAYS || + low90dVnd == null || + high90dVnd == null + ) { + return { + signal: 'insufficient_data', + percentile: null, + topPercentileDisplay: null, + low90dVnd, + high90dVnd, + median90dVnd, + aboveFloorVnd: null, + aboveFloorPct: null, + observedPointDays, + observedSpanDays90d, + }; + } + + let belowCount = 0; + let equalCount = 0; + for (const p of sortedDailyPrices) { + if (p < currentInStockPriceVnd) belowCount++; + else if (p === currentInStockPriceVnd) equalCount++; + } + + const rawPercentile = + ((belowCount + 0.5 * equalCount) / sortedDailyPrices.length) * 100; + const percentile = Math.min(100, Math.max(0, Math.round(rawPercentile))); + const topPercentileDisplay = Math.max(1, percentile); + const aboveFloorVnd = Math.max(0, currentInStockPriceVnd - low90dVnd); + const aboveFloorPct = + low90dVnd > 0 && aboveFloorVnd > 0 + ? roundDisplayPct((aboveFloorVnd / low90dVnd) * 100) + : 0; + const relativeSpread = + low90dVnd > 0 ? (high90dVnd - low90dVnd) / low90dVnd : 0; + + let signal: Cycle90dSignalKind; + if (relativeSpread < MIN_CYCLE_90D_RELATIVE_SPREAD) { + signal = 'fair_market'; + } else if (percentile <= CYCLE_BUY_NOW_MAX_PERCENTILE) { + signal = 'buy_now_floor'; + } else if ( + percentile <= CYCLE_FAIR_MARKET_MAX_PERCENTILE || + aboveFloorPct < 1 + ) { + signal = 'fair_market'; + } else { + signal = 'above_recent_floor'; + } + + return { + signal, + percentile, + topPercentileDisplay, + low90dVnd, + high90dVnd, + median90dVnd, + aboveFloorVnd, + aboveFloorPct, + observedPointDays, + observedSpanDays90d, + }; +} + +/** + * Evaluates both the 30-day EU Omnibus prior price-floor audit and the 90-day + * price-cycle Buy-Now vs Wait percentile indicator with strict window honesty. + */ +export function evaluateOmnibusPriceAudit( + params: EvaluateOmnibusPriceAuditParams +): OmnibusPriceAuditResult { + const safeParams = + params && typeof params === 'object' + ? params + : ({ + points: [], + currentPriceVnd: null, + } as EvaluateOmnibusPriceAuditParams); + + const minFloorVnd = + typeof safeParams.minValidPriceVnd === 'number' && + Number.isFinite(safeParams.minValidPriceVnd) && + safeParams.minValidPriceVnd > 0 + ? Math.round(safeParams.minValidPriceVnd) + : MINIMUM_EARBUDS_PRICE_FLOOR_VND; + + const { excludedIds, inStockPlausibleOffers } = buildOfferExclusionSets({ + referenceOffers: safeParams.referenceOffers, + unavailableOfferIds: safeParams.unavailableOfferIds, + implausibleOfferIds: safeParams.implausibleOfferIds, + minFloorVnd, + }); + + const rawCurrent = sanitizeOmnibusPriceVnd( + safeParams.currentPriceVnd, + minFloorVnd + ); + const currentIsBaitAgainstPeers = + rawCurrent != null && + inStockPlausibleOffers.length >= 2 && + isImplausiblyLowPrice(rawCurrent, inStockPlausibleOffers); + + const currentPriceVnd = + safeParams.currentOfferUnavailable === true || + safeParams.currentOfferImplausiblyLow === true || + currentIsBaitAgainstPeers + ? null + : rawCurrent; + + const rawClaimedOrig = sanitizeOmnibusPriceVnd( + safeParams.claimedOriginalPriceVnd, + minFloorVnd + ); + const claimedOriginalPriceVnd = + currentPriceVnd != null && + rawClaimedOrig != null && + rawClaimedOrig > currentPriceVnd + ? rawClaimedOrig + : null; + + const claimedDiscountVnd = + currentPriceVnd != null && claimedOriginalPriceVnd != null + ? claimedOriginalPriceVnd - currentPriceVnd + : null; + const claimedDiscountPct = + claimedDiscountVnd != null && claimedOriginalPriceVnd != null + ? roundDisplayPct((claimedDiscountVnd / claimedOriginalPriceVnd) * 100) + : null; + + const resolvedInStockPrice = (() => { + if (safeParams.currentInStockPriceVnd !== undefined) { + if (safeParams.currentInStockPriceVnd === null) return null; + const candidate = sanitizeOmnibusPriceVnd( + safeParams.currentInStockPriceVnd, + minFloorVnd + ); + if ( + candidate != null && + inStockPlausibleOffers.length >= 2 && + isImplausiblyLowPrice(candidate, inStockPlausibleOffers) + ) { + return null; + } + return candidate; + } + return currentPriceVnd; + })(); + + const explicitAnchorMs = + safeParams.referenceTimestampMs != null && + Number.isFinite(safeParams.referenceTimestampMs) && + safeParams.referenceTimestampMs > 0 + ? Math.round(safeParams.referenceTimestampMs) + : null; + + const rawPoints = Array.isArray(safeParams.points) ? safeParams.points : []; + const cleanPoints: CleanHistoryPoint[] = []; + + for (const pt of rawPoints) { + if (!pt || typeof pt !== 'object' || Array.isArray(pt)) continue; + // Synthetic fallback rows (`live_listing`) mirror current listing prices and + // are never historical observation evidence. + if (pt.source === 'live_listing') continue; + if (isOfferUnavailable(pt) || pt.implausiblyLow === true) continue; + + const rawOfferId = + typeof pt.product_id === 'string' ? pt.product_id.trim() : ''; + const canonOfferId = normalizeOfferId(rawOfferId); + if ( + (canonOfferId && excludedIds.has(canonOfferId)) || + (rawOfferId && excludedIds.has(rawOfferId)) + ) { + continue; + } + + const priceVnd = sanitizeOmnibusPriceVnd(pt.price, minFloorVnd); + if (priceVnd == null) continue; + if ( + inStockPlausibleOffers.length >= 2 && + priceVnd < + inStockPlausibleOffers[ + Math.floor((inStockPlausibleOffers.length - 1) / 2) + ]!.price_current * + IMPLAUSIBLY_LOW_RATIO + ) { + continue; + } + + const recordedMs = parseRecordedAtMs(pt.recorded_at); + if (recordedMs == null) continue; + if (explicitAnchorMs != null && recordedMs > explicitAnchorMs) continue; + + cleanPoints.push({ + offerKey: canonOfferId || rawOfferId || '__default__', + priceVnd, + recordedMs, + }); + } + + const mode = safeParams.mode === 'market' ? 'market' : 'offer'; + const series = buildEffectiveSeries(cleanPoints, mode); + + if (series.length === 0) { + return { + currentPriceVnd, + claimedOriginalPriceVnd, + claimedDiscountVnd, + claimedDiscountPct, + priorFloorPriceVnd: null, + observedSpanDays: 0, + windowDaysUsed: 0, + isOmnibusCertified: false, + hasBlackoutGap: false, + windowStatus: 'insufficient_history', + verdict: 'unverified_window', + deltaVsPriorFloorVnd: null, + deltaVsPriorFloorPct: null, + claimedVsPriorFloorMarkupVnd: null, + claimedVsPriorFloorMarkupPct: null, + validObservationCount: 0, + cycle90d: { + signal: 'insufficient_data', + percentile: null, + topPercentileDisplay: null, + low90dVnd: null, + high90dVnd: null, + median90dVnd: null, + aboveFloorVnd: null, + aboveFloorPct: null, + observedPointDays: 0, + observedSpanDays90d: 0, + }, + }; + } + + const seriesLatestMs = series[series.length - 1]!.recordedMs; + const anchorMs = explicitAnchorMs ?? seriesLatestMs; + const earliestMs = series[0]!.recordedMs; + const seriesSpanMs = Math.max(0, seriesLatestMs - earliestMs); + const anchorSpanMs = Math.max(0, anchorMs - earliestMs); + const observedSpanDays = + series.length >= 2 ? Math.floor(seriesSpanMs / DAY_MS) : 0; + + const cycle90d = evaluate90dCycleFromSeries({ + series, + anchorMs, + currentInStockPriceVnd: resolvedInStockPrice, + }); + + // Require multi-day actual observations (>= 1 full day between real points + // and >= 2 timestamps) before reporting any prior floor at all. + if (series.length < 2 || seriesSpanMs < DAY_MS || currentPriceVnd == null) { + return { + currentPriceVnd, + claimedOriginalPriceVnd, + claimedDiscountVnd, + claimedDiscountPct, + priorFloorPriceVnd: null, + observedSpanDays, + windowDaysUsed: 0, + isOmnibusCertified: false, + hasBlackoutGap: false, + windowStatus: 'insufficient_history', + verdict: 'unverified_window', + deltaVsPriorFloorVnd: null, + deltaVsPriorFloorPct: null, + claimedVsPriorFloorMarkupVnd: null, + claimedVsPriorFloorMarkupPct: null, + validObservationCount: series.length, + cycle90d, + }; + } + + const windowStartMs = anchorMs - OMNIBUS_WINDOW_DAYS * DAY_MS; + const spansFull30d = + seriesSpanMs >= OMNIBUS_WINDOW_DAYS * DAY_MS && + anchorSpanMs >= OMNIBUS_WINDOW_DAYS * DAY_MS; + + let carryInPoint: SeriesPoint | null = null; + const inWindowPoints: SeriesPoint[] = []; + for (const pt of series) { + if (pt.recordedMs <= windowStartMs) { + carryInPoint = pt; + } else if (pt.recordedMs <= anchorMs) { + inWindowPoints.push(pt); + } + } + + const maxGapMs = MAX_OMNIBUS_BLACKOUT_GAP_DAYS * DAY_MS; + let hasBlackoutGap = false; + if (spansFull30d) { + const checkTimes: number[] = []; + if (carryInPoint) { + checkTimes.push(carryInPoint.recordedMs); + } else { + checkTimes.push(windowStartMs); + } + for (const pt of inWindowPoints) { + checkTimes.push(pt.recordedMs); + } + checkTimes.push(anchorMs); + + for (let i = 1; i < checkTimes.length; i++) { + if (checkTimes[i]! - checkTimes[i - 1]! > maxGapMs) { + hasBlackoutGap = true; + break; + } + } + } + + const windowCandidates: SeriesPoint[] = spansFull30d + ? [ + ...(carryInPoint && windowStartMs - carryInPoint.recordedMs <= maxGapMs + ? [carryInPoint] + : []), + ...inWindowPoints, + ] + : [...series]; + + const distinctWindowDays = new Set( + windowCandidates.map((pt) => + Math.floor((anchorMs - pt.recordedMs) / DAY_MS) + ) + ).size; + + // Separate the current price event tail from prior observations when the price + // changed within the recent campaign window (`<= 7` days), so a genuine sale + // starting today compares against the prior floor rather than against itself. + const hasPriceVariationInWindow = windowCandidates.some( + (pt) => pt.priceVnd !== currentPriceVnd + ); + const tailCutoffMs = hasPriceVariationInWindow + ? anchorMs - MAX_CURRENT_EVENT_TAIL_DAYS * DAY_MS + : anchorMs - 12 * 3_600_000; + + let trimEnd = windowCandidates.length; + while (trimEnd > 1) { + const tail = windowCandidates[trimEnd - 1]!; + if (tail.priceVnd === currentPriceVnd && tail.recordedMs > tailCutoffMs) { + trimEnd--; + } else { + break; + } + } + const priorCandidates = windowCandidates.slice(0, trimEnd); + + let priorFloorPriceVnd: number | null = null; + for (const pt of priorCandidates) { + if (priorFloorPriceVnd == null || pt.priceVnd < priorFloorPriceVnd) { + priorFloorPriceVnd = pt.priceVnd; + } + } + + const isOmnibusCertified = + spansFull30d && + !hasBlackoutGap && + distinctWindowDays >= MIN_OMNIBUS_OBSERVATION_DAYS && + priorFloorPriceVnd != null; + + const windowStatus: OmnibusWindowStatus = + priorFloorPriceVnd == null + ? 'insufficient_history' + : isOmnibusCertified + ? 'omnibus_30d_certified' + : spansFull30d && + (hasBlackoutGap || + distinctWindowDays < MIN_OMNIBUS_OBSERVATION_DAYS) + ? 'blackout_gap' + : 'partial_window'; + + const windowDaysUsed = + priorFloorPriceVnd == null || windowStatus === 'blackout_gap' + ? 0 + : isOmnibusCertified + ? OMNIBUS_WINDOW_DAYS + : Math.min(OMNIBUS_WINDOW_DAYS - 1, Math.max(1, observedSpanDays)); + + const deltaVsPriorFloorVnd = + priorFloorPriceVnd != null ? currentPriceVnd - priorFloorPriceVnd : null; + const deltaVsPriorFloorPct = + deltaVsPriorFloorVnd != null && priorFloorPriceVnd != null + ? roundDisplayPct((deltaVsPriorFloorVnd / priorFloorPriceVnd) * 100) + : null; + + const claimedVsPriorFloorMarkupVnd = + claimedOriginalPriceVnd != null && priorFloorPriceVnd != null + ? claimedOriginalPriceVnd - priorFloorPriceVnd + : null; + const claimedVsPriorFloorMarkupPct = + claimedVsPriorFloorMarkupVnd != null && priorFloorPriceVnd != null + ? roundDisplayPct( + (claimedVsPriorFloorMarkupVnd / priorFloorPriceVnd) * 100 + ) + : null; + + let verdict: OmnibusAuditVerdict = 'unverified_window'; + if (isOmnibusCertified && priorFloorPriceVnd != null) { + if (claimedOriginalPriceVnd != null) { + if ( + claimedOriginalPriceVnd > priorFloorPriceVnd && + currentPriceVnd >= priorFloorPriceVnd + ) { + verdict = 'fake_strikethrough_above_floor'; + } else if ( + claimedOriginalPriceVnd > Math.round(priorFloorPriceVnd * 1.02) && + currentPriceVnd < priorFloorPriceVnd + ) { + verdict = 'exaggerated_strikethrough'; + } else if (currentPriceVnd < priorFloorPriceVnd) { + verdict = 'verified_omnibus_reduction'; + } else { + verdict = 'at_or_above_30d_floor'; + } + } else if (currentPriceVnd < priorFloorPriceVnd) { + verdict = 'below_30d_floor'; + } else { + verdict = 'at_or_above_30d_floor'; + } + } + + return { + currentPriceVnd, + claimedOriginalPriceVnd, + claimedDiscountVnd, + claimedDiscountPct, + priorFloorPriceVnd, + observedSpanDays, + windowDaysUsed, + isOmnibusCertified, + hasBlackoutGap, + windowStatus, + verdict, + deltaVsPriorFloorVnd, + deltaVsPriorFloorPct, + claimedVsPriorFloorMarkupVnd, + claimedVsPriorFloorMarkupPct, + validObservationCount: series.length, + cycle90d, + }; +} + +/** + * Formats an `OmnibusPriceAuditResult` into locale-ready strings and semantic + * WCAG contrast tones (`good` / `warn` / `bad` / `neutral`) for `vi`, `en`, `cs`. + */ +export function formatOmnibusAuditCopy( + audit: OmnibusPriceAuditResult, + t: OmnibusVerdictTranslator, + locale?: string | null +): FormattedOmnibusAuditCopy { + const priceOrDash = (vnd: number | null) => + vnd != null && vnd > 0 ? formatPriceVnd(vnd, locale) : '-'; + + let statusBadgeText: string; + let statusBadgeTone: 'good' | 'warn' | 'bad' | 'neutral'; + if (audit.windowStatus === 'omnibus_30d_certified') { + statusBadgeText = t('oOk'); + statusBadgeTone = + audit.verdict === 'fake_strikethrough_above_floor' ? 'bad' : 'good'; + } else if (audit.windowStatus === 'partial_window') { + statusBadgeText = t('oPart', { days: audit.windowDaysUsed }); + statusBadgeTone = 'warn'; + } else if (audit.windowStatus === 'blackout_gap') { + statusBadgeText = t('oGap'); + statusBadgeTone = 'warn'; + } else { + statusBadgeText = t('oPend'); + statusBadgeTone = 'neutral'; + } + + const claimedBadgeText = + audit.claimedOriginalPriceVnd != null && audit.claimedDiscountPct != null + ? t('oClaim', { + pct: formatPlainNumber(audit.claimedDiscountPct, locale), + original: formatPriceVnd(audit.claimedOriginalPriceVnd, locale), + }) + : null; + + let currentSubText: string; + let currentSubTone: 'bad' | 'good' | 'neutral' = 'neutral'; + const exceedsAlignedTolerance = + audit.claimedOriginalPriceVnd != null && + audit.priorFloorPriceVnd != null && + (audit.verdict === 'fake_strikethrough_above_floor' || + audit.verdict === 'exaggerated_strikethrough' || + audit.claimedOriginalPriceVnd > + Math.round(audit.priorFloorPriceVnd * 1.02)); + + if (audit.claimedOriginalPriceVnd == null) { + currentSubText = t('oNoOrig'); + } else if (audit.priorFloorPriceVnd == null) { + currentSubText = t('oNeed'); + } else if ( + exceedsAlignedTolerance && + audit.claimedVsPriorFloorMarkupVnd != null && + audit.claimedVsPriorFloorMarkupVnd > 0 && + audit.claimedVsPriorFloorMarkupPct != null + ) { + currentSubText = t('oMarkup', { + markup: formatPriceVnd(audit.claimedVsPriorFloorMarkupVnd, locale), + pct: formatPlainNumber(audit.claimedVsPriorFloorMarkupPct, locale), + }); + currentSubTone = + audit.verdict === 'fake_strikethrough_above_floor' || + audit.verdict === 'exaggerated_strikethrough' + ? 'bad' + : 'neutral'; + } else { + currentSubText = t('oAlign'); + currentSubTone = audit.isOmnibusCertified ? 'good' : 'neutral'; + } + + const colFloorTitle = + audit.windowStatus === 'omnibus_30d_certified' + ? t('oOk') + : audit.windowStatus === 'partial_window' + ? t('oPart', { days: audit.windowDaysUsed }) + : t('oFlr'); + + let floorDeltaText: string; + let floorDeltaTone: 'good' | 'bad' | 'neutral' = 'neutral'; + if ( + audit.priorFloorPriceVnd == null || + audit.deltaVsPriorFloorVnd == null || + audit.deltaVsPriorFloorPct == null + ) { + floorDeltaText = t('oNeed'); + } else if (audit.deltaVsPriorFloorVnd < 0) { + const absAmount = Math.abs(audit.deltaVsPriorFloorVnd); + const absPct = Math.abs(audit.deltaVsPriorFloorPct); + floorDeltaText = t('oDrop', { + pct: formatPlainNumber(absPct, locale), + amount: formatPriceVnd(absAmount, locale), + }); + floorDeltaTone = 'good'; + } else if (audit.deltaVsPriorFloorVnd > 0) { + if (audit.verdict === 'fake_strikethrough_above_floor') { + floorDeltaText = t('oFake', { + pct: formatPlainNumber(audit.deltaVsPriorFloorPct, locale), + amount: formatPriceVnd(audit.deltaVsPriorFloorVnd, locale), + }); + } else { + floorDeltaText = t('oUp', { + pct: formatPlainNumber(audit.deltaVsPriorFloorPct, locale), + amount: formatPriceVnd(audit.deltaVsPriorFloorVnd, locale), + }); + } + floorDeltaTone = 'bad'; + } else if (audit.verdict === 'fake_strikethrough_above_floor') { + floorDeltaText = t('oFake', { + pct: formatPlainNumber(0, locale), + amount: formatPriceVnd(0, locale), + }); + floorDeltaTone = 'bad'; + } else { + floorDeltaText = t('oFlat'); + floorDeltaTone = 'neutral'; + } + + const floorDisclaimerText = + audit.windowStatus === 'partial_window' + ? t('oNoteP', { days: audit.windowDaysUsed }) + : audit.windowStatus === 'blackout_gap' + ? t('oNoteG') + : null; + + let cycleValueText: string; + let cycleValueTone: 'good' | 'bad' | 'neutral' = 'neutral'; + let cycleSubText: string; + const c = audit.cycle90d; + + if ( + c.signal === 'buy_now_floor' && + c.topPercentileDisplay != null && + c.low90dVnd != null && + c.high90dVnd != null + ) { + cycleValueText = t('oBuy', { + pct: formatPlainNumber(c.topPercentileDisplay, locale), + }); + cycleValueTone = 'good'; + cycleSubText = t('oRng', { + low: formatPriceVnd(c.low90dVnd, locale), + high: formatPriceVnd(c.high90dVnd, locale), + }); + } else if ( + c.signal === 'fair_market' && + c.percentile != null && + c.low90dVnd != null && + c.high90dVnd != null + ) { + cycleValueText = t('oFair', { + pct: formatPlainNumber(c.percentile, locale), + }); + cycleValueTone = 'neutral'; + cycleSubText = t('oRng', { + low: formatPriceVnd(c.low90dVnd, locale), + high: formatPriceVnd(c.high90dVnd, locale), + }); + } else if ( + c.signal === 'above_recent_floor' && + c.aboveFloorVnd != null && + c.low90dVnd != null && + c.high90dVnd != null + ) { + cycleValueText = t('oWait', { + gap: formatPriceVnd(c.aboveFloorVnd, locale), + }); + cycleValueTone = 'bad'; + cycleSubText = t('oRng', { + low: formatPriceVnd(c.low90dVnd, locale), + high: formatPriceVnd(c.high90dVnd, locale), + }); + } else { + cycleValueText = t('oCycP'); + cycleValueTone = 'neutral'; + cycleSubText = t('oCycN', { + points: c.observedPointDays, + days: c.observedSpanDays90d, + }); + } + + return { + cardTitle: t('oTitle'), + statusBadgeText, + statusBadgeTone, + colCurrentTitle: t('oCur'), + currentPriceText: priceOrDash(audit.currentPriceVnd), + claimedBadgeText, + currentSubText, + currentSubTone, + colFloorTitle, + floorPriceText: priceOrDash(audit.priorFloorPriceVnd), + floorDeltaText, + floorDeltaTone, + floorDisclaimerText, + colCycleTitle: t('oCyc'), + cycleValueText, + cycleValueTone, + cycleSubText, + }; +} + +/** + * Seasonal sale campaign filter predicate for `/deals` (`DealFinderWorkspace`). + */ +export function matchesSeasonalSaleFilter( + signal: RadarSignal | null | undefined, + mode: SeasonalSaleFilterMode +): boolean { + if (mode === 'all') return true; + if (!signal || typeof signal !== 'object') return false; + if (mode === 'genuine_sale_drops') { + const g = signal.genuineDeal; + if (!g || typeof g !== 'object') return false; + const current = parseStrictFiniteNumber(g.priceCurrent); + const savingsVnd = parseStrictFiniteNumber(g.savingsVsMedianVnd); + return Boolean( + typeof signal.savingsPct === 'number' && + Number.isFinite(signal.savingsPct) && + signal.savingsPct > 0 && + current != null && + current > 0 && + current <= MAX_VALID_VND_PRICE && + savingsVnd != null && + savingsVnd > 0 && + savingsVnd <= MAX_VALID_VND_PRICE + ); + } + if (mode === 'inflated_presale_warnings') { + const trap = signal.fakeSaleTrap; + if (!trap || typeof trap !== 'object') return false; + const current = parseStrictFiniteNumber(trap.priceCurrent); + const orig = parseStrictFiniteNumber(trap.priceOriginal); + return Boolean( + typeof signal.fakeMarkupPct === 'number' && + Number.isFinite(signal.fakeMarkupPct) && + signal.fakeMarkupPct > 0 && + current != null && + current > 0 && + current <= MAX_VALID_VND_PRICE && + orig != null && + orig > current && + orig <= MAX_VALID_VND_PRICE + ); + } + return true; +} + +export function countSeasonalSaleCampaignDeals( + deals: readonly T[], + getSignal: (slug: string) => RadarSignal | null | undefined +): { + genuineSaleCount: number; + inflatedWarningCount: number; +} { + if (!Array.isArray(deals)) { + return { genuineSaleCount: 0, inflatedWarningCount: 0 }; + } + let genuineSaleCount = 0; + let inflatedWarningCount = 0; + for (const d of deals) { + if (!d || typeof d.slug !== 'string') continue; + const sig = getSignal(d.slug); + if (matchesSeasonalSaleFilter(sig, 'genuine_sale_drops')) { + genuineSaleCount++; + } + if (matchesSeasonalSaleFilter(sig, 'inflated_presale_warnings')) { + inflatedWarningCount++; + } + } + return { genuineSaleCount, inflatedWarningCount }; +}