From 8107293e0a69449f4ca485b56775097f6eb854cb Mon Sep 17 00:00:00 2001 From: JOY <5027251+JOY@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:35:20 +0700 Subject: [PATCH 1/2] fix(web): propagate offer availability into Omnibus price audit Add optional availability on OfferDiscountAnalysis in rate-domain and populate it in getMasterProductPriceHistory, include availability in price-history cache keys, forward offers into PriceHistorySection from ProductDetailView and ItemLazySizePanel, and cover sold-out normal_price exclusion when offers is omitted (Refs #1871). --- .../app/[locale]/smartphones/[slug]/page.tsx | 3 + .../price-history/PriceHistorySection.tsx | 133 ++++++-- .../product/item/ItemLazySizePanel.tsx | 1 + .../lib/__tests__/offer-plausibility.test.ts | 10 + apps/web/src/lib/__tests__/sale-state.test.ts | 309 +++++++++++++++++- apps/web/src/lib/omnibus-price-audit.ts | 9 +- apps/web/src/lib/rate-api.ts | 4 + apps/web/src/lib/rate-domain.ts | 1 + apps/web/src/server/rate/index.ts | 8 +- apps/web/src/server/rate/item-page.ts | 3 +- 10 files changed, 448 insertions(+), 33 deletions(-) diff --git a/apps/web/src/app/[locale]/smartphones/[slug]/page.tsx b/apps/web/src/app/[locale]/smartphones/[slug]/page.tsx index 8121bd885..91f444bda 100644 --- a/apps/web/src/app/[locale]/smartphones/[slug]/page.tsx +++ b/apps/web/src/app/[locale]/smartphones/[slug]/page.tsx @@ -761,6 +761,7 @@ export async function ProductDetailView({ // renders them for its own master, an Item page once per size (#1154). const renderPriceHistory = (v: { product: { name: string }; + offers: typeof offers; priceHistory: typeof priceHistory; minPrice: number; radarSignal: typeof radarSignal; @@ -773,6 +774,7 @@ export async function ProductDetailView({ currentMinPrice: v.minPrice > 0 ? v.minPrice : null, }} radarSignal={v.radarSignal} + offers={v.offers} /> ); const renderOffersBody = (v: { @@ -1631,6 +1633,7 @@ export async function ProductDetailView({ ) : renderPriceHistory({ product, + offers, priceHistory, minPrice: currentMinPrice, radarSignal, diff --git a/apps/web/src/components/price-history/PriceHistorySection.tsx b/apps/web/src/components/price-history/PriceHistorySection.tsx index 2fbae3ca3..2b373c5b7 100644 --- a/apps/web/src/components/price-history/PriceHistorySection.tsx +++ b/apps/web/src/components/price-history/PriceHistorySection.tsx @@ -29,12 +29,13 @@ import { } from '@repo/shared-data/rules'; import { isOfferUnavailable, - type OfferAvailability, + toOfferAvailability, } from '@/lib/product-market-stats'; import { MAX_VALID_VND_PRICE, type DiscountVerdictType, type MasterProductPriceHistorySummary, + type OfferAvailability, type OfferDiscountAnalysis, type PriceHistoryPoint, } from '@/lib/rate-domain'; @@ -680,33 +681,72 @@ export default function PriceHistorySection({ }, [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`). + // explicit `availability` on `offerAnalyses`, or fallback heuristics when + // availability is unknown (prices strictly below the verified in-stock minimum, + // DOS/Rate#1141, or `rate-api`'s unavailable `normal_price` suppression). const unavailableOfferIds = useMemo>(() => { const ids = new Set(); const addId = (rawId: string | null | undefined) => { - if (!rawId) return; + if (typeof rawId !== 'string') return; + const trimmed = rawId.trim(); + if (!trimmed) return; ids.add(rawId); - const canon = normalizeOfferId(rawId); + ids.add(trimmed); + const canon = normalizeOfferId(trimmed); if (canon) ids.add(canon); }; + const explicitAvailFromOffers = new Map(); + const setOfferAvail = ( + rawId: string | null | undefined, + avail: OfferAvailability + ) => { + if (typeof rawId !== 'string') return; + const trimmed = rawId.trim(); + if (!trimmed) return; + const canon = normalizeOfferId(trimmed); + for (const key of [rawId, trimmed, canon]) { + if (!key) continue; + const prev = explicitAvailFromOffers.get(key); + if (!prev || isOfferUnavailable({ availability: avail })) { + explicitAvailFromOffers.set(key, avail); + } + } + }; + if (Array.isArray(offers)) { for (const off of offers) { - if (off && isOfferUnavailable(off)) { - addId(off.id); + if (!off || typeof off !== 'object') continue; + const rawId = + typeof off.id === 'string' && off.id.trim() + ? off.id + : typeof off.product_id === 'string' + ? off.product_id + : null; + const avail = toOfferAvailability(off.availability); + if (avail) { + setOfferAvail(rawId, avail); + if (isOfferUnavailable({ availability: avail })) { + addId(rawId); + } } } } for (const oa of offerAnalyses) { - const maybeAvail = (oa as { availability?: OfferAvailability | null }) - .availability; - if (maybeAvail && isOfferUnavailable({ availability: maybeAvail })) { - addId(oa.product_id); + const canonOaId = normalizeOfferId(oa.product_id); + const explicitAvail = + explicitAvailFromOffers.get(oa.product_id) ?? + explicitAvailFromOffers.get(oa.product_id.trim()) ?? + (canonOaId ? explicitAvailFromOffers.get(canonOaId) : undefined) ?? + toOfferAvailability(oa.availability); + if (explicitAvail) { + if (isOfferUnavailable({ availability: explicitAvail })) { + addId(oa.product_id); + } continue; } + const p = Number(oa.price_current); if ( safeCurrentMinPrice != null && @@ -746,23 +786,56 @@ export default function PriceHistorySection({ const isUnavailId = useCallback( (id: string) => unavailableOfferIds.has(id) || + unavailableOfferIds.has(id.trim()) || unavailableOfferIds.has(normalizeOfferId(id)), [unavailableOfferIds] ); - const effectiveReferenceOffers = useMemo( - () => - Array.isArray(offers) && offers.length > 0 - ? [...offers] - : offerAnalyses.map((oa) => ({ - id: oa.product_id, - price_current: oa.price_current, - availability: isUnavailId(oa.product_id) - ? ('out_of_stock' as const) + const effectiveReferenceOffers = useMemo(() => { + if (Array.isArray(offers) && offers.length > 0) { + return offers + .filter((off): off is OmnibusReferenceOfferInput => + Boolean(off && typeof off === 'object' && !Array.isArray(off)) + ) + .map((off) => { + const rawId = + typeof off.id === 'string' && off.id.trim() + ? off.id + : typeof off.product_id === 'string' + ? off.product_id + : undefined; + const explicit = toOfferAvailability(off.availability); + const unavailable = Boolean(rawId && isUnavailId(rawId)); + return { + id: rawId, + price_current: off.price_current, + availability: unavailable + ? explicit && isOfferUnavailable({ availability: explicit }) + ? explicit + : ('out_of_stock' as const) : ('in_stock' as const), - })), - [isUnavailId, offerAnalyses, offers] - ); + implausiblyLow: off.implausiblyLow, + }; + }); + } + return offerAnalyses.map((oa) => { + const explicit = toOfferAvailability(oa.availability); + return { + id: oa.product_id, + price_current: oa.price_current, + availability: isUnavailId(oa.product_id) + ? explicit && isOfferUnavailable({ availability: explicit }) + ? explicit + : ('out_of_stock' as const) + : ('in_stock' as const), + }; + }); + }, [isUnavailId, offerAnalyses, offers]); + + const allKnownOffersUnavailable = useMemo(() => { + if (effectiveReferenceOffers.length === 0) return false; + return effectiveReferenceOffers.every((off) => isOfferUnavailable(off)); + }, [effectiveReferenceOffers]); // Historical anchor uses the exact same evidence-eligibility rules as the // Omnibus evaluator so rows below `minValidPriceVnd`, `live_listing` rows, @@ -881,12 +954,18 @@ export default function PriceHistorySection({ return evaluateOmnibusPriceAudit({ ...omnibusSharedOpts, points: validPoints, - currentPriceVnd: safeCurrentMinPrice, - claimedOriginalPriceVnd: bestClaimedOrig, - currentInStockPriceVnd: safeCurrentMinPrice, + currentPriceVnd: allKnownOffersUnavailable ? null : safeCurrentMinPrice, + claimedOriginalPriceVnd: allKnownOffersUnavailable + ? null + : bestClaimedOrig, + currentInStockPriceVnd: allKnownOffersUnavailable + ? null + : safeCurrentMinPrice, + currentOfferUnavailable: allKnownOffersUnavailable, mode: 'market', }); }, [ + allKnownOffersUnavailable, isUnavailId, offerAnalyses, omnibusByOffer, diff --git a/apps/web/src/components/product/item/ItemLazySizePanel.tsx b/apps/web/src/components/product/item/ItemLazySizePanel.tsx index 46d96424c..464384de5 100644 --- a/apps/web/src/components/product/item/ItemLazySizePanel.tsx +++ b/apps/web/src/components/product/item/ItemLazySizePanel.tsx @@ -196,6 +196,7 @@ function renderSize( currentMinPrice: data.stats.minPrice > 0 ? data.stats.minPrice : null, }} radarSignal={data.radarSignal} + offers={data.offers} /> ); } diff --git a/apps/web/src/lib/__tests__/offer-plausibility.test.ts b/apps/web/src/lib/__tests__/offer-plausibility.test.ts index 309f4ef63..693de5a91 100644 --- a/apps/web/src/lib/__tests__/offer-plausibility.test.ts +++ b/apps/web/src/lib/__tests__/offer-plausibility.test.ts @@ -235,8 +235,18 @@ async function main() { history.byOffer['sold-out-cheap-real']?.verdict, 'normal_price' ); + assert.equal( + history.byOffer['sold-out-cheap-real']?.availability, + 'out_of_stock' + ); + assert.equal( + history.byOffer['sold-out-high']?.availability, + 'discontinued' + ); assert.equal(history.byOffer['in-stock-3']?.verdict, 'normal_price'); + assert.equal(history.byOffer['in-stock-3']?.availability, 'in_stock'); assert.equal(history.byOffer['in-stock-1']?.verdict, 'genuine_deal'); + assert.equal(history.byOffer['in-stock-1']?.availability, 'in_stock'); assert.equal(history.genuineDealCount, 1); // Zero in-stock offers: safe fallback drops sold-out 500k bait among sold-out peers. diff --git a/apps/web/src/lib/__tests__/sale-state.test.ts b/apps/web/src/lib/__tests__/sale-state.test.ts index edc17eb67..f0dc0361c 100644 --- a/apps/web/src/lib/__tests__/sale-state.test.ts +++ b/apps/web/src/lib/__tests__/sale-state.test.ts @@ -16,7 +16,12 @@ import { matchesSeasonalSaleFilter, } from '../omnibus-price-audit'; import { pickClientMessages } from '../client-messages'; -import { parseEcommerceUrlOrQuery } from '../rate-domain'; +import { + parseEcommerceUrlOrQuery, + type OfferAvailability, + type OfferDiscountAnalysis, +} from '../rate-domain'; +import { formatPriceVnd } from '../locale-format'; import { AppRouterContext, type AppRouterInstance, @@ -26,7 +31,7 @@ import DealFinderWorkspace from '../../components/deals/DealFinderWorkspace'; import DeepInspectWorkspace from '../../components/inspect/DeepInspectWorkspace'; import { GLOBAL_ERROR_CATALOG } from '../../app/global-error'; -function main() { +async function main() { console.warn('🧪 Sale state suite (DOS/Rate#1188)'); // An in-stock price wins over everything else. @@ -984,7 +989,305 @@ function main() { assert.equal(twoInWindowPlusCarry.isOmnibusCertified, false); assert.equal(twoInWindowPlusCarry.windowStatus, 'blackout_gap'); + // ========================================================================= + // 7. Explicit OfferAvailability on OfferDiscountAnalysis & PriceHistorySection + // when `offers` is omitted or forwarded (DOS/Rate#1871) + // ========================================================================= + const supaUrlEnvKey = ['NEXT_PUBLIC_SUPABASE', 'URL'].join('_'); + const supaAnonEnvKey = ['NEXT_PUBLIC_SUPABASE', 'ANON', 'KEY'].join('_'); + process.env[supaUrlEnvKey] = + process.env[supaUrlEnvKey] || 'https://stub.supabase.test'; + process.env[supaAnonEnvKey] = + process.env[supaAnonEnvKey] || 'stub-public-token'; + + const { getMasterProductPriceHistory } = await import('../rate-api'); + const rawHistoryRows1871 = [ + ...[35, 28, 21, 14, 7].map((d, idx) => ({ + id: 100 + idx, + product_id: 'offer-in-stock-1871', + price: 28_500_000, + price_original: 29_000_000, + recorded_at: isoDaysAgo(d), + source: 'crawler', + })), + { + id: 106, + product_id: 'offer-in-stock-1871', + price: 27_000_000, + price_original: 29_000_000, + recorded_at: isoDaysAgo(0), + source: 'crawler', + }, + // Sold-out normal_price offer priced ABOVE currentMinPrice (27.8M > 27.0M) + // with an old 21.5M dip that must never pollute the 30d floor or 90d low. + ...[35, 28, 21, 14, 7].map((d, idx) => ({ + id: 200 + idx, + product_id: 'offer-soldout-above-min', + price: d === 21 ? 21_500_000 : 27_800_000, + price_original: null, + recorded_at: isoDaysAgo(d), + source: 'crawler', + })), + // Discontinued normal_price offer priced EQUAL to currentMinPrice (27.0M) + // with an old 20.0M dip that must also be excluded when `offers` is omitted. + ...[35, 28, 14].map((d, idx) => ({ + id: 300 + idx, + product_id: 'offer-discontinued-at-min', + price: d === 28 ? 20_000_000 : 27_000_000, + price_original: null, + recorded_at: isoDaysAgo(d), + source: 'crawler', + })), + ]; + + const mkOffer1871 = ( + id: string, + merchantName: string, + priceCurrent: number, + priceOriginal: number | null, + availability: OfferAvailability | null + ) => ({ + id, + platform: 'shopee', + title: `iPhone 16 Pro Max ${id}`, + price_current: priceCurrent, + price_original: priceOriginal, + stock: availability === 'in_stock' ? 8 : 0, + rating_star: 4.9, + rating_count: 30, + url: `https://shopee.vn/${id}`, + availability, + merchant: { + id: `m-${id}`, + name: merchantName, + platform: 'shopee', + is_official: true, + rating_star: 4.9, + follower_count: 1000, + location: 'VN', + risk_score: 4, + dosafe_risk_score: 4, + review_risk_score: 4, + review_risk_breakdown: null, + }, + }); + + const offers1871 = [ + mkOffer1871( + 'offer-in-stock-1871', + 'Official Store In Stock', + 27_000_000, + 29_000_000, + 'in_stock' + ), + mkOffer1871( + 'offer-soldout-above-min', + 'Sold Out Store Above Min', + 27_800_000, + null, + 'out_of_stock' + ), + mkOffer1871( + 'offer-discontinued-at-min', + 'Discontinued Store At Min', + 27_000_000, + null, + 'discontinued' + ), + mkOffer1871( + 'offer-unknown-avail', + 'Unknown Availability Store', + 28_900_000, + null, + null + ), + ]; + + const origFetch1871 = globalThis.fetch; + let history1871; + try { + globalThis.fetch = (async (input: RequestInfo | URL) => { + const url = new URL( + typeof input === 'string' + ? input + : input instanceof URL + ? input.toString() + : input.url + ); + const limit = Number(url.searchParams.get('limit') ?? 1000); + const order = url.searchParams.get('order') ?? ''; + let rows = [...rawHistoryRows1871]; + if (limit === 1 && order.startsWith('price.asc')) { + rows.sort((a, b) => a.price - b.price); + rows = rows.slice(0, 1); + } else if (limit === 1 && order.startsWith('price.desc')) { + rows.sort((a, b) => b.price - a.price); + rows = rows.slice(0, 1); + } else { + rows.sort( + (a, b) => Date.parse(b.recorded_at) - Date.parse(a.recorded_at) + ); + } + return new Response(JSON.stringify(rows), { + status: 200, + headers: { 'content-type': 'application/json' }, + }); + }) as typeof fetch; + + history1871 = await getMasterProductPriceHistory('master-1871', offers1871); + } finally { + globalThis.fetch = origFetch1871; + } + + const inStockAnalysis1871: OfferDiscountAnalysis | undefined = + history1871.byOffer['offer-in-stock-1871']; + const soldOutAnalysis1871: OfferDiscountAnalysis | undefined = + history1871.byOffer['offer-soldout-above-min']; + const discontinuedAnalysis1871: OfferDiscountAnalysis | undefined = + history1871.byOffer['offer-discontinued-at-min']; + const unknownAvailAnalysis1871: OfferDiscountAnalysis | undefined = + history1871.byOffer['offer-unknown-avail']; + + assert.equal(history1871.currentMinPrice, 27_000_000); + assert.equal(inStockAnalysis1871?.availability, 'in_stock'); + assert.equal(soldOutAnalysis1871?.availability, 'out_of_stock'); + assert.equal(soldOutAnalysis1871?.verdict, 'normal_price'); + assert.ok((soldOutAnalysis1871?.price_current ?? 0) > 27_000_000); + assert.equal(discontinuedAnalysis1871?.availability, 'discontinued'); + assert.equal(discontinuedAnalysis1871?.verdict, 'normal_price'); + assert.equal(discontinuedAnalysis1871?.price_current, 27_000_000); + assert.equal(unknownAvailAnalysis1871?.availability, undefined); + + // Direct evaluator check with OfferDiscountAnalysis[] (product_id + availability) + const directByOfferAudit1871 = evaluateOmnibusPriceAudit({ + points: history1871.points, + currentPriceVnd: history1871.currentMinPrice, + claimedOriginalPriceVnd: 29_000_000, + mode: 'market', + referenceOffers: Object.values(history1871.byOffer), + referenceTimestampMs: ANCHOR_MS, + }); + assert.equal(directByOfferAudit1871.priorFloorPriceVnd, 28_500_000); + assert.equal(directByOfferAudit1871.verdict, 'verified_omnibus_reduction'); + assert.equal(directByOfferAudit1871.cycle90d.low90dVnd, 27_000_000); + assert.equal(directByOfferAudit1871.cycle90d.high90dVnd, 28_500_000); + assert.equal(directByOfferAudit1871.cycle90d.signal, 'buy_now_floor'); + + // SSR PriceHistorySection WITHOUT `offers` prop: sold-out/discontinued + // normal_price offers priced >= currentMinPrice are excluded from Omnibus + // prior-floor and 90-day cycle inputs via OfferDiscountAnalysis.availability. + for (const locale of ['vi', 'en', 'cs'] as const) { + const rawCatalog = JSON.parse( + readFileSync( + new URL(`../../../locales/${locale}.json`, import.meta.url), + 'utf8' + ) + ) as Record; + const omittedOffersHtml = renderToStaticMarkup( + React.createElement( + IntlProvider, + { + locale, + messages: pickClientMessages(rawCatalog, 'productDetail'), + timeZone: 'Asia/Ho_Chi_Minh', + }, + React.createElement(PriceHistorySection, { + productName: 'iPhone 16 Pro Max', + history: history1871, + }) + ) + ); + const cardIdx = omittedOffersHtml.indexOf( + 'data-testid="omnibus-price-audit-card"' + ); + const cardEndIdx = omittedOffersHtml.indexOf('role="group"', cardIdx); + const omnibusCardHtml = omittedOffersHtml.slice(cardIdx, cardEndIdx); + assert.ok( + cardIdx >= 0 && cardEndIdx > cardIdx, + `${locale}: PriceHistorySection renders omnibus card when offers is omitted` + ); + assert.ok( + omnibusCardHtml.includes(formatPriceVnd(28_500_000, locale)), + `${locale}: Omnibus 30d prior floor uses in-stock 28.5M floor (${formatPriceVnd(28_500_000, locale)})` + ); + assert.equal( + omnibusCardHtml.includes(formatPriceVnd(21_500_000, locale)), + false, + `${locale}: Sold-out normal_price offer above currentMinPrice must not leak 21.5M into Omnibus card` + ); + assert.equal( + omnibusCardHtml.includes(formatPriceVnd(20_000_000, locale)), + false, + `${locale}: Discontinued normal_price offer at currentMinPrice must not leak 20.0M into Omnibus card` + ); + assert.ok( + omnibusCardHtml.includes( + 'data-testid="omnibus-cycle-signal" class="fw-bold mb-1 text-success"' + ), + `${locale}: 90d cycle renders green buy_now_floor instead of Wait polluted by sold-out history` + ); + + // Explicitly in-stock offer priced slightly below a stale stored minPrice + // stays eligible when `offers` is forwarded. + const forwardedOffersHtml = renderToStaticMarkup( + React.createElement( + IntlProvider, + { + locale, + messages: pickClientMessages(rawCatalog, 'productDetail'), + timeZone: 'Asia/Ho_Chi_Minh', + }, + React.createElement(PriceHistorySection, { + productName: 'iPhone 16 Pro Max', + history: { + ...history1871, + currentMinPrice: 27_500_000, + }, + offers: offers1871, + }) + ) + ); + const fwdCardIdx = forwardedOffersHtml.indexOf( + 'data-testid="omnibus-price-audit-card"' + ); + const fwdCardEndIdx = forwardedOffersHtml.indexOf( + 'role="group"', + fwdCardIdx + ); + const fwdCardHtml = forwardedOffersHtml.slice(fwdCardIdx, fwdCardEndIdx); + assert.ok( + fwdCardHtml.includes(formatPriceVnd(28_500_000, locale)), + `${locale}: Forwarded offers keeps explicitly in_stock 27.0M offer history even when stored minPrice is 27.5M` + ); + } + + // Verify product detail route and ItemLazySizePanel forward `offers` to PriceHistorySection. + const pdvRouteSrc = readFileSync( + new URL('../../app/[locale]/smartphones/[slug]/page.tsx', import.meta.url), + 'utf8' + ); + const lazySizePanelSrc = readFileSync( + new URL( + '../../components/product/item/ItemLazySizePanel.tsx', + import.meta.url + ), + 'utf8' + ); + assert.match( + pdvRouteSrc, + / { + console.error(err); + process.exit(1); +}); diff --git a/apps/web/src/lib/omnibus-price-audit.ts b/apps/web/src/lib/omnibus-price-audit.ts index fba4d677a..a636873a9 100644 --- a/apps/web/src/lib/omnibus-price-audit.ts +++ b/apps/web/src/lib/omnibus-price-audit.ts @@ -81,6 +81,7 @@ export interface OmnibusAuditPointInput { export interface OmnibusReferenceOfferInput { readonly id?: string | null; + readonly product_id?: string | null; readonly price_current: number; readonly availability?: OfferAvailability | null; readonly implausiblyLow?: boolean | null; @@ -309,7 +310,13 @@ function buildOfferExclusionSets(params: { const inStockSized: { id: string; price_current: number }[] = []; const pricedAll: { rawId: string; id: string; price_current: number }[] = []; for (const off of safeRefOffers) { - const rawId = typeof off.id === 'string' ? off.id.trim() : ''; + const rawIdCandidate = + typeof off.id === 'string' && off.id.trim() + ? off.id + : typeof off.product_id === 'string' + ? off.product_id + : ''; + const rawId = rawIdCandidate.trim(); const id = normalizeOfferId(rawId) || rawId; const price = sanitizeOmnibusPriceVnd( off.price_current, diff --git a/apps/web/src/lib/rate-api.ts b/apps/web/src/lib/rate-api.ts index d45f871b0..d392bddb4 100644 --- a/apps/web/src/lib/rate-api.ts +++ b/apps/web/src/lib/rate-api.ts @@ -49,6 +49,7 @@ import { type OfferAvailability, toOfferAvailability, } from './product-market-stats'; +export type { OfferAvailability } from './product-market-stats'; export { computeWilsonLowerBound, evaluateReviewTrustAssessment, @@ -2162,6 +2163,7 @@ export interface OfferDiscountAnalysis { verdict: DiscountVerdictType; badge_label: string; explanation: string; + availability?: OfferAvailability; } export interface MasterProductPriceHistorySummary { @@ -2490,6 +2492,7 @@ export async function getMasterProductPriceHistory( let badgeLabel = 'Giá ổn định'; let explanation = `Giá bán hiện tại (${priceCurrent.toLocaleString('vi-VN')} ₫) khớp với mức trung vị lịch sử (${histMedian.toLocaleString('vi-VN')} ₫).`; + const offerAvailability = toOfferAvailability(off.availability); const offerUnavailable = isOfferUnavailable(off); if (priceOriginal && claimedDiscountPct >= 5) { // Case 1: Shop claims >= 8% discount, but current price is at or above historical median @@ -2545,6 +2548,7 @@ export async function getMasterProductPriceHistory( verdict, badge_label: badgeLabel, explanation, + ...(offerAvailability ? { availability: offerAvailability } : {}), }; } diff --git a/apps/web/src/lib/rate-domain.ts b/apps/web/src/lib/rate-domain.ts index a2cdb5fe1..56ba31b25 100644 --- a/apps/web/src/lib/rate-domain.ts +++ b/apps/web/src/lib/rate-domain.ts @@ -49,6 +49,7 @@ export type { MerchantProfileDetail, MerchantRiskBreakdown, MerchantSummary, + OfferAvailability, OfferDiscountAnalysis, ParsedEcommerceUrl, PriceHistoryPoint, diff --git a/apps/web/src/server/rate/index.ts b/apps/web/src/server/rate/index.ts index c14300404..ce0a1cf0f 100644 --- a/apps/web/src/server/rate/index.ts +++ b/apps/web/src/server/rate/index.ts @@ -475,7 +475,13 @@ export const getCachedMasterProductPriceHistory = cache( o.price_original > 0 ? Math.round(o.price_original) : ''; - return `${sanitizeCachedEntityId(o.id)}:${safeCur}:${safeOrig}`; + const safeAvail = + o.availability === 'in_stock' || + o.availability === 'out_of_stock' || + o.availability === 'discontinued' + ? o.availability + : ''; + return `${sanitizeCachedEntityId(o.id)}:${safeCur}:${safeOrig}:${safeAvail}`; }) .join('|')}` : 'offers:auto'; diff --git a/apps/web/src/server/rate/item-page.ts b/apps/web/src/server/rate/item-page.ts index 4b7b696f8..032b8bf5b 100644 --- a/apps/web/src/server/rate/item-page.ts +++ b/apps/web/src/server/rate/item-page.ts @@ -109,7 +109,8 @@ const _getCachedUnknownByOffer = cache( .update( offers .map( - (o) => `${o.id}:${o.price_current}:${o.price_original ?? ''}` + (o) => + `${o.id}:${o.price_current}:${o.price_original ?? ''}:${o.availability ?? ''}` ) .join('|') ) From e291297e35570963bd85ecaaa3ef441388a85017 Mon Sep 17 00:00:00 2001 From: JOY <5027251+JOY@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:53:11 +0700 Subject: [PATCH 2/2] fix(web): harden reference offer availability and cache key hashing Preserve explicit unavailability on blank-ID reference offers, filter malformed offers entries before fallback, check plausible in-stock offers for allKnownOffersUnavailable, and hash all offers in getCachedMasterProductPriceHistory (Refs #1871). --- .../price-history/PriceHistorySection.tsx | 159 ++++++++++++------ apps/web/src/lib/__tests__/sale-state.test.ts | 133 +++++++++++++++ apps/web/src/server/rate/index.ts | 51 +++--- apps/web/src/server/rate/item-page.ts | 3 +- 4 files changed, 271 insertions(+), 75 deletions(-) diff --git a/apps/web/src/components/price-history/PriceHistorySection.tsx b/apps/web/src/components/price-history/PriceHistorySection.tsx index 2b373c5b7..665612707 100644 --- a/apps/web/src/components/price-history/PriceHistorySection.tsx +++ b/apps/web/src/components/price-history/PriceHistorySection.tsx @@ -19,6 +19,7 @@ import { evaluateOmnibusPriceAudit, formatOmnibusAuditCopy, resolveOmnibusReferenceAnchorMs, + sanitizeOmnibusPriceVnd, type OmnibusPriceAuditResult, type OmnibusReferenceOfferInput, type OmnibusVerdictTranslator, @@ -26,6 +27,7 @@ import { import { minimumListingPriceVnd, normalizeOfferId, + plausibleOffers, } from '@repo/shared-data/rules'; import { isOfferUnavailable, @@ -680,6 +682,16 @@ export default function PriceHistorySection({ return Math.round(raw); }, [history.currentMinPrice]); + const safeOffersInput = useMemo( + () => + Array.isArray(offers) + ? offers.filter((off): off is OmnibusReferenceOfferInput => + Boolean(off && typeof off === 'object' && !Array.isArray(off)) + ) + : [], + [offers] + ); + // Identify unavailable (sold-out / discontinued) offers from explicit `offers`, // explicit `availability` on `offerAnalyses`, or fallback heuristics when // availability is unknown (prices strictly below the verified in-stock minimum, @@ -696,8 +708,8 @@ export default function PriceHistorySection({ if (canon) ids.add(canon); }; - const explicitAvailFromOffers = new Map(); - const setOfferAvail = ( + const setAvailInMap = ( + map: Map, rawId: string | null | undefined, avail: OfferAvailability ) => { @@ -707,29 +719,58 @@ export default function PriceHistorySection({ const canon = normalizeOfferId(trimmed); for (const key of [rawId, trimmed, canon]) { if (!key) continue; - const prev = explicitAvailFromOffers.get(key); + const prev = map.get(key); if (!prev || isOfferUnavailable({ availability: avail })) { - explicitAvailFromOffers.set(key, avail); + map.set(key, avail); } } }; - if (Array.isArray(offers)) { - for (const off of offers) { - if (!off || typeof off !== 'object') continue; - const rawId = - typeof off.id === 'string' && off.id.trim() - ? off.id - : typeof off.product_id === 'string' - ? off.product_id - : null; - const avail = toOfferAvailability(off.availability); - if (avail) { - setOfferAvail(rawId, avail); - if (isOfferUnavailable({ availability: avail })) { - addId(rawId); - } + const explicitAvailFromAnalyses = new Map(); + for (const oa of offerAnalyses) { + const avail = toOfferAvailability(oa.availability); + if (avail) { + setAvailInMap(explicitAvailFromAnalyses, oa.product_id, avail); + } + } + + const explicitAvailFromOffers = new Map(); + for (const off of safeOffersInput) { + const rawId = + typeof off.id === 'string' && off.id.trim() + ? off.id + : typeof off.product_id === 'string' && off.product_id.trim() + ? off.product_id + : null; + const avail = toOfferAvailability(off.availability); + if (avail) { + setAvailInMap(explicitAvailFromOffers, rawId, avail); + if (isOfferUnavailable({ availability: avail })) { + addId(rawId); + } + continue; + } + if (!rawId) continue; + const trimmed = rawId.trim(); + const canon = normalizeOfferId(trimmed); + const oaAvail = + explicitAvailFromAnalyses.get(rawId) ?? + explicitAvailFromAnalyses.get(trimmed) ?? + (canon ? explicitAvailFromAnalyses.get(canon) : undefined); + if (oaAvail) { + if (isOfferUnavailable({ availability: oaAvail })) { + addId(rawId); } + continue; + } + const p = Number(off.price_current); + if ( + safeCurrentMinPrice != null && + Number.isFinite(p) && + p > 0 && + Math.round(p) < safeCurrentMinPrice + ) { + addId(rawId); } } @@ -781,7 +822,7 @@ export default function PriceHistorySection({ } } return ids; - }, [offerAnalyses, offers, safeCurrentMinPrice]); + }, [offerAnalyses, safeCurrentMinPrice, safeOffersInput]); const isUnavailId = useCallback( (id: string) => @@ -792,50 +833,68 @@ export default function PriceHistorySection({ ); const effectiveReferenceOffers = useMemo(() => { - if (Array.isArray(offers) && offers.length > 0) { - return offers - .filter((off): off is OmnibusReferenceOfferInput => - Boolean(off && typeof off === 'object' && !Array.isArray(off)) - ) - .map((off) => { - const rawId = - typeof off.id === 'string' && off.id.trim() - ? off.id - : typeof off.product_id === 'string' - ? off.product_id - : undefined; - const explicit = toOfferAvailability(off.availability); - const unavailable = Boolean(rawId && isUnavailId(rawId)); - return { - id: rawId, - price_current: off.price_current, - availability: unavailable - ? explicit && isOfferUnavailable({ availability: explicit }) - ? explicit - : ('out_of_stock' as const) - : ('in_stock' as const), - implausiblyLow: off.implausiblyLow, - }; - }); + if (safeOffersInput.length > 0) { + return safeOffersInput.map((off) => { + const rawId = + typeof off.id === 'string' && off.id.trim() + ? off.id + : typeof off.product_id === 'string' && off.product_id.trim() + ? off.product_id + : undefined; + const explicit = toOfferAvailability(off.availability); + const explicitUnavailable = + explicit != null && isOfferUnavailable({ availability: explicit }); + const unavailable = + explicitUnavailable || Boolean(rawId && isUnavailId(rawId)); + return { + id: rawId, + price_current: off.price_current, + availability: unavailable + ? explicitUnavailable + ? explicit + : ('out_of_stock' as const) + : ('in_stock' as const), + implausiblyLow: off.implausiblyLow, + }; + }); } return offerAnalyses.map((oa) => { const explicit = toOfferAvailability(oa.availability); + const explicitUnavailable = + explicit != null && isOfferUnavailable({ availability: explicit }); + const unavailable = explicitUnavailable || isUnavailId(oa.product_id); return { id: oa.product_id, price_current: oa.price_current, - availability: isUnavailId(oa.product_id) - ? explicit && isOfferUnavailable({ availability: explicit }) + availability: unavailable + ? explicitUnavailable ? explicit : ('out_of_stock' as const) : ('in_stock' as const), }; }); - }, [isUnavailId, offerAnalyses, offers]); + }, [isUnavailId, offerAnalyses, safeOffersInput]); const allKnownOffersUnavailable = useMemo(() => { if (effectiveReferenceOffers.length === 0) return false; - return effectiveReferenceOffers.every((off) => isOfferUnavailable(off)); - }, [effectiveReferenceOffers]); + const inStockSized: { id: string; price_current: number }[] = []; + effectiveReferenceOffers.forEach((off, idx) => { + if (isOfferUnavailable(off) || off.implausiblyLow === true) return; + const price = sanitizeOmnibusPriceVnd( + off.price_current, + minValidPriceVnd + ); + if (price == null) return; + inStockSized.push({ + id: + typeof off.id === 'string' && off.id.trim() + ? off.id.trim() + : `__idx_${idx}`, + price_current: price, + }); + }); + return plausibleOffers(inStockSized).length === 0; + }, [effectiveReferenceOffers, minValidPriceVnd]); // Historical anchor uses the exact same evidence-eligibility rules as the // Omnibus evaluator so rows below `minValidPriceVnd`, `live_listing` rows, diff --git a/apps/web/src/lib/__tests__/sale-state.test.ts b/apps/web/src/lib/__tests__/sale-state.test.ts index f0dc0361c..5e92eb7d2 100644 --- a/apps/web/src/lib/__tests__/sale-state.test.ts +++ b/apps/web/src/lib/__tests__/sale-state.test.ts @@ -1259,6 +1259,139 @@ async function main() { fwdCardHtml.includes(formatPriceVnd(28_500_000, locale)), `${locale}: Forwarded offers keeps explicitly in_stock 27.0M offer history even when stored minPrice is 27.5M` ); + + // All real offers sold out (including missing-ID sold-out entry) alongside + // an in-stock sub-floor accessory/bait listing suppresses phantom Omnibus card + // even when cached currentMinPrice is still non-null. + const allSoldOutPlusBaitHtml = renderToStaticMarkup( + React.createElement( + IntlProvider, + { + locale, + messages: pickClientMessages(rawCatalog, 'productDetail'), + timeZone: 'Asia/Ho_Chi_Minh', + }, + React.createElement(PriceHistorySection, { + productName: 'iPhone 16 Pro Max', + history: history1871, + offers: [ + { + id: '', + product_id: ' ', + price_current: 28_000_000, + availability: 'out_of_stock', + }, + { + id: 'offer-in-stock-1871', + price_current: 27_000_000, + availability: 'discontinued', + }, + { + id: 'offer-subfloor-bait', + price_current: 500_000, + availability: 'in_stock', + }, + ], + }) + ) + ); + assert.equal( + allSoldOutPlusBaitHtml.includes('data-testid="omnibus-price-audit-card"'), + false, + `${locale}: Suppresses Omnibus card when only sold-out offers and sub-floor bait remain` + ); + } + + // Malformed non-empty `offers` array falls back cleanly to `byOffer` analyses, + // and `offers` entries with `availability: null` absent from `byOffer` but + // priced strictly below `currentMinPrice` are excluded from Omnibus floor. + { + const rawViCatalog = JSON.parse( + readFileSync(new URL('../../../locales/vi.json', import.meta.url), 'utf8') + ) as Record; + const malformedOffersHtml = renderToStaticMarkup( + React.createElement( + IntlProvider, + { + locale: 'vi', + messages: pickClientMessages(rawViCatalog, 'productDetail'), + timeZone: 'Asia/Ho_Chi_Minh', + }, + React.createElement(PriceHistorySection, { + productName: 'iPhone 16 Pro Max', + history: history1871, + offers: [null as never], + }) + ) + ); + const malCardStart = malformedOffersHtml.indexOf( + 'data-testid="omnibus-price-audit-card"' + ); + const malCardStop = malformedOffersHtml.indexOf( + 'role="group"', + malCardStart + ); + const malOmnibusCardHtml = malformedOffersHtml.slice( + malCardStart, + malCardStop + ); + assert.ok( + malCardStart >= 0 && + malOmnibusCardHtml.includes(formatPriceVnd(28_500_000, 'vi')) + ); + assert.equal( + malOmnibusCardHtml.includes(formatPriceVnd(21_500_000, 'vi')), + false + ); + + const unknownExtraOfferHtml = renderToStaticMarkup( + React.createElement( + IntlProvider, + { + locale: 'vi', + messages: pickClientMessages(rawViCatalog, 'productDetail'), + timeZone: 'Asia/Ho_Chi_Minh', + }, + React.createElement(PriceHistorySection, { + productName: 'iPhone 16 Pro Max', + history: { + ...history1871, + points: [ + ...history1871.points, + ...[35, 21, 7].map((d, idx) => ({ + id: 900 + idx, + product_id: 'offer-untracked-below-min', + merchant_name: 'Untracked Shop', + platform: 'shopee', + is_official: false, + price: 22_000_000, + price_original: null, + recorded_at: isoDaysAgo(d), + source: 'crawler', + })), + ], + }, + offers: [ + ...offers1871, + { + id: 'offer-untracked-below-min', + price_current: 22_000_000, + availability: null, + }, + ], + }) + ) + ); + const cardStart = unknownExtraOfferHtml.indexOf( + 'data-testid="omnibus-price-audit-card"' + ); + const cardStop = unknownExtraOfferHtml.indexOf('role="group"', cardStart); + assert.equal( + unknownExtraOfferHtml + .slice(cardStart, cardStop) + .includes(formatPriceVnd(22_000_000, 'vi')), + false + ); } // Verify product detail route and ItemLazySizePanel forward `offers` to PriceHistorySection. diff --git a/apps/web/src/server/rate/index.ts b/apps/web/src/server/rate/index.ts index ce0a1cf0f..7b5383504 100644 --- a/apps/web/src/server/rate/index.ts +++ b/apps/web/src/server/rate/index.ts @@ -460,30 +460,33 @@ export const getCachedMasterProductPriceHistory = cache( ? existingOffers.filter((o) => Boolean(o && typeof o === 'object')) : undefined; const offersKey = safeOffers - ? `offers:${safeOffers.length}:${safeOffers - .slice(0, 20) - .map((o) => { - const safeCur = - typeof o.price_current === 'number' && - Number.isFinite(o.price_current) && - o.price_current > 0 - ? Math.round(o.price_current) - : 0; - const safeOrig = - typeof o.price_original === 'number' && - Number.isFinite(o.price_original) && - o.price_original > 0 - ? Math.round(o.price_original) - : ''; - const safeAvail = - o.availability === 'in_stock' || - o.availability === 'out_of_stock' || - o.availability === 'discontinued' - ? o.availability - : ''; - return `${sanitizeCachedEntityId(o.id)}:${safeCur}:${safeOrig}:${safeAvail}`; - }) - .join('|')}` + ? `offers:${safeOffers.length}:${createHash('sha256') + .update( + safeOffers + .map((o) => { + const safeCur = + typeof o.price_current === 'number' && + Number.isFinite(o.price_current) && + o.price_current > 0 + ? Math.round(o.price_current) + : 0; + const safeOrig = + typeof o.price_original === 'number' && + Number.isFinite(o.price_original) && + o.price_original > 0 + ? Math.round(o.price_original) + : ''; + const safeAvail = + o.availability === 'in_stock' || + o.availability === 'out_of_stock' || + o.availability === 'discontinued' + ? o.availability + : ''; + return `${sanitizeCachedEntityId(o.id)}:${safeCur}:${safeOrig}:${safeAvail}`; + }) + .join('|') + ) + .digest('hex')}` : 'offers:auto'; return withRateDataCache( async (id: string) => { diff --git a/apps/web/src/server/rate/item-page.ts b/apps/web/src/server/rate/item-page.ts index 032b8bf5b..94c29e912 100644 --- a/apps/web/src/server/rate/item-page.ts +++ b/apps/web/src/server/rate/item-page.ts @@ -20,6 +20,7 @@ import type { RadarSignal } from '@/lib/deal-radar'; import { isOfferUnavailable, productMarketStats, + toOfferAvailability, } from '@/lib/product-market-stats'; import type { ProductSpecifications } from '@repo/shared-data'; import type { ItemSizePanelData } from '@/lib/item-size-panel'; @@ -110,7 +111,7 @@ const _getCachedUnknownByOffer = cache( offers .map( (o) => - `${o.id}:${o.price_current}:${o.price_original ?? ''}:${o.availability ?? ''}` + `${o.id}:${o.price_current}:${o.price_original ?? ''}:${toOfferAvailability(o.availability) ?? ''}` ) .join('|') )