90 Commits

Author SHA1 Message Date
af20a4aa57 fix(lifecycle): status_changed_by uuid → text (Süper Panel founderId nanoid)
Some checks failed
QA Gate (P0/P1) / Test affected app (pull_request) Has been cancelled
Süper Panel suspend/ban aksiyonları founderId olarak panelin Better Auth
kullanıcı ID'sini (32 karakterlik nanoid) gönderiyor. users.status_changed_by
uuid tipinde olduğu için Postgres 'invalid input syntax for type uuid' ile
düşüyor ve kullanıcı askıya alınamıyordu. Alan FK'sız salt audit alanı;
text'e genişletildi, mevcut UUID değerleri korunuyor.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-11 12:34:24 +03:00
c12b2992f9 Merge pull request 'fix(analytics): CSP Google Ads tag + conversion domainleri (ASIL conversion bugu)' (#256) from dev into main 2026-08-04 16:54:36 +03:00
57d16b9aea fix(analytics): CSP'ye kalan enhanced-conversion endpoint'lerini ekle
Some checks failed
QA Gate (P0/P1) / Test affected app (pull_request) Has been cancelled
Dev testinde ana conversion ping'i (googleadservices/pagead/conversion) geçti
ama ad.doubleclick.net (ccm/collect enhanced) + google.com.tr (TR yerelleştirilmiş
1p-conversion) hâlâ bloklanıyordu. img-src/connect-src'e eklendi.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-04 16:53:48 +03:00
eb277cd55a fix(analytics): CSP'ye Google Ads tag + conversion domain'lerini ekle
CSP script-src googletagmanager.com İÇERMİYORDU → gtag.js hiç yüklenmiyordu →
gtag config/conversion event'i çalışmıyor, _gcl_aw linker cookie set olmuyor,
conversion ping'i Google'a hiç gitmiyor → haftalardır panelde 0 dönüşüm (doğru
AW id + label + kanonik gtag'e rağmen). ASIL bloker buydu — gtag shim (6c936d5)
+ OAuth (685c6af) fix'leri gerekliydi ama tek başına yetmezdi.
- script-src += www.googletagmanager.com
- img-src/connect-src += google.com, googleadservices.com, googleads.g.doubleclick.net
Meta Pixel worker-src ve Sentry ingest ile aynı sınıf CSP-blocking bug.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-04 16:47:22 +03:00
8346a1db8e Merge pull request 'perf(prefetch): pcat gunluk butce 30k->45k' (#255) from dev into main 2026-08-01 14:32:44 +03:00
2df73e6a48 perf(prefetch): pcat günlük bütçe 30k→45k (main lane 36k, fast lane 9k rezerv)
Some checks failed
QA Gate (P0/P1) / Test affected app (pull_request) Has been cancelled
Gate fix (PR#254) prod'da doğrulandı: pressure=56 (eskiden backlog=11495),
bütçesi dolan kaynak eligible'dan düşüyor — runaway guard'ları canlı. Bütçenin
kalan tek riski bant genişliği maliyeti.

45k gerekçesi: guard'ı doğuran 2026-07-09 olayı ~74k çağrı/~10 GB idi; 45k onun
%61'i (~6 GB/gün). DAILY_FAST_RESERVE ile backfill main lane 36k alır = eski
efektif 30k'ya göre +%20, kullanıcıya 9k rezerv kalır. Burst hızı DEĞİŞMİYOR
(pcat 90/dk) → per-IP ban baskısı aynı, sadece tempo günün daha uzun bölümünde
sürüyor. Rollback: bir saatte >2 pcat HTTP 402 → 30_000'e dön.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-01 14:32:42 +03:00
c21472d930 Merge pull request 'fix(prefetch): Phase-2 kilidini ac (pressure/total gate) + tamamlanma muhasebesi' (#254) from dev into main 2026-08-01 14:22:23 +03:00
3597b03c4f fix(prefetch): Phase-2 kilidini aç (pressure vs total gate) + tamamlanma muhasebesi
Some checks failed
QA Gate (P0/P1) / Test affected app (pull_request) Has been cancelled
Sorun (2026-08-01): wait=0/active=0 iken scan backlog=11495 hesaplıyordu — hepsi
günlük-bütçe ile ertesi gün 00:00'a park edilmiş pcat job'ı. backlog>maxBacklog
olduğu için Phase-2 günün çoğunda askıdaydı; 2143 kısmi araç ilerlemiyordu.

Adversarial analiz kritik uyarı verdi: delayed'ı gate'ten çıkarmak TEK BAŞINA
470k runaway'i tekrarlar (üretim ~288k job/gün vs bütçe 65k/gün; bütçe-defer'leri
skipAttempt ile attempts tüketmediğinden asla düşmez). Bu yüzden üretim kaynağında
kesiliyor + ikinci tavan ekleniyor:

- Gate ikiye ayrıldı: pressure (waiting+active+10dk içinde vadesi gelen delayed,
  HER İKİ kuyruk) vs maxBacklog; total (tüm bekleyen) vs HARD_MAX_TOTAL_JOBS=50k.
  zcount BullMQ delayed ZSET score'u (dueMs*4096+seq) ile; hata halinde fail-CLOSED.
- ÜRETİMİ KES: scan, günlük main-lane bütçesi dolmuş kaynağı eligible'dan düşürür.
- Admission control JOB cinsinden (EST_JOBS_PER_VEHICLE=400), araç cinsinden değil.
- Günlük bütçe lane-aware (fast lane'e %20 rezerv) + READ-then-INCR (sayaç artık
  defer'lerle şişmiyor; 48531 vs 30000 gözlemi) + 45dk jitter (thundering herd).
- KÖK NEDEN: addJob artık boolean, queueCategoryJob sayı döndürüyor; progress.total
  yalnız GERÇEKTEN kuyruğa giren job'ı sayıyor. Şişmiş total zinciri asla
  "finished"a ulaştırmıyordu → araç fullyFetched işaretlenmiyor → scan sonsuza dek
  yeniden seçiyordu (~25/gün platosu). processInit queued===0 ise finalizeVehicle.
- prefetch:scheduled:<id> ÇAKIŞMASI: backfill artık :backfill: namespace'i yazıyor;
  eski 6h TTL kullanıcının fresh-decode fast-lane init'ini sessizce atlatıyordu.
  TTL 6h→36h (bütçe-park edilmiş zincir ~24h yaşıyor).
- Phase-2 artık kalıcı vehicles.fullyFetched'i hedefliyor (efemeral marker değil).
- CATEGORY_CAP DB'den ölçülüyor (her processInit'te sıfırlanan sayaçtan değil).

537 test geçti. Bütçe artışı (PREFETCH_DAILY_PCAT) BU PR'da DEĞİL — ayrı adım.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-01 14:21:44 +03:00
2cda50f9af Merge pull request 'fix(analytics): gtag shim kanonik arguments push' (#253) from dev into main 2026-08-01 10:09:43 +03:00
6c936d546b fix(analytics): gtag shim kanonik arguments push — tüm conversion takibi kırıktı
Some checks failed
QA Gate (P0/P1) / Test affected app (pull_request) Has been cancelled
initGoogleAds gtag shim'i array push ediyordu ((...args) => dataLayer.push(args));
gtag.js komut olarak sadece `arguments` nesnesini işler, array'i inert dataLayer
verisi sayar → config/event HİÇ çalışmıyordu → _gcl_aw linker cookie'si set
olmuyor, conversion ping'i Google'a gitmiyor, panelde 14 günde 0 dönüşüm (email
kayıtları dahil — sadece OAuth değil). Google'ın kanonik snippet formuna
(function gtag(){dataLayer.push(arguments)}) döndürüldü. OAuth post-auth fix'iyle
(685c6af) birlikte email+OAuth tüm kayıtlar artık ateşler + doğru atfeder.
Doğrulama: headless test gtag'i teyit edemez (Google bot-baskılaması); kesin
kanıt gerçek tarayıcıda kaydın panele düşmesi.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-01 10:09:28 +03:00
bf0cc4e96c Merge pull request 'fix(analytics): OAuth Google Ads sign-up conversion' (#252) from dev into main 2026-08-01 09:16:41 +03:00
685c6af3ed fix(analytics): OAuth kayıtlarında Google Ads sign-up conversion'ı ateşle
Some checks failed
QA Gate (P0/P1) / Test affected app (pull_request) Has been cancelled
Conversion sadece register.tsx email path'inde ateşleniyordu; Google OAuth
signup'lar (register + login Google butonu) hiç ateşlemiyordu → ölçüm: paid-
kaynaklı kayıtların ~%79'u OAuth, Google Ads'e görünmüyordu, Max Conversions
sinyalsiz optimize ediyordu. Evrensel post-auth bileşeni (google-ads-signup-
conversion.tsx, __root'a mount) yeni kullanıcıda (createdAt < 30dk) conversion'ı
bir kez ateşler; transaction_id signup_<userId> Google tarafında dedup eder,
register.tsx guard'ı email path'in çift-ateşini önler. _gcl_aw cookie OAuth
roundtrip'inde korunduğu için atıf doğru. Playwright 6/6.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-01 09:16:20 +03:00
95818b2501 Merge pull request 'feat(growth): B2B segment kapısı + funnel-bucket A/B (Kova B)' (#251) from dev into main 2026-07-29 11:03:48 +03:00
55b4cd38e9 feat(growth): B2B segment kapısı + funnel-bucket A/B deneyi (Kova B)
Some checks failed
QA Gate (P0/P1) / Test affected app (pull_request) Has been cancelled
Fix (herkes, flag'siz): evrensel post-auth segment kapısı (segment-gate.tsx).
Kayıtların ~%41'i segmentsizdi çünkü login.tsx Google OAuth segment adımını
atlıyordu. Yeni kullanıcıya zorunlu (açığı kapatır), mevcut segmentsize
7g-cooldown'lu yumuşak prompt (~538 backfill). Segment localStorage +
PostHog person prop (b2b_segment); backend persist faz 2.

Kova B (funnel-bucket flag, b2b_qualified): trial-value-upsell'e segmente-özel
Meta-kanıtlı kopya (iade / yanlış-parça / sınırsız-şase). Flag SADECE banner
görünürken okunur → deney maruziyeti = gerçekten gören aktif trial'lar.
vehicle_owner / bilinmeyen segment → nötr control kopya (ürün kararı).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-27 17:26:19 +03:00
c0045fa372 Merge pull request 'feat(prefetch): kalici vehicles.fully_fetched kolonu (migration 0034)' (#250) from dev into main 2026-07-25 10:44:19 +03:00
6610bdf720 feat(prefetch): kalıcı vehicles.fully_fetched kolonu (güvenilir tamlık ölçümü)
Some checks failed
QA Gate (P0/P1) / Test affected app (pull_request) Has been cancelled
Redis prefetch:complete:* 21g TTL'li → "% tam çekilmiş"i güvenilir ölçemiyorduk.
Migration 0034: vehicles'a fully_fetched (bool, default false) + fully_fetched_at
(ts) + index. incrementCompleted chain parça ile bitince kalıcı flag'i set eder
(Redis marker'a EK — operasyonel skip mantığı değişmedi). fully_fetched_at her
re-drill tamamlanışında güncellenir (son-doğrulanma). Idempotent SQL.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-25 10:40:40 +03:00
8c1ee15fac Merge pull request 'perf(prefetch): backfill günlük bütçe (storm guard)' (#249) from dev into main 2026-07-16 13:32:47 +03:00
ed8a6ce6e9 perf(prefetch): backfill'e per-source günlük bütçe (storm guard)
Some checks failed
QA Gate (P0/P1) / Test affected app (pull_request) Has been cancelled
Per-dakika rate cap'i (pcat 90/dk) burst'ü sınırlıyor ama günlük TOPLAM'ı değil —
bir kaynak saatlerce tavanda çalışıp proxy bütçesini boşaltabiliyor (2026-07-09:
backlog drain pcat'i ~74k çağrı / ~10 GB'a çıkardı). SOURCE_DAILY_MAX eklendi:
UTC-gün fixed-window Redis sayacı; kaynak günlük bütçeyi aşınca backfill job'ları
pencere dönene kadar ertelenir. Kullanıcı decode'ları etkilenmez (worker'dan
geçmiyor). Dakikalık gate'ten SONRA sayılır → rate-limitli retry'lar şişirmez.

Default (env-tunable): pcat 30k, emex 20k, pl24 15k/gün. Backlog drain'i
hızlandırmak için yükselt, bütçeyi daha çok korumak için düşür.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-16 13:32:34 +03:00
8a4dd6e10e Merge pull request 'chore(proxy): DataImpulse birincil, Floxy default kaldır' (#248) from dev into main 2026-07-16 13:04:30 +03:00
bf834b8f41 chore(proxy): DataImpulse'i birincil yap, Floxy default'unu kaldır
Some checks failed
QA Gate (P0/P1) / Test affected app (pull_request) Has been cancelled
Floxy kalıcı olarak devre dışı (bakiye/tünel ölü — pcat+emex loglarında sürekli
"Floxy unhealthy → DataImpulse failover"). Floxy-primary her çağrıda önce bir
başarısız deneme yakıp sonra failover ediyordu. DataImpulse zaten kanıtlanmış
çalışıyor (call-leg %97,6).

PCAT_PROXY_PROVIDER ve EMEX_PROXY_PROVIDER default'ları floxy→dataimpulse
(pcat auth + emex browser + emex HTTP ayağı). Floxy hâlâ env ile seçilebilir
(PCAT_PROXY_PROVIDER=floxy / EMEX_PROXY_PROVIDER=floxy); failover makinesi
dormant kalıyor.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-16 13:04:15 +03:00
bd134bba06 Merge pull request 'perf(pcat): capture widget asset cache — ~%90 capture bant genişliği' (#247) from dev into main 2026-07-16 12:52:59 +03:00
7fd486855f perf(pcat): capture'da widget asset'lerini cache'le — ~%90 capture bant genişliği
Some checks failed
QA Gate (P0/P1) / Test affected app (pull_request) Has been cancelled
Her JWT capture yeni context (boş cache) açıp aynı widget JS/CSS'ini residential
proxy'den yeniden indiriyordu — ölçüldü ~2,2 MB/capture, %93'ü static (en büyüğü
tüm sitelerde ORTAK `.../v3/bundle_<hash>.js`, 603 KB). ~3-4k capture/gün ile bu
en büyük kaçınılabilir proxy maliyeti (~20 GB/15g), sıfır ban riski.

URL-anahtarlı, disk-destekli (hot in-memory + best-effort disk) cache eklendi.
Sadece versiyonlu static JS/CSS cache'lenir (hash/`?_=` → invalidation otomatik);
token XHR (/v3/api/proxy/*) ve HTML document HER ZAMAN canlı geçer. HIT'te sıfır
proxy byte'ı; MISS'te bir kez route.fetch (context proxy'sinden) + sakla + servis.
PCAT_ASSET_CACHE=false ile redeploysuz kapatılabilir (kill switch).

Doğrulama (autotrade.md + e-trak.ru, gerçek yükleme, 2 ardışık capture):
warm capture canlı trafiği %89-91 düştü VE token XHR ikisinde de atıldı — yani
cache'ten JS servisi widget'ı bozmuyor (geçen capture-blocking olayının tersi).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-16 12:47:10 +03:00
8d07d9a31a Merge pull request 'fix(vinpin): blank Dialogys header retries instead of definitive not_found' (#246) from dev into main 2026-07-16 07:59:39 +03:00
fdbaaf375f fix(vinpin): blank Dialogys header → ambiguous (retry), not definitive not_found
Some checks failed
QA Gate (P0/P1) / Test affected app (pull_request) Has been cancelled
A blank header region means the Dialogys vehicle result never rendered (transient/
slow), NOT a genuine miss — a decodable Renault (Megane) read "" here and was wrongly
returned not_found (made definitive by the Rpartstore-down gate). Return ambiguous so
the caller's cheap in-session reset retries; a real empty-form miss just exhausts the
bounded retries. A NON-empty unparseable header (old R19's garbled parts screen) stays
a fast definitive not_found.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-16 07:59:32 +03:00
ebbdb22e33 Merge pull request 'chore(compose): VINPIN_RPARTSTORE_ENABLED env ref' (#245) from dev into main 2026-07-16 07:41:23 +03:00
8e4581f1b5 chore(compose): add VINPIN_RPARTSTORE_ENABLED env ref (api+worker)
So the flag reaches the container (Coolify only injects compose-referenced ${VAR}).
Default true = unchanged; set false during a Rpartstore outage.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-16 07:41:16 +03:00
679664d7b0 Merge pull request 'feat(vinpin): VINPIN_RPARTSTORE_ENABLED flag — skip Rpartstore during outage (+pcat capture fix)' (#244) from dev into main 2026-07-16 07:39:43 +03:00
c3ea03db03 feat(vinpin): VINPIN_RPARTSTORE_ENABLED flag skips Rpartstore during known outage
Some checks failed
QA Gate (P0/P1) / Test affected app (pull_request) Has been cancelled
Rpartstore is DOWN upstream. Every Renault decode still tried to OPEN it
first → launch-error, stuck "Loading application..." app (dirty-resume for
the next decode), ~30-50s burned, and the in-memory down-cooldown resets on
every worker restart so the first decode after each restart repaid the full
cost. That overhead pushed decodes over VINPIN_DECODE_BUDGET_MS → budget
abort → sessionPoisoned → cascade.

Add a persistent kill-switch: VINPIN_RPARTSTORE_ENABLED=false makes BOTH
Renault paths (warm warmRenaultDecode + cold runRenaultFlow) skip opening
Rpartstore entirely and route straight to Dialogys — mirroring the existing
rpartstoreInCooldown() skip but surviving worker restarts. Flag-disabled is
treated as "Rpartstore unavailable" exactly like cooldown, so primaryRan
stays false and a clean Dialogys not_found is definitive (no retry thrash).
Also gated the _warmUp Rpartstore-open so a future warm session with the
flag off pays no launch cost / leaves no stray app.

DEFAULT true (only the exact string "false" disables) → behaviour with the
flag unset is completely unchanged. tsc clean; vinpin unit tests green
(+3 flag tests: warm/cold skip + Dialogys-definitive, and default-true still
attempts Rpartstore).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-16 07:36:20 +03:00
7ec4fb9297 Merge pull request 'fix(pcat): capture route'unu bilinen-iyi'ye döndür — prod token capture kurtar' (#243) from dev into main
Reviewed-on: #243
2026-07-16 07:00:24 +03:00
6df9c18efb fix(pcat): capture route'unu bilinen-iyi'ye döndür — prod token capture kurtar
Some checks failed
QA Gate (P0/P1) / Test affected app (pull_request) Has been cancelled
0f2126d'deki agresif capture blocking (stylesheet + yastatic/google-font/ad
domain'leri) prod'da token capture'ı öldürdü: dataimpulse ile 425→0 capture/
saat, tam deploy anında (03:40 UTC), hepsi capture_timeout. RU katalog widget'ı
init olup /v3/api/proxy XHR'ını atmak için CSS'ine ve Yandex-hosted runtime'ına
ihtiyaç duyuyor. Aynı deploy'da emex (HTML-scrape, widget yok) aynı dataimpulse
üzerinden sağlıklı kaldı → sorun pcat-capture'a özgü.

pcat capture blocking'i orijinaline döndürüldü (image/font/media + tracker'lar)
— resim engellemesi zaten çalışıyordu, korunur. Emex blocking (kanıtlanmış
güvenli) ve ipify gate (PCAT_EXIT_IP_PROBE, kapalı) korunur.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-16 06:56:09 +03:00
f42f1888ae Merge pull request 'perf(proxy): capture/scrape browser'larında bant genişliği israfını kes' (#242) from dev into main
Reviewed-on: #242
2026-07-16 06:39:49 +03:00
0f2126d694 perf(proxy): capture/scrape browser'larında bant genişliği israfını kes
Some checks failed
QA Gate (P0/P1) / Test affected app (pull_request) Has been cancelled
DataImpulse residential kotası hızlı tükeniyordu (15 günde 58.5 GB). CSV
analizi capture/scrape tarayıcılarının tam sayfa (resim/font/CSS/reklam/
CDN) yüklediğini gösterdi.

- pcat + emex capture: resource-blocking'e stylesheet + üçüncü-parti çöp
  (yastatic, google fonts/autofill, adsco.re, displayvertising, tidio,
  ipify) eklendi. Widget runtime CDN'leri (jsdelivr/unpkg) bilinçli hariç.
- emex: engelleme context seviyesine alındı → tüm tab'ları kapsıyor.
- pcat: ipify exit-IP probe artık PCAT_EXIT_IP_PROBE ile default-off
  (15 günde ~54k faturalı istek + 352 MB, sadece telemetri içindi).

Not: emex scraping resmi tarayıcıda yüklemiyor; URL'yi HTML'den parse edip
boyutu ayrı Range GET ile alıyor → resim engellemek scraping'i etkilemez.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-15 18:25:51 +03:00
3248ab1c3a Merge pull request 'test(shared): fix normalizeName hyphen test to correct tr-TR output' (#241) from dev into main 2026-07-15 16:55:43 +03:00
a6437dcd67 test(shared): correct normalizeName hyphen test expectation to tr-TR output
The failing test expected normalizeName("ANNA-MARIA")=="Anna-Maria" (dotted i),
but that is internally inconsistent with the suite's own Turkish tests that REQUIRE
the deliberate tr-TR locale: "ALİ YILMAZ"→"Ali Yılmaz" (dotless ı) and "ÇAĞRI"→
"Çağrı". Uppercase Latin "I" (U+0049) is the SAME codepoint as Turkish dotless-I,
so tr-TR lowercases it to "ı" — correct for a TR product (invariant casing would
break every Turkish name: Yilmaz/Çağri, and mangle İ→i̇ with a combining dot). Not
a code bug; expectation corrected to "Anna-Marıa" with an explanatory comment.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-15 16:55:35 +03:00
544b3f25d1 Merge pull request 'fix(vinpin): Rpartstore-down definitive not_found (no budget-burn+poison) + old-Renault tokens + year-cycle' (#240) from dev into main 2026-07-15 15:50:02 +03:00
cc543ace21 fix(vinpin): poll Dialogys header before a definitive not_found (fixA follow-up)
Some checks failed
QA Gate (P0/P1) / Test affected app (pull_request) Has been cancelled
FIX A made a CLEAN Dialogys not_found definitive on its own while Rpartstore is
down (no retry). But runDialogysSearch inferred not_found from a SINGLE OCR
sample taken after a blind fixed wait — a slow render or a transient OCR glitch
on a DECODABLE Renault read empty at t=afterDialogysSubmit and was mislabelled
not_found, and under FIX A that miss is now terminal (decodeRenaultLocked
returns null, no cheap retry).

Replace the blind wait + single sample with a poll (pollForState) over the
header region for a decodable render, capped at afterDialogysSubmit — mirrors
runRpartstore's poll-then-decide shape. Multi-samples across the same window and
returns early on a hit, so a slow render/OCR glitch no longer produces a false
not_found. Cap unchanged, so a genuine miss consumes no more time than before:
FIX A's no-budget-burn / no-seat-poison guarantee and the definitive-not_found
semantics both hold, and the full-frame fallback is preserved. Working Renault
decodes only get faster (early return). tsc clean; vinpin (119) + extractModelYear
(12) green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-15 15:48:44 +03:00
c03e7f4079 fix(vinpin): stop budget-burn + seat-poison on undecodable Renault when Rpartstore down
FIX A (runRenaultFlow): when Rpartstore is UNAVAILABLE (down-cooldown or it
never loaded, so `primary` is only a placeholder ambiguous), a CLEAN Dialogys
not_found is now DEFINITIVE. The old gate required BOTH catalogs to say
not_found, so every undecodable Renault while Rpartstore was down got
downgraded to ambiguous → 3x retry → 180s budget → sessionPoisoned, which
then degraded later decodes. A genuinely-ambiguous Dialogys (unreachable)
still retries. When Rpartstore actually ran, both-must-agree is preserved.
runDialogysSearch now logs its outcome + truncated OCR header so this class
is diagnosable from prod logs.

FIX B (vinpin.constants): add old R-number + TR-badge Renault model tokens
(R5/R9/R11/R12/R19/R21/R25, Europa/Broadway/Toros/Flash). R-prefixed form
only — no bare numerics that could false-match year/engine digits.

FIX C (vin-validator extractModelYear): the position-10 year code repeats every
30 years ("T" = 1996 or 2026) with no clean VIN-only rule. New optional
{modelResolved:false} signal: for a brand-only decode of an old-shaped Renault
VIN (Renault WMI + numeric-led VDS type code) whose code pins to the current
cycle's leading edge, roll back one 30-year cycle so a ~1996 R19 isn't labelled
2026. Narrow: model-resolved or modern-shaped VINs are unchanged. Corgi's
WMI-only decoder wired to pass modelResolved:false.

Keeps never-throw / VINPIN_DECODE_BUDGET_MS / sessionPoisoned semantics and the
Fiat + working Renault paths intact. tsc clean; vinpin + corgi + extractModelYear
tests green (new tests cover A and C).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-15 15:39:26 +03:00
41f2f1777f Merge pull request 'fix(vinpin): warm Fiat window-fault cold fallback' (#239) from dev into main 2026-07-15 13:56:47 +03:00
d7d78a77a6 fix(vinpin): warm Fiat window-fault falls back to cold (not throw→null)
Some checks failed
QA Gate (P0/P1) / Test affected app (pull_request) Has been cancelled
The last gap: when ensureWarmWindow('fiat') can't bring the Fiat ePER to its VIN
panel (partial Rpartstore-down session leaves it off-panel + re-nav can't recover),
warmDecode threw SessionDropped → re-warm → null, turning a DECODABLE Fiat VIN into
a not_found. Fall back to the proven cold Fiat path instead, so a warm-window fault
never loses a real decode. Completes the FIX2 cold-fallback (previously only the
unusable-parse branch had it; now the can't-reach-panel branch does too).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-15 13:56:40 +03:00
5a79e94df3 Merge pull request 'fix(vinpin): warm on Fiat+Dialogys anchor (no starvation)' (#238) from dev into main 2026-07-15 13:42:39 +03:00
dac0708cda fix(vinpin): claim warm on Fiat+Dialogys anchor (not full 3-window)
Some checks failed
QA Gate (P0/P1) / Test affected app (pull_request) Has been cancelled
The full 3-window gate never warmed during a prolonged Rpartstore outage, so the
daemon re-attempted warm-up every backoff cycle — each ~2min attempt holds the
single-seat mutex and STARVES real decodes. Anchor warm on Fiat ePER + Dialogys
(the two windows that serve both brands; the Rpartstore-down cooldown routes
Renault to Dialogys anyway, so Rpartstore is an optional bonus). Warm is then
claimed once and HELD (no re-warm loop → no starvation); the Поиск-token foreground
fix makes warm Fiat raise the correct window. Rpartstore rejoins on recovery.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-15 13:42:31 +03:00
5628cbceaf Merge pull request 'fix(vinpin): claim warm only on full 3-window session' (#237) from dev into main 2026-07-15 13:25:46 +03:00
aa798ec03d fix(vinpin): claim warm ONLY on a full 3-window session (Fiat+Rpartstore+Dialogys)
Some checks failed
QA Gate (P0/P1) / Test affected app (pull_request) Has been cancelled
A partial warm session (e.g. Rpartstore DOWN → only Fiat+Dialogys) is proven
unstable: re-warm cycles + the missing catalog's launch-error keep knocking the
Fiat window off its VIN panel, so warm Fiat decodes thrash to the 180s budget →
not_found. Require all three windows before this.warm=true; otherwise stay on the
reliable cold path (which decodes Fiat/Renault + cross-brand cleanly). The daemon
backs off + retries, so warm auto-resumes once Rpartstore recovers.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-15 13:25:39 +03:00
0011c80ec3 Merge pull request 'fix(vinpin): warm-Fiat decode (Поиск false-match + silent-null cold-fallback + strict not-found)' (#236) from dev into main 2026-07-15 13:03:30 +03:00
46f0210ba6 fix(vinpin): strict not-found for warm-Fiat full-frame garble check
Some checks failed
QA Gate (P0/P1) / Test affected app (pull_request) Has been cancelled
Review finding: warmDecode's genuine-not-found decision used VINPIN_OCR.notFound
(/…|Catalogue/i) against the FULL frame, where the 'Spare Parts Catalogue' header
always matches → every on-panel garble was flagged a genuine miss and null'd out
instead of falling back to the cold retry. Add notFoundStrict (no Catalogue token)
for the full-frame check so a transient on-panel garble (VIN exists) recovers via
the cold path; keep notFound for the runVinFlow modal-region settle poll.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-15 13:03:23 +03:00
31aabfc28f fix(vinpin): warm-path Fiat silent not_found (wrong-window raise + silent null)
When the warm daemon is up and Rpartstore is DOWN, a partial-warm session
(Fiat opened, Rpartstore launch-error, Dialogys opened last → foreground)
made a Fiat warm decode fail silently: the Fiat foreground regex shared the
`Поиск` token with the Dialogys "ПОИСК" button, so raiseWarmWindow reported
success without raising Fiat and the VIN was typed into Dialogys → garbage;
warmDecode's Fiat branch then did a bare `return null` (no log, no fallback).

- FIX 1: drop the ambiguous `Поиск` from VINPIN_WINDOW_FOREGROUND.fiat; keep
  Fiat-only chrome (Dealer/ePER) + VIN-panel model tokens.
- FIX 2: warmDecode Fiat unusable-parse no longer returns a silent null —
  OCR the frame; on-panel + genuine not-found → null (real miss), otherwise
  warn (cold-path parity) and fall back to the proven cold decodeFiatLocked.
- FIX 3: ensureWarmWindow panel-verifies a raised Fiat window (catalogueReady);
  if up but off the VIN panel, re-navigate via establishSession (bounded/never-throw).
- FIX 4: _warmUp records per-window availability (warmWindows) so a Fiat VIN
  routes straight to cold when no Fiat window opened; and dismisses a leftover
  Rpartstore launch-error modal before opening Dialogys so it can't dirty the
  desktop / drive the wrong-window state.

Adds ocrFrame() test seam + 4 unit tests. tsc clean; 114 vinpin tests green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-15 12:55:10 +03:00
0de05e5515 Merge pull request 'fix(vinpin): cheap in-session retry on ambiguous Renault decode' (#235) from dev into main 2026-07-15 10:28:57 +03:00
9cb58c583c fix(vinpin): cheap in-session grid reset on ambiguous Renault retry (no relaunch)
Some checks failed
QA Gate (P0/P1) / Test affected app (pull_request) Has been cancelled
An AMBIGUOUS Renault outcome is transient/state-dependent, but decodeRenaultLocked
retried it with a full browser teardown (this.close()). The next attempt then
re-launched chromium + re-did the web login + re-established from scratch
(~60-90s each), and each re-establish re-hit the seat's dirty-resume ("catalog
window resumed open" -> closeStrayRunningApps), so 3 attempts blew the 180s budget
-> not_found. Proven live: VF1RFE00653633190 decoded cleanly to KADJAR earlier
when the desktop state was favorable, then thrashed to not_found on relaunch.

Fix: on the ambiguous path, reset to a clean VinPower brand grid on the SAME live
session via ensureBrandGrid (closeStrayRunningApps DOM recovery first, canvas
tab-X fallback) instead of tearing the browser down. Keep the browser + authed so
the next iteration's ensureAuthenticated is a no-op (no relaunch, no web login),
and re-run runRenaultFlow from the clean grid (~30-40s). Graduated safety: if the
cheap reset can't confirm a clean grid or the session is broken (page
closed/disconnected), fall back to the old close() + cold re-establish. The reset
runs under the wall-clock deadline so an overrun still routes to the existing
VinpinBudgetError teardown+poison path. never-throw + budget/poison paths
unchanged; maxAttempts semantics unchanged.

Tests: +3 (ambiguous -> in-session ensureBrandGrid reset re-runs runRenaultFlow
with NO close(); graduated fallback close()s when the reset can't reach a grid;
broken session skips straight to close()). 110 vinpin tests green; tsc clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-15 10:27:17 +03:00
d55a2b570f Merge pull request 'fix(vinpin): DOM Running-panel recovery for dirty-resume + fail-safe stray close' (#234) from dev into main 2026-07-15 09:49:20 +03:00
cf36da07af fix(vinpin): fail-safe stray-app close — never terminate a row on an unreadable name
Some checks failed
QA Gate (P0/P1) / Test affected app (pull_request) Has been cancelled
Review finding: closeStrayRunningApps classified an unreadable/empty VinPower
running-app row as a stray and closed it (`/VinPower/i.test('')` is false),
needlessly killing+relaunching a healthy VinPower on a transient name-read miss.
Only close rows POSITIVELY identified as non-VinPower (non-empty name that fails
the VinPower match); treat unreadable names as keep.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-15 09:48:48 +03:00
814d11d03e fix(vinpin): DOM-based dirty-resume recovery via Horizon Running panel
On login the RDS seat resumes DIRTY (e.g. a Renault Rpartstore launch-error
modal + its taskbar window over the brand grid). The old recovery failed: the
canvas tab-✕ (93,45) only hits a TABBED catalog window's ✕, which a resumed
stray doesn't have, so 6 tries did nothing and escalated to logout+relogin —
counterproductive, since the seat publishes apps-only and the RDS session ends
only on server-side idle timeout, so a Connection-Server logout+relogin PROVABLY
resumes the same dirty window.

New state-agnostic recovery `closeStrayRunningApps`: reveal the Horizon sidebar
(#sidebar-toggler), enumerate ul.running-app rows, and terminate every app whose
name != VinPower via its per-app ✕ (li.icon-close-app-image) — real DOM outside
the Blast canvas, so it closes a window regardless of its modal/spinner/loading
state. Collapse the sidebar, OCR-confirm the brand grid; relaunch VinPower via
#available-VINPIN (or the vinpinApp canvas coord) if the app itself was gone.

Wired as the PRIMARY recovery in ensureBrandGrid — both the resumed-catalog
branch (before the canvas tab-✕ fallback) and the end-of-loop escalation, which
NO LONGER calls logout+relogin (method retired). Every DOM op is guarded
(try/catch + presence check) so a missing selector / canvas-only render degrades
gracefully to the existing dismissBlockingModal + tab-✕ / OCR path instead of
throwing. Bounded loop; the launch-error modal dismissal (OK 868,530 / Escape)
is kept as a fast pre-step and fallback.

Preserves the never-throw contract, 180s budget/poison, spinner-guard, acquire
cap, launch-error cooldown, ensureRpartstore fast-bail, and the Fiat ePER path.
tsc clean; 107 vinpin tests green (adds closeStrayRunningApps close/degrade tests
and the ensureBrandGrid-uses-closeStrayRunningApps escalation tests).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-15 09:43:53 +03:00
ee56dec2d5 Merge pull request 'fix(vinpin): ffmpeg OCR root-cause + robust DOWN-Rpartstore Renault decode (defense-in-depth + hardening)' (#233) from dev into main 2026-07-15 08:47:46 +03:00
8137845198 fix(vinpin): bail a DOWN Rpartstore on iteration 1, don't re-click the flyout 6×
Some checks failed
QA Gate (P0/P1) / Test affected app (pull_request) Has been cancelled
When Rpartstore is DOWN, its hard launch-error modal ("Ошибка запуска каталога",
title "Renault Rpartstore") renders OVER the brand grid. The grid tiles stay
OCR-visible behind the small centered modal, so the full-frame read matches both
`brandGrid` and `renaultSubmenu` — making ensureRpartstore's flyout branch fire on
EVERY iteration, re-clicking renaultRpartstore(584,779) + langOk + a 12s full-frame
poll for all ~6 iterations (~72s) before finally returning false. That wastes ~60s on
the first cold DOWN decode AND repeatedly actuates coordinates on a wedged desktop.

Detect the launch-error modal (upscaled crop via the existing
`rpartstoreLaunchErrorPresent`) at the top of the per-iteration loop, BEFORE the
flyout branch: if present, return false on iteration 1 so the acquire loop's
`!present` path dismisses it, sets the down-cooldown, and routes straight to Dialogys.
Depends on the crop OCR being legible (ffmpeg upscale, added in 281c54a); when
illegible it's false and behaviour is exactly as before.

Adds two robustness tests: (1) modal-over-grid → false on the first iteration with no
flyout re-clicks; (2) illegible crop → flyout path still runs (unchanged).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-15 08:46:40 +03:00
c8d9e45207 fix(vinpin): don't cool down Rpartstore on transient born-stuck streak; don't relaunch on clean-logout launcher
Two review follow-ups to 281c54a:

1. born-stuck cooldown regression: acquireLoadedRpartstoreInner set the 10m
   down-cooldown when maxOpens was exhausted by a born-stuck-spinner streak — a
   TRANSIENT, reopen-recoverable blip, not a server outage. Because the cooldown
   can only self-clear from INSIDE the acquire loop (skipped while cooling down),
   one spinner streak suppressed the richer Rpartstore catalog for every Renault
   decode for 10m. Reserve the cooldown for the confirmed launch-error DOWN signal
   (unchanged at the two launch-error sites); the born-stuck give-up now just falls
   back to Dialogys for that one VIN and retries Rpartstore fresh next VIN.

2. clean-logout false disconnect-recovery: cleanTeardown's disconnect recovery
   gated on VINPIN_OCR.sessionDropped, whose broad "HTML Access" token also matches
   the clean-logout Horizon HTML-Access launcher. A clean log-off could then click
   disconnectedClose + RELAUNCH VinPower right before close(), leaving the exact
   dirty resumed session the teardown prevents (+~17s wasted). Veto the recovery
   with !VINPIN_OCR.launcher so it fires only on a real Disconnected drop.

Keeps never-throw, budget, spinner-guard, Fiat/Dialogys fallbacks intact. Adds a
born-stuck-no-cooldown test and a clean-logout-launcher-no-relaunch test.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-15 08:41:35 +03:00
281c54a423 fix(vinpin): Renault-decode robustness for a DOWN Rpartstore (ffmpeg + flyout/close/logout/cooldown)
Root cause: ffmpeg is absent in the prod worker, so vinpin.ocr cropScale silently
returns the full 1600x900 frame — the tiny centered Rpartstore launch-error modal
is illegible, so a DOWN Rpartstore is misread as a spinner and thrashes the seat.

- Dockerfile: install ffmpeg so cropScale actually crops+3x-upscales (restores all
  clipped OCR: modal-crop error detect, Fiat modal, Renault header).
- ensureRpartstore: gate the "already open" short-circuit on a CONTENT token
  (rpartstoreLoaded), not rpartstoreOpen which false-matches the flyout/title word
  "Rpartstore"; click the flyout entry when the submenu is up over the grid; keep a
  late open-window branch so a spinner/vehicle-page window still counts as present.
- closeRpartstoreTab: never click windowClose(1298,14) (it hits the language
  selector and wedges the grid); gate the retry on a content token; Escape after.
- cleanTeardown: dismiss any blocking modal BEFORE "Çıkış yap" so logout is a clean
  RDS log-off (not a dirty channel disconnect); recover a Disconnected dialog via
  disconnectedClose(953,505) + relaunch VINPIN app for a fresh grid.
- Rpartstore-down cooldown (10m): a launch-error / repeated load-failure routes
  Renault decodes straight to Dialogys (skip reopening a down catalog); a confirmed
  load clears it.
- ensureBrandGrid: dismiss a wedging launch-error modal + short-retry instead of
  burning the 84s dead-wait.
- parseRenaultHeader: ignore the status-bar license-expiry date when reading the
  model year; sessionAlive matches RDST01/RDST02 (seat load-balances).
- Keeps never-throw, VINPIN_DECODE_BUDGET_MS, sessionPoisoned, the acquire cap,
  spinner-guard, relogin-cap and the Fiat/Dialogys fallbacks intact.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-15 08:32:39 +03:00
5b93864dd5 Merge pull request 'fix(vinpin): dismiss leftover launch-error modal + cap relogin per decode (browser-disconnect loop)' (#232) from dev into main 2026-07-15 07:01:23 +03:00
f54511d393 fix(vinpin): clear leftover launch-error modal on acquire give-up + cap relogin
Some checks failed
QA Gate (P0/P1) / Test affected app (pull_request) Has been cancelled
The Renault decode fell to not_found when Rpartstore is DOWN (hard
launch-error modal) even though Dialogys should take over. Root cause:

- acquireLoadedRpartstore's budget-exhausted / never-loaded return-false
  paths left the centered launch-error modal on screen (only the flaky
  OCR error-detect branch dismissed it). The modal then blocked the
  Dialogys grid-return.
- returnToBrandGrid's tab-✕ can't close a centered dialog, so every
  "not on brand grid (try N/4)" wedged and re-entered ensureBrandGrid,
  which escalated to logoutAndRelogin → close()+launch() ("browser
  disconnected — will relaunch") on EVERY iteration, thrashing on a stale
  page ref until the 180s budget → not_found.

Fixes (conservative, all safety nets intact):
1. Wrap acquireLoadedRpartstore so EVERY false return runs a best-effort
   defensive dismiss (Escape → click launch-error OK 868,530 → Escape),
   unconditional of the OCR read. Harmless when no modal is up.
2. returnToBrandGrid + ensureBrandGrid dismiss a possible centered modal
   before the tab-✕ close so a leftover dialog can't wedge the loop.
3. Cap the logout+relogin escalation to ONE attempt per decode/warm-up
   (reloginUsedThisDecode) — a capped exhaustion poisons the seat for a
   clean cold restart instead of looping close()+launch() until budget.

Keeps the OCR fast-path branch, maxOpens/acquireBudgetMs=14s, fcc0298,
61b5769, Fiat path, never-throw/budget/poison all intact.

Tests: +3 (budget-exhausted defensive dismiss; grid-return modal-clear
before tab-✕; relogin capped to one attempt) — 88 vinpin tests green,
tsc + biome clean. Needs prod validation.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-15 06:47:28 +03:00
9f6693e833 Merge pull request 'fix(vinpin): cap Rpartstore acquire at ~1 open via 14s sub-budget' (#231) from dev into main
Reviewed-on: #231
2026-07-15 06:25:45 +03:00
e0b3de8dc7 fix(vinpin): cap Rpartstore acquire at ~1 open via 14s sub-budget
Some checks failed
QA Gate (P0/P1) / Test affected app (pull_request) Has been cancelled
Rpartstore's launch-error modal OCR-detection is unreliable across renderings,
so a DOWN Rpartstore was grinding all 3 reopens (~54s) + dirtying the seat →
Dialogys fallback couldn't finish inside the decode budget → not_found.
Lower acquireBudgetMs 90s→14s so the loop bails after the first open+poll (~22s)
straight to Dialogys on a still-clean seat. Healthy Rpartstore loads on the first
open and is used as before; maxOpens kept so tests still exercise the reopen path.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-15 06:18:55 +03:00
6c5f8401f8 Merge pull request 'fix(vinpin): detect Rpartstore launch-error via upscaled modal crop, not full 1x frame' (#230) from dev into main
Reviewed-on: #230
2026-07-15 06:01:39 +03:00
542ab0cb2b fix(vinpin): detect Rpartstore launch-error via upscaled modal crop, not full 1x frame
Some checks failed
QA Gate (P0/P1) / Test affected app (pull_request) Has been cancelled
The prod Rpartstore→Dialogys bail regressed: a DOWN Rpartstore was still
misclassified as a "born-stuck spinner", burning 3 reopens (~54s) and pushing
the decode past the 180s budget → not_found. The rpartstoreLaunchError regex
never matched because acquireLoadedRpartstore's load-poll OCR'd the FULL
1600x900 frame at 1x — at which the small centered Cyrillic modal ("Ошибка
запуска каталога") is illegible to tesseract (it returns the surrounding
brand-grid tiles and drops the modal text). The regex text was actually fine;
the modal was never fed to it.

Root cause (verified live 2026-07-15, seat trvinpin47828): wrong OCR
resolution/region, not wrong regex.

Fix:
- New VINPIN_RPARTSTORE_ERROR_REGION (centered modal crop); OCR it UPSCALED (3x)
  so "Ошибка запуска каталога" reads as "Owwu6ka 3anycka KaTanora" and matches.
- pollRpartstoreState(): each poll reads LOADED off the full frame (large Latin
  text, unchanged) AND the launch-error off the upscaled modal crop → bail on the
  FIRST open, no wasted reopens. Genuine-spinner reopen path preserved.
- Also catch the launch error when ensureRpartstore/raiseWarmWindow can't confirm
  a window (modal is over the grid, no catalog chrome) → dismiss + bail.
- rpartstoreLaunchError regex: add the verbatim live transliterations
  (Owwu6ka/OwwbKa); 3anycka+KaTanora remain the stable anchors.

Live verification (seat trvinpin47828, exclusive night access):
- Rpartstore is DOWN server-side (hard launch error, NOT a spinner).
- New detection returns launchError on open 1 → bail, no reopens.
- Dialogys fallback decoded VF1RFE00653633190 → RENAULT Kadjar (HFE) in 52.2s
  (well under the 180s budget).

Budget/poison/livelock/Fiat paths untouched. 85 vinpin unit tests green;
typecheck + biome clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-15 05:53:22 +03:00
74c718fb18 Merge pull request 'fix(vinpin): detect Rpartstore hard launch-error → bail straight to Dialogys' (#229) from dev into main
Reviewed-on: #229
2026-07-15 05:16:15 +03:00
0ad3f114f3 fix(vinpin): detect Rpartstore hard launch-error → bail straight to Dialogys
Some checks failed
QA Gate (P0/P1) / Test affected app (pull_request) Has been cancelled
Rpartstore currently throws an immediate hard launch-error modal ("Ошибка
запуска каталога" / title "Renault Rpartstore") within ~8-10s of every open —
a server-side/entitlement failure that reopening never fixes. The old code
misclassified it: the error dialog's title matched rpartstoreOpen so
ensureRpartstore returned true, but it lacked the rpartstoreLoaded content
markers, so acquireLoadedRpartstore judged it a born-stuck spinner and burned
all 3 reopens (~54s) before falling back to Dialogys — which then ran out of
the 150s decode budget → not_found. Dialogys itself decodes correctly (~25s).

Fix (detect-and-bail on the FIRST open, no wasted reopens):
- constants: add VINPIN_COORDS.rpartstoreLaunchErrorOk (868,530) + the
  VINPIN_OCR.rpartstoreLaunchError pattern (matches the real Cyrillic AND its
  stable eng-OCR transliteration "Owwnbka 3anycka KaTanora").
- acquireLoadedRpartstore step 2: poll now stops on loaded OR launch-error and
  classifies via the returned OCR text; a launch error dismisses the modal and
  returns false immediately → straight to Dialogys (reopen loop untouched for
  genuine spinners).
- ensureRpartstore: submenu-open poll also stops fast on the launch error
  instead of dead-waiting afterRenaultCatalogOpen.
- bump VINPIN_DECODE_BUDGET_MS 150s→180s (cheap safety margin).
- tests: launch-error → false after ONE open (no reopens, dismiss clicked);
  genuine spinner still reopens; OCR-pattern matches Cyrillic + transliteration.

Never-throw contract, sessionPoisoned, budget teardown, cold/Dialogys
fallbacks, the fcc0298 spinner-guard, the 61b5769 establish/teardown fix and
the Fiat ePER path are all intact. Skipped the warm-path Dialogys field-clear
tweak — runDialogysSearch is shared with the cold path and switching its clear
step would change cold behavior.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-15 04:24:02 +03:00
68e3eb4a61 Merge pull request 'dev' (#228) from dev into main
Reviewed-on: #228
2026-07-15 03:12:22 +03:00
61b5769e48 fix(vinpin): reliable warm-daemon establish (clean teardown + tab-close + backoff)
Some checks failed
QA Gate (P0/P1) / Test affected app (pull_request) Has been cancelled
Root cause of warm-establish failures was resume-into-dirty-session +
broken window-close + no backoff, not OCR/detection. Four composing fixes:

A. Clean teardown (cleanTeardown): before the browser close(), close each
   open catalog window via the corrected tab-✕ then click "Çıkış yap" logout
   to END the RDS session, so the next warm-up starts from a fresh login/grid
   instead of resuming into the last-open 3-window desktop. Wired into
   teardownWarm() and both failed-warmUp exits. Bounded + never-throw.

B. Fix close coords + tab-✕ primary. catalogTabClose {135,45}→{93,45}
   (validated live). In ensureBrandGrid/returnToBrandGrid the tab-✕ is now the
   PRIMARY close; the windowClose {1298,14} click (which opens the HTML-Access
   language dropdown) is no longer used there. Escape pressed after each close
   to dismiss an accidental dropdown before re-OCR. After N failed closes,
   ensureBrandGrid escalates to logout+relogin (one-shot, no recursion) instead
   of limping into the ePER-open loop.

C. Realistic grid wait. afterLogin 20_000→45_000 (real grid render ~32-46s).

D. Backoff between re-warm attempts. A failed warmUp sets a cooldown (60s,
   exponential to 5min) that BOTH reconcile() and decode()'s warm-on-demand
   honour; a successful warm resets it — so a failing seat is no longer
   hammered every ~60s leaving fresh dirty windows.

Safety nets preserved: never-throw contract, VINPIN_DECODE_BUDGET_MS,
sessionPoisoned, cold/Dialogys fallbacks; fcc0298 Rpartstore spinner-guard,
Fiat ePER path, and Russian-dialog dismissal (746,454) untouched. Cannot be
exercised in dev (single seat on prod) — needs prod validation on a rested seat.

Tests: +8 unit tests (clean-teardown ordering, tab-✕ primary + relogin
escalation, warm-up backoff respected by reconcile + warm-on-demand + reset).
81 vinpin tests green; tsc + biome clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-14 19:11:21 +03:00
8e10ebc883 feat(web): redirect path-style /dashboard/settings/<tab> to ?tab= search param
Unsubscribe confirmations (and any stale links) used the path form which
had no route and fell to the SPA not-found screen.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-14 17:47:24 +03:00
29e10b432f feat(notifications): visible unsubscribe footer link in lifecycle mails
- inject signed unsubscribeUrl into every optional-workflow Novu payload
  (templates render it via {{#if unsubscribeUrl}} footer)
- add 'conversion' campaign workflow to OPTIONAL_WORKFLOWS + email_marketing
  category so its one-click tokens validate and opt-outs suppress it
- declare UNSUBSCRIBE_SECRET/URL_BASE/EMAIL in env schema (""→undefined
  preprocess against the url().optional() boot-crash trap), .env.example and
  both compose env blocks
- fix confirmation-page settings link (?tab=notifications)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-14 16:35:47 +03:00
55dd34a450 Merge pull request 'dev' (#227) from dev into main
Reviewed-on: #227
2026-07-14 15:50:40 +03:00
66b39862c8 fix(part-prices): araç-marka etiketlerini de orijinal say (FORD/GM/BMW/Mercedes/VW)
Some checks failed
QA Gate (P0/P1) / Test affected app (pull_request) Has been cancelled
Kullanıcı düzeltmesi: kokpit tur ham araç-marka etiketlerini "yansanayi"
sayıyordu — yanlış. FORD/GM/BMW/Mercedes/Volkswagen/Renault… OE etiketidir.
Orijinal tespiti artık kokpit tur='orjinal' setine değil, OE aile üyeliğine
dayanır: OE_SUPPLY_LABELS OE_FAMILIES'ten TÜRETİLİR (+ jenerik ORJINAL), böylece
OE-tespiti ile aile-filtresi drift etmez ve tüm araç markaları orijinal sayılır.
Gerçek yan sanayi PARÇA markaları (Bosch/Febi/Valeo/TRW) hiçbir ailede yok →
orijinal değil. GM Opel ailesine eklendi (TR'de Opel OE'si). Redis v3→v4 (eski
"miss" değerleri bayat). kokpit'e DOKUNULMADI.

Ölçülen etki (dev): grafikli kod %0,77→%0,84; artış sase kataloğu ile takip
beslemesinin bu markalardaki kod kesişimiyle sınırlı (ör. takip'te 4.859 Ford-
stokta koddan 335'i sase kataloğunda).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-14 15:34:10 +03:00
fcc02984dd fix(vinpin): Rpartstore acquire-with-spinner-guard for Renault decode
A freshly-opened Rpartstore instance sometimes gets "born stuck" on an
infinite spinner (survives raise/maximize). The only reliable fix, proven
in a live spike, is to CLOSE the stuck instance and reopen a FRESH one.

Replace the old "raise Rpartstore → if not focusable reopen → else fall to
Dialogys" with a bounded load-verify-else-reopen loop applied to BOTH the
warm-daemon Renault path (warmRenaultDecode) and the cold per-decode path
(runRenaultFlow):

- acquireLoadedRpartstore(): bring a Rpartstore window forward, OCR-verify it
  actually rendered its search-home landing markers (new rpartstoreLoaded set —
  content tokens the spinner lacks), and if still spinning close the tab and
  reopen a fresh instance. Retries up to VINPIN_RPARTSTORE.maxOpens (3) times.
- Bounded inside the decode wall-clock budget AND a tighter acquireBudgetMs
  (90s) sub-cap, so a permanently-stuck Rpartstore still leaves headroom to
  fall back to Dialogys — never a livelock.
- Rpartstore stays PRIMARY (richer Turkish catalog); Dialogys only as a
  last resort once reopen attempts are exhausted or it genuinely misses.
- Fiat ePER path unchanged; sessionPoisoned / never-throw contract preserved.

Adds unit tests for reuse / spinner→reopen→loaded / exhausted→false /
budget-bail / Rpartstore-primary-on-hit / exhausted→Dialogys-fallback.

Could not live-test (single Vinpin seat is held on prod) — needs prod
validation after promote.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-14 15:29:12 +03:00
edde2dc3b4 fix(part-prices): OEM fiyatını kodun araç markasına göre filtrele (PSA vs OPAR)
Aynı OEM koduna farklı OE dağıtıcıları düşebiliyor (Stellantis: PSA ₺5.531 vs
OPAR ₺3.459) → OE-only havuz bile iki dağıtıcıyı medyanlayıp hayalet fiyat
veriyordu. Artık kart, kodun kendi araç markasına göre tek OE ailesine süzer.

- part-prices.logic: marka→OE-dağıtıcı-ailesi haritası (OE_FAMILIES: PSA=
  Peugeot/Citroen/DS, FIAT=Fiat/OPAR/Tofaş, RENAULT=Renault/Dacia/MAIS, ...).
  filterOffersForBrand: araç markası → yalnız o ailenin orijinal teklifleri
  (jenerik ORJINAL aile-belirsiz olduğu için elenir); yan sanayi markası çipi
  → yalnız etiket-uyumlular; markasız → tüm OE aileleri (taban).
- Web: OEM kartı kodun araç markasını oem-vehicles'tan (en çok geçen brandName)
  türetip geçirir; başlık "Orijinal (OE) fiyat analizi · <Marka>". Kart marka
  çözümü için oem-vehicles'ı bekler.
- vehiclesByOem NORMALIZE eşleşmeye geçti + parts_oem_code_norm_idx functional
  index (migration 0033): PSA kodları boşluklu saklandığından ("9827 622 780")
  exact match onları kaçırıyordu — marka bu yüzden çözülemiyordu. Reverse
  "kataloğunuzda" bölümü de artık reformatlı kodları buluyor.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-14 14:07:55 +03:00
f52cafd622 Merge pull request 'dev' (#226) from dev into main
Reviewed-on: #226
2026-07-14 13:51:22 +03:00
d0caf57e89 fix(part-prices): OEM ana kartında yalnız orijinal (OE) fiyatları göster
Some checks failed
QA Gate (P0/P1) / Test affected app (pull_request) Has been cancelled
OEM detay ana fiyat kartı seriyi markasız istiyordu; allowBrandless uzun
kodlarda orijinal + yan sanayi tekliflerini tek havuzda medyanlıyordu →
hiçbir satıcının fiyatı olmayan "hayalet medyan" ve marka stok girip-
çıkmasından fiyat değişmeden sahte grafik sıçraması (2026-07-14 ölçümü:
9827622780 pg p50 4.495₺ = PSA 5.531 ile OPAR 3.459'un ortası).

- filterOffersForBrand: markasız istek artık yalnız orijinal (OE/dağıtıcı
  etiketli) teklifleri kullanır; araç-markalı OE çapraz-ref çipleri de
  OE-only'ye iner, yan sanayi markasına orijinal fallback'i kaldırıldı.
- Orijinal sınıflaması otoritesi = kokpit marka tur='orjinal' seti (39
  marka, statik; PSA/MAIS/OPAR/ORJINAL... — FORD/GM/BMW/Mercedes/VW kokpit'te
  yansanayi, bilinçli dışarıda). Runtime kokpit bağımlılığı yok.
- Web: kart başlığı "Orijinal (OE) fiyat analizi" + açıklama/dipnot orijinal
  bilgisini yazıyor; ana OEM kodunun ölü markasız batch push'u kaldırıldı.
- Redis cache v2→v3 (anahtar üreticileri export'lanıp worker ile paylaşıldı);
  migration 0032 eski karma-havuz part_price satırlarını siler → OE-only
  kurallarla lazy re-backfill.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-14 13:28:27 +03:00
32655ead7b chore(vinpin): add VINPIN_WARM_DAEMON compose env ref (api+worker) so Coolify can inject the warm-daemon flag
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-14 13:21:35 +03:00
98376747cd feat(vinpin): persistent warm-session daemon (taskbar-raise decode) with cold fallback
Replace the per-decode "launch browser + login + open catalog" model with a
persistent warm Vinpin seat that eliminates cold-start, brand-switch cost and the
seat livelock. Additive + fail-safe: every warm operation degrades to the proven
cold per-decode path, so behaviour never regresses.

Warm daemon (VinpinDaemonService, worker-process singleton):
- Scheduler warms the seat at 08:00 and tears it down at 21:00 Europe/Istanbul
  (proper TZ via Intl, no hardcoded offset); warms on worker start if inside hours;
  reconcile() every 60s with a reentrancy guard.
- Keepalive nudges the RDS session (mouse.move) every ~75s while warm+idle; it
  SKIPS during any active seat op (busy flag) and never takes a lock that blocks a
  decode.
- decode(vin): inside hours ensure warm (warm-on-demand once) then delegate to the
  driver; off-hours delegate straight to the cold path. Never throws.

Driver warm path (VinpinDriverService):
- warmUp() launches+logs in ONCE and opens Fiat ePER + Renault Rpartstore + Renault
  Dialogys windows without closing each other, then OCR-binds each taskbar button
  (order read via OCR, not hardcoded; raise self-heals by probing slots + OCR
  verify). isWarm()/teardownWarm()/keepalivePing() added.
- warmDecode(): taskbar-raise the brand window (Fiat→ePER, Renault→Rpartstore w/
  Dialogys fallback), run the EXISTING in-catalog decode on the warm window, OCR
  the modal, parse, then Escape to ready the field for the next VIN. Runs under the
  wall-clock budget; a hang still aborts.
- Health-recovery: a dropped seat (Disconnected/no-free-sessions OCR marker) →
  teardown + re-warm ONCE, then retry the decode once.
- Refactored runDialogys into openDialogysSubmenu + runDialogysSearch so the warm
  path searches without a window-closing reopen; cold Dialogys flow unchanged.

Safety nets retained: VINPIN_DECODE_BUDGET_MS + sessionPoisoned breaker (warm
budget abort → teardown+poison+null), single-seat serialization (runExclusive),
decode() never throws. Gated by VINPIN_ENABLED; VINPIN_WARM_DAEMON=false forces the
legacy cold path (kill-switch). Widened VINPIN_MODAL_REGION to ~900px.

Wiring: processor calls getVinpinDaemon().decode(); worker starts the daemon on
boot and stops it (releasing the seat) on shutdown. BullMQ concurrency 1 +
attempts:1 unchanged.

Tests: business-hours warm/teardown scheduling (injected clock/TZ), brand→taskbar
routing, taskbar OCR-order binding, keepalive-skips-during-decode, and
session-drop→re-warm→retry recovery. All existing vinpin/queue tests stay green.

NOTE: un-dev-testable (prod holds the single seat) — pixel/taskbar coords are
OCR-verified + marked TUNE and need live prod validation; warm falls back to cold
until confirmed.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-14 13:19:20 +03:00
ccf2417cc8 Merge pull request 'fix(vinpin): break the single-seat decode livelock (attempts:1 + budget + poison)' (#225) from dev into main
Reviewed-on: #225
2026-07-14 11:32:46 +03:00
d253a43ad2 fix(vinpin): break the single-seat decode livelock (attempts:1 + budget + poison)
Some checks failed
QA Gate (P0/P1) / Test affected app (pull_request) Has been cancelled
A bad/unresolvable VIN could leave a catalog window open on the shared Vinpin
seat; the next decode's ensureBrandGrid found it "resumed open" and looped
(close→brand-grid-not-confirmed→ePER-open→browser-disconnect→relaunch) forever.
BullMQ attempts:2 + 30s backoff auto-re-fed every failure straight back into the
stuck seat, starving all real decodes for minutes.

- queue: attempts:1, drop the 30s exponential backoff (extract VINPIN_DECODE_JOB_
  OPTIONS). The driver already runs its own bounded internal retries; a BullMQ
  retry on top is what compounded the livelock. Null decode still persists as
  not_found; a hard infra throw stays user-retriable (failed).
- driver: hard per-decode wall-clock budget (VINPIN_DECODE_BUDGET_MS, 150s) via
  withDeadline() racing each attempt; on abort → close() + poison seat + return
  null (no retry into the stuck state).
- driver: sessionPoisoned flag — set at nav-loop exhaustion (ensureBrandGrid /
  establishSession), budget abort, and failed post-decode cleanup; the NEXT
  decode forces a full cold re-establish instead of reconnecting to the resumed
  desktop. Cleared on any confirmed-clean grid/catalogue.
- driver: finally-cleanup after every decode — on failure/not-found return the
  seat to a clean brand grid; if that can't reach the grid, poison + tear down.
- driver: basic VIN sanity (17 alphanumerics) before touching the seat.

Healthy Fiat/Renault happy paths are byte-identical when nothing is stuck.
Cannot be live-tested (seat is on prod) — needs prod validation.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-14 11:29:43 +03:00
c2bb1e7382 Merge pull request 'fix(vinpin): prefer exact model over wrong-market catalog in matcher' (#224) from dev into main
Reviewed-on: #224
2026-07-14 10:55:06 +03:00
1fade89df4 fix(vinpin): prefer exact model over wrong-market catalog in matcher
Some checks failed
QA Gate (P0/P1) / Test affected app (pull_request) Has been cancelled
The Vinpin catalog matcher could route a European Renault VIN
(VF1RFE00653633190, decoded "KADJAR") onto the China-market catalog
"KADJAR ÇİN" (source XZH, 22 categories) instead of the correct European
"KADJAR" (XFE, 44 categories), serving wrong parts. Root cause: the
Turkish "ÇİN" lost its Ç/İ to the ASCII token strip and collapsed to a
dropped 1-char "N", so "KADJAR ÇİN" tokenized identically to "KADJAR" —
the market qualifier was invisible to the scorer.

Fixes:
- modelTokens now folds diacritics (NFD + combining-mark strip) so
  "ÇİN" survives as the ASCII token "CIN".
- Scorer prefers an EXACT normalized model match (no extra tokens) over
  a superset, via a bonus kept smaller than the year-range swing so
  multi-generation routing (2022 TIPO-EGEA → MCA) is unaffected.
- New MARKET_QUALIFIERS set (ÇİN/CIN, CHINA, CHINE, RUSYA, ... grounded
  in the real Renault/Dacia catalog rows) heavily penalizes candidates
  whose EXTRA tokens are region qualifiers; generation tokens are not
  penalized, so generations stay matchable.
- Richer-catalog (categoryCount) tiebreak among equal-score candidates;
  match() query selects the category count via a correlated subquery.

Adds unit tests incl. the KADJAR case, CLIO/DUSTER generation cases, and
diacritic-folding. Fiat behavior unchanged; all 39 vinpin tests green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-14 10:47:55 +03:00
7387c02da0 Merge pull request 'fix(web): cover cold Vinpin decode + drop hardcoded Fiat no-catalog copy' (#223) from dev into main
Reviewed-on: #223
2026-07-14 10:22:48 +03:00
7069ceaeae fix(web): cover cold Vinpin decode + drop hardcoded Fiat no-catalog copy
Some checks failed
QA Gate (P0/P1) / Test affected app (pull_request) Has been cancelled
Two Vinpin decode-flow UX bugs in the search page:

1. Poll window (VINPIN_MAX_POLLS 6→30, still 3s interval) now covers a
   cold Vinpin VDI decode (~60-100s) instead of bailing at 18s. On
   poll-exhaust we no longer fall through to the no-catalog dead-end;
   instead a reassuring brand-neutral "still working, ready shortly"
   card (decodePendingHint) — the decode caches server-side so a later
   re-submit returns instantly.

2. The poll-exhaust fallback previously forced brandName:"Fiat" onto the
   no-catalog prompt, so a Renault VIN read "Fiat". Removed. The
   no-catalog copy is brand-aware via the API's noCatalog.brandName, with
   brand-neutral fallback keys (noCatalogHintNeutral / browseCatalogCtaNeutral)
   when no brand is available. A Renault VIN never says "Fiat".

Web-only, no flag. New i18n keys added to tr.json + en.json. No API change.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-14 10:21:43 +03:00
cf9454482f Merge pull request 'perf(vinpin): in-session Renault→Fiat swap + OCR-poll waits + input micro-trims' (#222) from dev into main
Reviewed-on: #222
2026-07-14 10:09:38 +03:00
eaa500ddd5 perf(vinpin): in-session Renault→Fiat swap + OCR-poll waits + input micro-trims
Some checks failed
QA Gate (P0/P1) / Test affected app (pull_request) Has been cancelled
Latency optimizations in the flag-gated (VINPIN_ENABLED) Vinpin decode driver.
Every change keeps the existing fixed-wait value as a fallback cap, so
worst-case behaviour and robustness are unchanged — only the common case is
faster. No live seat session was run (prod holds the single Horizon seat).

#2 Renault→Fiat symmetric swap: ensureReady no longer tears the whole browser
down on a Renault→Fiat flow switch (was a ~60-80s cold restart). It now keeps
the authenticated Horizon/VinPower session, returns to the brand grid via the
existing ensureBrandGrid (which closes a resumed foreign catalog window) and
reopens Fiat via the normal tile flow — symmetric with the Fiat→Renault
direction. Guarded fallback: if the in-session swap can't reach the grid /
throws, it falls back to close()+cold re-establish.

#3 OCR-poll-until-ready: replaced big fixed post-action sleeps whose completion
is OCR-detectable with a capped poll (screenshot→ocrRegion→regex every ~700ms,
return on match, cap == old fixed wait). Converted: afterFiatOpen(12s),
afterVinSubmit(7s, Fiat modal), afterRpartstoreSubmit(8s),
afterRenaultCatalogOpen(12s, ×2), plus cold-path afterLogin(20s) and
afterVinPowerLogin(18s). Left afterVinpinLaunch(14s) fixed — the VinPower login
dialog has no reliable OCR marker (detected via DOM), and it doubles as a
generic connecting-screen settle. Left afterDialogysSubmit fixed (out of scope).

#4 Micro-trims: field-clear Backspace burst 40→5 (VINPIN_FIELD_CLEAR_BACKSPACES),
key-type delay 45-50ms→20ms (VINPIN_TYPE_DELAY_MS, 17-char VIN ~850→~340ms),
afterAlertDismiss 700→250ms.

New pure/injectable pollForText helper in vinpin.ocr.ts (unit-tested:
early-return, cap-never-exceeded, first-read match). typecheck + biome clean;
31 vinpin unit tests green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-14 09:57:40 +03:00
e47e795a09 Merge pull request 'dev' (#221) from dev into main
Reviewed-on: #221
2026-07-14 09:13:52 +03:00
77c93af9a0 feat(vinpin): Renault/Dacia decode akışı (Rpartstore + Dialogys)
Some checks failed
QA Gate (P0/P1) / Test affected app (pull_request) Has been cancelled
VINPIN köprüsüne Fiat'ın yanına Renault/Dacia desteği eklendi.

- Marka yönlendirme: selectVinpinBrandFlow(vin) WMI'den akışı seçer
  (Renault/Dacia → Rpartstore/Dialogys, geri kalan → mevcut Fiat ePER,
  Fiat davranışı byte-identical). isVinpinBrandAllowed allowlist'i
  fiat + renault + dacia'ya genişletildi.
- Renault akışı durum-toleranslı: koltuk son katalogu (Rpartstore)
  sunucu-taraflı hatırlayıp açık resume ediyor; ensureRpartstore grid /
  submenu / açık-pencere / yükleniyor durumlarını tanıyıp kendini
  toparlıyor. Rpartstore ana akış, Dialogys best-effort fallback.
- Ortak ensureBrandGrid artık resume olmuş yabancı katalog penceresini
  (Rpartstore/Dialogys/ePER) kapatıp grid'e dönüyor → Renault↔Fiat
  ardışık decode'ları (tek koltuk) artık kırılmıyor.
- parseRenaultHeader/isUsableRenaultParse: OCR başlığından model+marka
  (RENAULT/DACIA) + yıl; bilinen-token allowlist ile contiguous model
  koşusu. Matcher + processor kararlaştırılan markaya göre PL24
  catalog_vehicle eşliyor (Fiat varsayılan korunur).
- Testler: Renault parser + marka-yönlendirme/allowlist birim testleri.

Flag-gated (VINPIN_ENABLED). Canlı doğrulama: 5/5 Renault/Dacia VIN
(Kadjar, Clio II, Clio IV, Dacia Duster, Latitude) doğru decode; Fiat
Egea spot-check korunuyor.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-14 08:44:09 +03:00
24716d03a9 Merge pull request 'revert(build): drop ineffective cache-bust (#219)' (#220) from revert/build-cache-web into dev 2026-07-14 08:13:46 +03:00
6de7839107 revert(build): drop ineffective per-commit cache-bust (#219)
SOURCE_COMMIT isn't substituted into docker-compose build args by Coolify
(resolved to a constant "unknown"), so the cache-bust never fired. Removing the
dead ARG/RUN + compose arg. Web-only deploys use a Coolify force-rebuild instead.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-14 08:13:44 +03:00
edcd168d48 Merge pull request 'fix(build): per-commit cache-bust for web-only deploys' (#219) from fix/build-cache-web into dev 2026-07-14 07:43:07 +03:00
4bba42fc13 Merge pull request 'promote: Fiat eper-default katalog (Orijinal→ePER, Birleşik→kanonik)' (#218) from dev into main 2026-07-14 07:35:32 +03:00
5697447988 Merge pull request 'fix(vinpin): reject stale-breadcrumb decodes (require SINCOM) + harden matcher' (#213) from fix/vinpin-false-positive into main 2026-07-13 12:09:15 +03:00
59 changed files with 6829 additions and 301 deletions

View File

@@ -21,14 +21,6 @@ COPY --from=deps /app/apps/web/node_modules ./apps/web/node_modules
COPY --from=deps /app/packages/shared/node_modules ./packages/shared/node_modules COPY --from=deps /app/packages/shared/node_modules ./packages/shared/node_modules
COPY --from=deps /app/packages/config/node_modules ./packages/config/node_modules COPY --from=deps /app/packages/config/node_modules ./packages/config/node_modules
COPY --from=deps /app/packages/ui/node_modules ./packages/ui/node_modules COPY --from=deps /app/packages/ui/node_modules ./packages/ui/node_modules
# Cache-bust: web-only commits were sticking to a cached build layer, so
# auto-deploys shipped a stale bundle (only --no-cache/force rebuilds picked
# them up). Referencing the commit SHA *before* the source COPY makes this layer
# (and therefore COPY + `pnpm build`) invalidate on every commit; the deps stage
# above stays cached on the lockfile, so installs aren't repeated.
ARG SOURCE_COMMIT=unknown
RUN echo "Building commit ${SOURCE_COMMIT}"
COPY . . COPY . .
# Vite env vars (baked at build time) # Vite env vars (baked at build time)
@@ -46,8 +38,12 @@ RUN pnpm build
# ── Stage 4: Production ─────────────────────────────── # ── Stage 4: Production ───────────────────────────────
FROM node:22-alpine AS production FROM node:22-alpine AS production
# Chromium for Playwright (EMEX/PartsCatalogs) # Chromium for Playwright (EMEX/PartsCatalogs). ffmpeg is required by the Vinpin
RUN apk add --no-cache chromium nss freetype harfbuzz ca-certificates ttf-freefont # OCR pipeline (vinpin.ocr cropScale): it crops+3x-upscales the tiny centered
# Rpartstore launch-error / decode-modal region so tesseract can read it. Without
# it cropScale silently returns the full 1600x900 frame and every clipped OCR
# degrades to an illegible full-frame 1x read (the DOWN-Rpartstore misclassify bug).
RUN apk add --no-cache chromium nss freetype harfbuzz ca-certificates ttf-freefont ffmpeg
ENV PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH=/usr/bin/chromium-browser ENV PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH=/usr/bin/chromium-browser
ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1

View File

@@ -23,3 +23,8 @@ NOVU_API_KEY=
APP_PUBLIC_URL=https://sase.tr APP_PUBLIC_URL=https://sase.tr
# HMAC secret for signed track.sase.tr click links (Bitwarden "mailtrack tracking (track.sase.tr)"). Empty → no click tracking. # HMAC secret for signed track.sase.tr click links (Bitwarden "mailtrack tracking (track.sase.tr)"). Empty → no click tracking.
MAILTRACK_SECRET= MAILTRACK_SECRET=
# Unsubscribe links (List-Unsubscribe header + mail footer). Empty secret → mailto-only header, no footer link (dev default).
UNSUBSCRIBE_SECRET=
# Defaults to <APP_PUBLIC_URL>/api/email/unsubscribe when empty.
UNSUBSCRIBE_URL_BASE=
UNSUBSCRIBE_EMAIL=unsubscribe@sase.tr

View File

@@ -0,0 +1,8 @@
-- Fiyat görünümleri artık markasız/araç-markalı bağlamlarda yalnız ORİJİNAL
-- (kokpit tur='orjinal' etiketli) teklifleri içerir. Mevcut satırlar eski
-- kuralla (orijinal + yan sanayi tek havuz) hesaplandığından tutarsız — sil;
-- seriler ilk görüntülenmede takip history'sinden OE-only kurallarla yeniden
-- backfill edilir (product_history 2026-01-29 epoch'undan beri eksiksiz),
-- cron sonraki günleri aynı kuralla ekler. (~166 track / ~4,8k satır — ucuz.)
DELETE FROM "part_price_daily";--> statement-breakpoint
DELETE FROM "part_price_tracks";

View File

@@ -0,0 +1,9 @@
-- OEM kodu normalize-eşleşme index'i. Reverse-catalog (vehiclesByOem) ve
-- fiyat-kartı marka çözümü artık normalize edilmiş koda göre eşleşir: URL
-- kodu boşluksuz ("9827622780") gelirken katalog boşluklu saklayabilir
-- ("9827 622 780"; özellikle PSA/Peugeot/Citroen) → exact match kaçırıyordu.
-- Functional btree, sorgudaki ifadeyle birebir aynı olmalı ki planner kullansın.
-- Not: non-concurrent build kısa süreli YAZMA kilidi alır (prod ~10s, salt-okuma
-- etkilenmez); parts ~9,3M satır. IF NOT EXISTS → idempotent/yeniden koşulur.
CREATE INDEX IF NOT EXISTS "parts_oem_code_norm_idx"
ON "parts" (regexp_replace(upper("oem_code"), '[^A-Z0-9]', '', 'g'));

View File

@@ -0,0 +1,9 @@
-- Kalıcı tamlık işareti: prefetch zinciri parça ile bittiğinde true olur
-- (PrefetchWorkerService.incrementCompleted). Redis prefetch:complete:* (21g TTL,
-- operasyonel skip mantığı) yerine SÜRESİZ ölçüm — "% tam çekilmiş" güvenilir
-- takibi. _at son doğrulanma zamanını tutar. IF NOT EXISTS → idempotent.
ALTER TABLE "vehicles" ADD COLUMN IF NOT EXISTS "fully_fetched" boolean DEFAULT false NOT NULL;
--> statement-breakpoint
ALTER TABLE "vehicles" ADD COLUMN IF NOT EXISTS "fully_fetched_at" timestamp with time zone;
--> statement-breakpoint
CREATE INDEX IF NOT EXISTS "vehicles_fully_fetched_idx" ON "vehicles" USING btree ("fully_fetched");

View File

@@ -0,0 +1,6 @@
-- Süper Panel lifecycle aksiyonları founderId olarak panelin Better Auth
-- kullanıcı ID'sini (32 karakter nanoid) gönderiyor; uuid kolonu bunu
-- reddedip suspend/ban'ı 500 ile düşürüyordu ("invalid input syntax for
-- type uuid"). Alan FK'sız salt audit → text. Mevcut UUID değerleri
-- USING ile aynen korunur.
ALTER TABLE "users" ALTER COLUMN "status_changed_by" TYPE text USING "status_changed_by"::text;

View File

@@ -225,6 +225,34 @@
"when": 1783092194145, "when": 1783092194145,
"tag": "0031_canonical_template_entries", "tag": "0031_canonical_template_entries",
"breakpoints": true "breakpoints": true
},
{
"idx": 32,
"version": "7",
"when": 1784023885041,
"tag": "0032_part_price_oe_reset",
"breakpoints": true
},
{
"idx": 33,
"version": "7",
"when": 1784027180912,
"tag": "0033_parts_oem_code_norm_idx",
"breakpoints": true
},
{
"idx": 34,
"version": "7",
"when": 1784965129879,
"tag": "0034_vehicle_fully_fetched",
"breakpoints": true
},
{
"idx": 35,
"version": "7",
"when": 1786440823041,
"tag": "0035_status_changed_by_text",
"breakpoints": true
} }
] ]
} }

View File

@@ -32,7 +32,9 @@ export const users = pgTable(
status: varchar("status", { length: 20 }).default("active").notNull(), status: varchar("status", { length: 20 }).default("active").notNull(),
statusReason: text("status_reason"), statusReason: text("status_reason"),
statusChangedAt: timestamp("status_changed_at", { withTimezone: true }), statusChangedAt: timestamp("status_changed_at", { withTimezone: true }),
statusChangedBy: uuid("status_changed_by"), // Süper Panel founder ID'si (Better Auth nanoid) — sase users.id UUID'si
// DEĞİL, o yüzden text. FK yok; salt audit alanı.
statusChangedBy: text("status_changed_by"),
referralCode: varchar("referral_code", { length: 20 }), referralCode: varchar("referral_code", { length: 20 }),
referredBy: uuid("referred_by"), referredBy: uuid("referred_by"),
// Reward days earned via referrals that couldn't be applied to a live // Reward days earned via referrals that couldn't be applied to a live
@@ -419,10 +421,20 @@ export const vehicles = pgTable(
market: varchar("market", { length: 100 }), market: varchar("market", { length: 100 }),
rawData: jsonb("raw_data"), rawData: jsonb("raw_data"),
source: varchar("source", { length: 20 }).default("pl24").notNull(), source: varchar("source", { length: 20 }).default("pl24").notNull(),
// Durable completeness marker: set true when the prefetch chain finishes with
// parts (see PrefetchWorkerService.incrementCompleted). Unlike the ephemeral
// Redis `prefetch:complete:*` marker (21-day TTL, operational skip logic) this
// never expires — it's the reliable "% fully fetched" measurement. `_at` tracks
// the last time completion was confirmed (re-set on each re-drill completion).
fullyFetched: boolean("fully_fetched").default(false).notNull(),
fullyFetchedAt: timestamp("fully_fetched_at", { withTimezone: true }),
createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(),
updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(), updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(),
}, },
(table) => [uniqueIndex("vehicles_vin_unique_idx").on(table.vin)], (table) => [
uniqueIndex("vehicles_vin_unique_idx").on(table.vin),
index("vehicles_fully_fetched_idx").on(table.fullyFetched),
],
); );
// ─── User Vehicles (junction — user ↔ shared vehicle) ─ // ─── User Vehicles (junction — user ↔ shared vehicle) ─

View File

@@ -33,7 +33,11 @@ export class CorgiService {
} }
private extractYear(vin: string): number | null { private extractYear(vin: string): number | null {
return extractModelYear(vin); // Corgi is a WMI-only decoder — it resolves brand + year but never a model.
// Signalling modelResolved:false lets extractModelYear roll a 30-year-ambiguous
// position-10 code (e.g. "T" = 1996-or-2026) back a cycle for an old-shaped
// Renault VIN, so a ~1996 R19 isn't mislabelled as a 2026 car (see vin-validator).
return extractModelYear(vin, undefined, { modelResolved: false });
} }
getBrandFromWmi(wmi: string): string | null { getBrandFromWmi(wmi: string): string | null {

View File

@@ -94,14 +94,16 @@ export class EmexBrowserService implements OnModuleInit, OnModuleDestroy {
this.semaphore = new Semaphore(MAX_CONCURRENT_PAGES); this.semaphore = new Semaphore(MAX_CONCURRENT_PAGES);
this.useProxy = this.configService.get<string>("EMEX_USE_PROXY", "true") === "true"; this.useProxy = this.configService.get<string>("EMEX_USE_PROXY", "true") === "true";
// Default dataimpulse: Floxy retired 2026-07 (permanently down). Set
// EMEX_PROXY_PROVIDER=floxy to re-enable it.
const rawProvider = this.configService const rawProvider = this.configService
.get<string>("EMEX_PROXY_PROVIDER", "floxy") .get<string>("EMEX_PROXY_PROVIDER", "dataimpulse")
.toLowerCase(); .toLowerCase();
this.proxyProvider = !this.useProxy this.proxyProvider = !this.useProxy
? "none" ? "none"
: rawProvider === "dataimpulse" || rawProvider === "none" : rawProvider === "floxy" || rawProvider === "none"
? (rawProvider as "dataimpulse" | "none") ? (rawProvider as "floxy" | "none")
: "floxy"; : "dataimpulse";
this.proxyHost = this.configService.get<string>("EMEX_PROXY_HOST", "74.81.81.81"); this.proxyHost = this.configService.get<string>("EMEX_PROXY_HOST", "74.81.81.81");
this.proxyPortStart = this.configService.get<number>("EMEX_PROXY_PORT_START", 10001); this.proxyPortStart = this.configService.get<number>("EMEX_PROXY_PORT_START", 10001);
this.proxyPortEnd = this.configService.get<number>("EMEX_PROXY_PORT_END", 10099); this.proxyPortEnd = this.configService.get<number>("EMEX_PROXY_PORT_END", 10099);
@@ -260,6 +262,42 @@ export class EmexBrowserService implements OnModuleInit, OnModuleDestroy {
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
}); });
// Block heavy resources to save proxy bandwidth. Scraping reads HTML/DOM
// only — schema-image URLs are parsed from the markup and their dims come
// from a separate Range GET, so the browser never needs images/fonts/CSS.
// Context-level route covers every tab (session establish + acquirePage).
await this.context.route("**/*", (route) => {
const url = route.request().url();
const type = route.request().resourceType();
if (["image", "font", "stylesheet", "media"].includes(type)) {
return route.abort();
}
// Third-party junk seen in proxy usage: analytics, ad networks, chat
// widgets, Google/Yandex assets, and our own ipify egress probe.
if (
url.includes("google-analytics.com") ||
url.includes("googletagmanager.com") ||
url.includes("mc.yandex.ru") ||
url.includes("yastatic.net") ||
url.includes("fonts.googleapis.com") ||
url.includes("fonts.gstatic.com") ||
url.includes("content-autofill.googleapis.com") ||
url.includes("facebook.net") ||
url.includes("doubleclick.net") ||
url.includes("hotjar.com") ||
url.includes("adsco.re") ||
url.includes("displayvertising.com") ||
url.includes("tidio.co") ||
url.includes("api.ipify.org")
) {
return route.abort();
}
return route.continue();
});
this.startedAt = Date.now(); this.startedAt = Date.now();
this.sessionExpiry = 0; // force session establish on first acquirePage this.sessionExpiry = 0; // force session establish on first acquirePage

View File

@@ -215,11 +215,15 @@ export class EmexService {
// random-port-per-call primary proved that), but a sticky Floxy IP across the // random-port-per-call primary proved that), but a sticky Floxy IP across the
// chained flow is still the safest choice — and avoids DataImpulse's ~50% dead // chained flow is still the safest choice — and avoids DataImpulse's ~50% dead
// ports that were eating the decode budget before reaching the Floxy fallback. // ports that were eating the decode budget before reaching the Floxy fallback.
// Default dataimpulse: Floxy retired 2026-07 (permanently down). Set
// EMEX_PROXY_PROVIDER=floxy to re-enable it.
this.emexProxyProvider = !useProxy this.emexProxyProvider = !useProxy
? "none" ? "none"
: (() => { : (() => {
const p = this.configService.get<string>("EMEX_PROXY_PROVIDER", "floxy").toLowerCase(); const p = this.configService
return p === "dataimpulse" || p === "none" ? p : "floxy"; .get<string>("EMEX_PROXY_PROVIDER", "dataimpulse")
.toLowerCase();
return p === "floxy" || p === "none" ? p : "dataimpulse";
})(); })();
// Default agent for the low-stakes image-dims path; fetchEmexHtml builds a // Default agent for the low-stakes image-dims path; fetchEmexHtml builds a
// fresh agent per request so a flaky exit can't pin every call. // fresh agent per request so a flaky exit can't pin every call.

View File

@@ -0,0 +1,98 @@
/**
* Parts-Catalogs capture asset cache.
*
* Every JWT capture opens a fresh browser context (empty HTTP cache) and
* re-downloads the SAME static widget assets through the billed residential
* proxy — measured ~2.2 MB/capture, ~93% of it the parts-catalogs widget
* bundle (`.../v3/bundle_<hash>.js`, identical across all partner sites) plus
* the sites' own versioned JS/CSS. At ~3–4k captures/day that is the single
* largest avoidable proxy cost (~20 GB/15d) with zero ban risk: the widget
* still runs (served from here) and still fires its token XHR live.
*
* This is a URL-keyed byte cache with a hot in-memory layer and a best-effort
* disk layer (survives redeploys). Only versioned static assets are cached —
* their URLs carry a content hash / `?_=<ver>` so a bundle bump is a new URL
* (cache miss → refetched once), i.e. invalidation is automatic. The token XHR
* (`/v3/api/proxy/*`) and HTML documents are never cached; they stay live.
*/
import { createHash } from "node:crypto";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
export interface CachedAsset {
contentType: string;
body: Buffer;
}
export class PcatAssetCache {
private readonly dir: string;
private readonly mem = new Map<string, CachedAsset>();
private readonly maxMemEntries: number;
private readonly ready: Promise<void>;
constructor(opts: { dir?: string; maxMemEntries?: number } = {}) {
this.dir = opts.dir ?? join(tmpdir(), "pcat-asset-cache");
this.maxMemEntries = opts.maxMemEntries ?? 300;
this.ready = mkdir(this.dir, { recursive: true }).then(
() => undefined,
() => undefined,
);
}
/**
* Only versioned static JS/CSS is cacheable. Never the token/API path, never
* HTML documents (may carry a per-session nonce the token call needs).
*/
static isCacheable(resourceType: string, url: string): boolean {
if (resourceType !== "script" && resourceType !== "stylesheet") return false;
if (url.includes("/v3/api/proxy/")) return false;
return true;
}
private fileKey(url: string): string {
return createHash("sha1").update(url).digest("hex");
}
async get(url: string): Promise<CachedAsset | null> {
const hot = this.mem.get(url);
if (hot) return hot;
await this.ready;
const key = this.fileKey(url);
try {
const [meta, body] = await Promise.all([
readFile(join(this.dir, `${key}.json`), "utf8"),
readFile(join(this.dir, `${key}.bin`)),
]);
const asset: CachedAsset = { contentType: JSON.parse(meta).contentType, body };
this.remember(url, asset);
return asset;
} catch {
return null;
}
}
async put(url: string, contentType: string, body: Buffer): Promise<void> {
if (!body.length) return;
this.remember(url, { contentType, body });
await this.ready;
const key = this.fileKey(url);
try {
await Promise.all([
writeFile(join(this.dir, `${key}.bin`), body),
writeFile(join(this.dir, `${key}.json`), JSON.stringify({ contentType, url })),
]);
} catch {
// Disk is best-effort; the in-memory layer still serves this process.
}
}
private remember(url: string, asset: CachedAsset): void {
// Cheap FIFO bound — versioned URLs keep the working set small anyway.
if (this.mem.size >= this.maxMemEntries) {
const oldest = this.mem.keys().next().value;
if (oldest !== undefined) this.mem.delete(oldest);
}
this.mem.set(url, asset);
}
}

View File

@@ -30,6 +30,7 @@ import {
isProxyConnectFailure, isProxyConnectFailure,
resolveExitIp, resolveExitIp,
} from "../proxy-telemetry/proxy-telemetry.service"; } from "../proxy-telemetry/proxy-telemetry.service";
import { PcatAssetCache } from "./parts-catalogs-asset-cache";
import { JwtSlot, PcatJwtToken, PcatSession } from "./parts-catalogs.types"; import { JwtSlot, PcatJwtToken, PcatSession } from "./parts-catalogs.types";
// Shared single-slot cache so dev + prod (and any restarted container) can // Shared single-slot cache so dev + prod (and any restarted container) can
@@ -195,6 +196,13 @@ export class PartsCatalogsAuthService implements OnModuleInit, OnModuleDestroy {
// the exact failure seen 2026-06-11 (Floxy 402) and 2026-07-03 (Floxy tunnel // the exact failure seen 2026-06-11 (Floxy 402) and 2026-07-03 (Floxy tunnel
// down). Disable with PCAT_CAPTURE_ALLOW_DIRECT=false. // down). Disable with PCAT_CAPTURE_ALLOW_DIRECT=false.
private readonly captureAllowDirect: boolean; private readonly captureAllowDirect: boolean;
// Exit-IP telemetry probe (one ipify call per capture). Off by default: it
// added ~54k billed proxy requests over 15 days for banned-IP telemetry only.
private readonly exitIpProbe: boolean;
// Cross-capture cache for the widget's static JS/CSS so each capture stops
// re-downloading ~2 MB of identical assets through the residential proxy.
// Null when disabled via PCAT_ASSET_CACHE=false (kill switch, no redeploy).
private readonly assetCache: PcatAssetCache | null;
constructor( constructor(
private configService: ConfigService, private configService: ConfigService,
@@ -216,13 +224,16 @@ export class PartsCatalogsAuthService implements OnModuleInit, OnModuleDestroy {
this.semaphore = new Semaphore(this.jwtSites.length); this.semaphore = new Semaphore(this.jwtSites.length);
// Provider selection. Back-compat: PCAT_USE_PROXY=false still forces direct. // Provider selection. Back-compat: PCAT_USE_PROXY=false still forces direct.
const rawProvider = cfg.get<string>("PCAT_PROXY_PROVIDER", "floxy").toLowerCase(); // Default is dataimpulse: Floxy was retired 2026-07 (permanently down —
// balance/tunnel dead), so floxy-primary just burned a failed attempt per
// call before failing over. Set PCAT_PROXY_PROVIDER=floxy to re-enable it.
const rawProvider = cfg.get<string>("PCAT_PROXY_PROVIDER", "dataimpulse").toLowerCase();
const useProxy = cfg.get<string>("PCAT_USE_PROXY", "true") === "true"; const useProxy = cfg.get<string>("PCAT_USE_PROXY", "true") === "true";
this.proxyProvider = !useProxy this.proxyProvider = !useProxy
? "none" ? "none"
: rawProvider === "dataimpulse" || rawProvider === "none" : rawProvider === "floxy" || rawProvider === "none"
? (rawProvider as ProxyProvider) ? (rawProvider as ProxyProvider)
: "floxy"; : "dataimpulse";
const toInt = (key: string, def: number): number => { const toInt = (key: string, def: number): number => {
const n = Number(cfg.get(key, def)); const n = Number(cfg.get(key, def));
@@ -242,6 +253,9 @@ export class PartsCatalogsAuthService implements OnModuleInit, OnModuleDestroy {
this.diHost = cfg.get<string>("PCAT_PROXY_HOST", DI_HOST); this.diHost = cfg.get<string>("PCAT_PROXY_HOST", DI_HOST);
this.diUser = cfg.get<string>("PCAT_PROXY_USER", DI_DEFAULT_USER); this.diUser = cfg.get<string>("PCAT_PROXY_USER", DI_DEFAULT_USER);
this.diPass = cfg.get<string>("PCAT_PROXY_PASS", DI_DEFAULT_PASS); this.diPass = cfg.get<string>("PCAT_PROXY_PASS", DI_DEFAULT_PASS);
this.exitIpProbe = cfg.get<string>("PCAT_EXIT_IP_PROBE", "false") === "true";
this.assetCache =
cfg.get<string>("PCAT_ASSET_CACHE", "true") === "true" ? new PcatAssetCache() : null;
this.captureAllowDirect = this.captureAllowDirect =
cfg.get<string>("PCAT_CAPTURE_ALLOW_DIRECT", "true") !== "false" && cfg.get<string>("PCAT_CAPTURE_ALLOW_DIRECT", "true") !== "false" &&
@@ -806,7 +820,10 @@ export class PartsCatalogsAuthService implements OnModuleInit, OnModuleDestroy {
// The session is sticky, so a parallel ipify probe exits from the SAME IP // The session is sticky, so a parallel ipify probe exits from the SAME IP
// the capture will use — that's what makes banned-IP tracking concrete. // the capture will use — that's what makes banned-IP tracking concrete.
// Resolves in ~1-2s while the capture itself takes 7s+; never throws. // Resolves in ~1-2s while the capture itself takes 7s+; never throws.
const exitIpPromise = proxyUrl ? resolveExitIp(proxyUrl) : Promise.resolve(null); // Gated off by default (PCAT_EXIT_IP_PROBE): the probe is billed proxy
// traffic and only feeds exit-IP telemetry, not the capture itself.
const exitIpPromise =
this.exitIpProbe && proxyUrl ? resolveExitIp(proxyUrl) : Promise.resolve(null);
const logCapture = (ok: boolean, errorKind?: string): void => { const logCapture = (ok: boolean, errorKind?: string): void => {
void exitIpPromise.then((exitIp) => void exitIpPromise.then((exitIp) =>
this.proxyTelemetry.record({ this.proxyTelemetry.record({
@@ -856,8 +873,15 @@ export class PartsCatalogsAuthService implements OnModuleInit, OnModuleDestroy {
this.logger.debug(`Token intercepted (key=${apiKey.slice(0, 16)}...)`); this.logger.debug(`Token intercepted (key=${apiKey.slice(0, 16)}...)`);
}); });
// Block heavy resources to save proxy bandwidth // Block heavy resources to save proxy bandwidth. Kept intentionally
await page.route("**/*", (route) => { // minimal: an aggressive block (stylesheet + yastatic/font/ad domains)
// shipped 2026-07-16 killed token capture on prod (dataimpulse 425→0
// captures/h at deploy time — the RU catalog widget needs its CSS and
// Yandex-hosted runtime to init and fire the /v3/api/proxy XHR). Only
// block what the widget provably never needs: images, fonts, media, and
// a few pure analytics/ad domains.
const assetCache = this.assetCache;
await page.route("**/*", async (route) => {
const url = route.request().url(); const url = route.request().url();
const type = route.request().resourceType(); const type = route.request().resourceType();
@@ -878,6 +902,29 @@ export class PartsCatalogsAuthService implements OnModuleInit, OnModuleDestroy {
return route.abort(); return route.abort();
} }
// Serve versioned static JS/CSS from the cross-capture cache; a hit
// costs zero proxy bytes. On miss, fetch once through the context proxy,
// store the decoded body, and serve it. Everything else (HTML document,
// the /v3/api/proxy token XHR, dynamic fetches) always goes live.
if (assetCache && PcatAssetCache.isCacheable(type, url)) {
const hit = await assetCache.get(url);
if (hit) {
return route.fulfill({ status: 200, contentType: hit.contentType, body: hit.body });
}
try {
const resp = await route.fetch({ timeout: 15_000 });
const body = await resp.body();
const contentType =
resp.headers()["content-type"] ??
(type === "script" ? "application/javascript" : "text/css");
if (resp.ok() && body.length) void assetCache.put(url, contentType, body);
return route.fulfill({ status: resp.status(), contentType, body });
} catch {
// Fetch failed (slow/dead proxy) — let the browser attempt it itself.
return route.continue();
}
}
return route.continue(); return route.continue();
}); });

View File

@@ -0,0 +1,213 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { VinpinDaemonService } from "./vinpin-daemon.service";
import type { VinpinDriverService } from "./vinpin-driver.service";
/**
* Unit tests for the Vinpin warm-session daemon lifecycle: the business-hours
* scheduler (warm/teardown reconciliation with an injected clock), warm-on-demand
* decode routing, and the reentrancy guard. The driver is a fake — the real seat
* lives on prod and can't be driven from a test.
*/
interface FakeDriver {
isWarm: ReturnType<typeof vi.fn>;
warmUp: ReturnType<typeof vi.fn>;
teardownWarm: ReturnType<typeof vi.fn>;
decode: ReturnType<typeof vi.fn>;
keepalivePing: ReturnType<typeof vi.fn>;
}
function makeDriver(warm = false): FakeDriver {
return {
isWarm: vi.fn(() => warm),
warmUp: vi.fn(async () => true),
teardownWarm: vi.fn(async () => undefined),
decode: vi.fn(async () => null),
keepalivePing: vi.fn(async () => undefined),
};
}
function daemon(driver: FakeDriver, opts: { hours: boolean; enabled?: boolean }) {
return new VinpinDaemonService({
driver: driver as unknown as VinpinDriverService,
isBusinessHours: () => opts.hours,
isEnabled: () => opts.enabled ?? true,
});
}
describe("VinpinDaemonService — scheduler reconcile", () => {
afterEach(() => vi.restoreAllMocks());
it("warms up inside business hours when enabled and not already warm", async () => {
const driver = makeDriver(false);
await daemon(driver, { hours: true }).reconcile();
expect(driver.warmUp).toHaveBeenCalledTimes(1);
expect(driver.teardownWarm).not.toHaveBeenCalled();
});
it("does NOT re-warm when already warm inside hours", async () => {
const driver = makeDriver(true);
await daemon(driver, { hours: true }).reconcile();
expect(driver.warmUp).not.toHaveBeenCalled();
expect(driver.teardownWarm).not.toHaveBeenCalled();
});
it("tears down the warm seat outside business hours", async () => {
const driver = makeDriver(true);
await daemon(driver, { hours: false }).reconcile();
expect(driver.teardownWarm).toHaveBeenCalledTimes(1);
expect(driver.warmUp).not.toHaveBeenCalled();
});
it("tears down a warm seat when the daemon is disabled (kill-switch)", async () => {
const driver = makeDriver(true);
await daemon(driver, { hours: true, enabled: false }).reconcile();
expect(driver.teardownWarm).toHaveBeenCalledTimes(1);
expect(driver.warmUp).not.toHaveBeenCalled();
});
it("does nothing when disabled and already cold", async () => {
const driver = makeDriver(false);
await daemon(driver, { hours: true, enabled: false }).reconcile();
expect(driver.warmUp).not.toHaveBeenCalled();
expect(driver.teardownWarm).not.toHaveBeenCalled();
});
it("does not stack overlapping reconciles (reentrancy guard)", async () => {
const driver = makeDriver(false);
let release!: () => void;
driver.warmUp.mockImplementation(
() =>
new Promise<boolean>((resolve) => {
release = () => resolve(true);
}),
);
const d = daemon(driver, { hours: true });
const first = d.reconcile();
const second = d.reconcile(); // should early-return while the first is in flight
release();
await Promise.all([first, second]);
expect(driver.warmUp).toHaveBeenCalledTimes(1);
});
});
describe("VinpinDaemonService — decode routing", () => {
afterEach(() => vi.restoreAllMocks());
it("warms on-demand then delegates when inside hours and cold", async () => {
const driver = makeDriver(false);
driver.decode.mockResolvedValue({ brand: "Fiat", model: "EGEA" });
const result = await daemon(driver, { hours: true }).decode("NM435600006H43436");
expect(driver.warmUp).toHaveBeenCalledTimes(1);
expect(driver.decode).toHaveBeenCalledWith("NM435600006H43436");
expect(result).toEqual({ brand: "Fiat", model: "EGEA" });
});
it("does NOT warm on-demand when already warm — just delegates", async () => {
const driver = makeDriver(true);
await daemon(driver, { hours: true }).decode("NM435600006H43436");
expect(driver.warmUp).not.toHaveBeenCalled();
expect(driver.decode).toHaveBeenCalledTimes(1);
});
it("off-hours delegates straight to the cold path (never holds the seat)", async () => {
const driver = makeDriver(false);
await daemon(driver, { hours: false }).decode("NM435600006H43436");
expect(driver.warmUp).not.toHaveBeenCalled();
expect(driver.decode).toHaveBeenCalledTimes(1);
});
it("returns null (never throws) if the driver decode rejects", async () => {
const driver = makeDriver(true);
driver.decode.mockRejectedValue(new Error("boom"));
const result = await daemon(driver, { hours: true }).decode("NM435600006H43436");
expect(result).toBeNull();
});
});
describe("VinpinDaemonService — warm-up backoff", () => {
afterEach(() => vi.restoreAllMocks());
function backoffDaemon(driver: FakeDriver, clock: { t: number }) {
return new VinpinDaemonService({
driver: driver as unknown as VinpinDriverService,
isBusinessHours: () => true,
isEnabled: () => true,
now: () => clock.t,
});
}
it("a failed warmUp sets a cooldown that reconcile() respects (no immediate re-warm)", async () => {
const driver = makeDriver(false);
driver.warmUp.mockResolvedValue(false); // warm-up keeps failing
const clock = { t: 0 };
const d = backoffDaemon(driver, clock);
await d.reconcile();
expect(driver.warmUp).toHaveBeenCalledTimes(1); // first attempt ran
// Still cold + in hours, but inside the cooldown → no second attempt.
clock.t = 30_000;
await d.reconcile();
expect(driver.warmUp).toHaveBeenCalledTimes(1);
// After the base cooldown (60s) elapses → it tries again.
clock.t = 61_000;
await d.reconcile();
expect(driver.warmUp).toHaveBeenCalledTimes(2);
});
it("warm-on-demand decode ALSO respects the cooldown, but still delegates the cold decode", async () => {
const driver = makeDriver(false);
driver.warmUp.mockResolvedValue(false);
const clock = { t: 0 };
const d = backoffDaemon(driver, clock);
await d.reconcile(); // fails → cooldown until 60_000
expect(driver.warmUp).toHaveBeenCalledTimes(1);
clock.t = 20_000;
await d.decode("NM435600006H43436"); // in cooldown → no warm-on-demand
expect(driver.warmUp).toHaveBeenCalledTimes(1);
expect(driver.decode).toHaveBeenCalledTimes(1); // still decodes via the cold path
});
it("a successful warm resets the backoff (next attempt is not blocked)", async () => {
const driver = makeDriver(false);
driver.warmUp.mockResolvedValueOnce(false).mockResolvedValueOnce(true).mockResolvedValue(false);
const clock = { t: 0 };
const d = backoffDaemon(driver, clock);
await d.reconcile(); // fail → cooldown until 60_000
clock.t = 61_000;
await d.reconcile(); // success → cooldown reset
expect(driver.warmUp).toHaveBeenCalledTimes(2);
// isWarm() is still false in the fake, so reconcile would warm again — and with
// the cooldown reset it may attempt immediately (no leftover backoff window).
clock.t = 61_500;
await d.reconcile();
expect(driver.warmUp).toHaveBeenCalledTimes(3);
});
});
describe("VinpinDaemonService — start/stop lifecycle", () => {
beforeEach(() => vi.useFakeTimers());
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
});
it("reconciles on start and drives keepalive on the interval; stop tears down", async () => {
const driver = makeDriver(false);
const d = daemon(driver, { hours: true });
d.start();
// Immediate reconcile → warm.
await vi.waitFor(() => expect(driver.warmUp).toHaveBeenCalledTimes(1));
// Advance past a keepalive interval → a ping fires.
await vi.advanceTimersByTimeAsync(80_000);
expect(driver.keepalivePing).toHaveBeenCalled();
await d.stop();
expect(driver.teardownWarm).toHaveBeenCalled();
});
});

View File

@@ -0,0 +1,195 @@
/**
* Vinpin warm-session daemon (worker-process singleton).
*
* Owns the LIFECYCLE of the persistent warm Vinpin seat, on top of the browser
* mechanics in VinpinDriverService:
* - a scheduler that warms the seat at 08:00 and tears it down at 21:00
* Europe/Istanbul (and warms on worker start if already inside the window),
* - an idle keepalive that nudges the RDS session every ~75s so it never drops,
* - `decode(vin)` — the entry the vinpin-decode processor calls. Inside business
* hours it makes sure the seat is warm (warming on-demand once), then delegates
* to the driver, which self-routes to the HOT warm path when warm and the
* proven COLD per-decode path otherwise. Outside hours it never holds the seat
* — the driver's cold path handles the decode and is torn down after.
*
* ADDITIVE + fail-safe: every warm operation degrades to the cold path, and
* `decode()` never throws (the driver returns null on any failure). Gated by
* VINPIN_ENABLED (feature flag) and VINPIN_WARM_DAEMON (kill-switch: set to
* "false" to force the legacy per-decode cold path with the daemon inert).
*/
import { Logger } from "@nestjs/common";
import { getVinpinDriver } from "./vinpin-driver.service";
import type { VinpinDecodeResult, VinpinDriverService } from "./vinpin-driver.service";
import { VINPIN_WARM, isVinpinBusinessHours } from "./vinpin.constants";
/** Whether the warm daemon is allowed to run (feature flag + kill-switch). */
export function isVinpinWarmDaemonEnabled(): boolean {
return process.env.VINPIN_ENABLED === "true" && process.env.VINPIN_WARM_DAEMON !== "false";
}
export interface VinpinDaemonDeps {
/** Driver singleton (injectable for tests). Defaults to the process-wide one. */
driver?: VinpinDriverService;
/** Business-hours predicate (injectable so tests can drive the clock). */
isBusinessHours?: () => boolean;
/** Warm-daemon enabled predicate (injectable for tests). */
isEnabled?: () => boolean;
/** Monotonic-ish clock (injectable so tests can drive the warm-up backoff). */
now?: () => number;
}
export class VinpinDaemonService {
private readonly logger = new Logger(VinpinDaemonService.name);
private readonly driver: VinpinDriverService;
private readonly isBusinessHours: () => boolean;
private readonly isEnabled: () => boolean;
private readonly now: () => number;
private schedulerTimer: ReturnType<typeof setInterval> | null = null;
private keepaliveTimer: ReturnType<typeof setInterval> | null = null;
private reconciling = false;
private started = false;
// ─── Warm-up backoff ─────────────────────────────────────
/** Wall-clock time until which a re-warm is suppressed after a failed warmUp.
* Both reconcile() and decode()'s warm-on-demand honour this so a failing seat
* isn't hammered every ~60s (each failed attempt would leave a fresh dirty
* window). A successful warm resets it. */
private warmCooldownUntil = 0;
/** Current backoff span (ms): 0 when healthy, else base…max, doubling per
* consecutive failure. */
private warmBackoffMs = 0;
constructor(deps: VinpinDaemonDeps = {}) {
this.driver = deps.driver ?? getVinpinDriver();
this.isBusinessHours = deps.isBusinessHours ?? (() => isVinpinBusinessHours());
this.isEnabled = deps.isEnabled ?? isVinpinWarmDaemonEnabled;
this.now = deps.now ?? (() => Date.now());
}
/** True while a failed warmUp's cooldown is still in effect. */
private inWarmCooldown(): boolean {
return this.now() < this.warmCooldownUntil;
}
/**
* Record a warm-up outcome and update the backoff. Success clears the cooldown;
* failure sets/extends it (base, then exponential up to max). Returns `ok` so
* callers can chain.
*/
private noteWarmResult(ok: boolean): boolean {
if (ok) {
this.warmBackoffMs = 0;
this.warmCooldownUntil = 0;
} else {
this.warmBackoffMs =
this.warmBackoffMs === 0
? VINPIN_WARM.warmBackoffBaseMs
: Math.min(this.warmBackoffMs * 2, VINPIN_WARM.warmBackoffMaxMs);
this.warmCooldownUntil = this.now() + this.warmBackoffMs;
this.logger.warn(
`warmUp failed — backing off ${Math.round(this.warmBackoffMs / 1000)}s before the next attempt`,
);
}
return ok;
}
/** Start the scheduler + keepalive loops (idempotent). */
start(): void {
if (this.started) return;
this.started = true;
// Reconcile once now (warm immediately if the worker booted inside hours).
void this.reconcile();
this.schedulerTimer = setInterval(() => {
void this.reconcile();
}, VINPIN_WARM.schedulerIntervalMs);
this.keepaliveTimer = setInterval(() => {
void this.driver.keepalivePing();
}, VINPIN_WARM.keepaliveIntervalMs);
// Don't keep the event loop alive just for these timers.
this.schedulerTimer.unref?.();
this.keepaliveTimer.unref?.();
this.logger.log(
`Vinpin warm daemon started (enabled=${this.isEnabled()}, hours ${VINPIN_WARM.businessStartHour}:00–${VINPIN_WARM.businessEndHour}:00 Europe/Istanbul)`,
);
}
/** Stop the loops and tear the warm seat down (worker shutdown). */
async stop(): Promise<void> {
if (this.schedulerTimer) clearInterval(this.schedulerTimer);
if (this.keepaliveTimer) clearInterval(this.keepaliveTimer);
this.schedulerTimer = null;
this.keepaliveTimer = null;
this.started = false;
await this.driver.teardownWarm().catch(() => undefined);
}
/**
* Reconcile the warm seat against the schedule: warm up when enabled + inside
* hours + not already warm; tear down when warm but disabled or outside hours.
* Guards against overlapping runs (a slow warmUp must not stack). Never throws.
*/
async reconcile(): Promise<void> {
if (this.reconciling) return;
this.reconciling = true;
try {
const enabled = this.isEnabled();
const inHours = this.isBusinessHours();
if (enabled && inHours && !this.driver.isWarm()) {
if (this.inWarmCooldown()) {
this.logger.debug("scheduler: in warm-up backoff — skipping this cycle");
} else {
this.logger.log("scheduler: inside business hours — warming the seat");
this.noteWarmResult(await this.driver.warmUp());
}
} else if (this.driver.isWarm() && (!enabled || !inHours)) {
this.logger.log("scheduler: outside business hours / disabled — tearing the seat down");
await this.driver.teardownWarm();
// Intentional teardown → clear any stale warm-up backoff so the next window
// (e.g. tomorrow 08:00) isn't blocked by a leftover cooldown.
this.warmBackoffMs = 0;
this.warmCooldownUntil = 0;
}
} catch (err) {
this.logger.warn(`reconcile failed: ${(err as Error).message}`);
} finally {
this.reconciling = false;
}
}
/**
* Decode entry the processor calls. Inside hours, ensure the seat is warm (warm
* on-demand once), then delegate to the driver — which uses the hot warm path
* when warm, else the cold per-decode path. Off-hours, delegate straight to the
* driver's cold path (no seat held). Never throws — returns null on any failure.
*/
async decode(vin: string): Promise<VinpinDecodeResult | null> {
try {
if (
this.isEnabled() &&
this.isBusinessHours() &&
!this.driver.isWarm() &&
!this.inWarmCooldown()
) {
// Warm-on-demand: a decode arrived inside hours before the scheduler warmed
// (e.g. right after 08:00, or after a drop). Best-effort — if it fails the
// driver silently runs the cold path for this decode, and the backoff spaces
// out the next warm attempt (respected by both this check and reconcile()).
this.noteWarmResult(await this.driver.warmUp().catch(() => false));
}
return await this.driver.decode(vin);
} catch (err) {
// Defensive: driver.decode never throws, but guarantee the processor a null.
this.logger.warn(`decode(${vin}) unexpected error: ${(err as Error).message}`);
return null;
}
}
}
// ─── Worker singleton ────────────────────────────────────────
let daemonSingleton: VinpinDaemonService | null = null;
export function getVinpinDaemon(): VinpinDaemonService {
if (!daemonSingleton) daemonSingleton = new VinpinDaemonService();
return daemonSingleton;
}

View File

@@ -0,0 +1,680 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
/**
* Renault-decode robustness tests (Rpartstore-down hardening). These exercise the
* fixes that stop a DOWN Rpartstore from thrashing the shared seat:
* (2) ensureRpartstore no longer short-circuits "already open" on the flyout /
* window-title word "Rpartstore" — it gates on a CONTENT token and clicks the
* flyout entry when the submenu is up over the grid;
* (3) closeRpartstoreTab never clicks the language-selector coord (1298,14);
* (6) an in-memory cooldown routes Renault decodes straight to Dialogys during a
* persistent Rpartstore outage, and a successful load clears it.
* OCR is mocked so the screen-state sequence is fully controllable — the real seat
* lives on prod and can't be driven from a test.
*/
vi.mock("./vinpin.ocr", () => ({
ocrRegion: vi.fn(async () => ""),
pollForText: vi.fn(async () => ({ matched: false, text: "" })),
terminateOcr: vi.fn(async () => undefined),
}));
import { VinpinDriverService } from "./vinpin-driver.service";
import { VINPIN_COORDS } from "./vinpin.constants";
import { ocrRegion } from "./vinpin.ocr";
const mockOcr = vi.mocked(ocrRegion);
type AnyDriver = Record<string, unknown>;
function fakePage(sink?: (x: number, y: number) => void) {
return {
isClosed: () => false,
frames: () => [] as unknown[],
mouse: {
click: vi.fn(async (x: number, y: number) => sink?.(x, y)),
move: vi.fn(async () => undefined),
down: vi.fn(async () => undefined),
up: vi.fn(async () => undefined),
},
keyboard: { press: vi.fn(async () => undefined) },
waitForTimeout: vi.fn(async () => undefined),
locator: () => ({
first: () => ({
count: async () => 0,
isVisible: async () => false,
click: async () => undefined,
}),
}),
};
}
describe("VinpinDriverService — ensureRpartstore flyout false-positive (change 2)", () => {
const savedEnv = { ...process.env };
beforeEach(() => {
process.env.VINPIN_ENABLED = "true";
mockOcr.mockReset();
});
afterEach(() => {
vi.restoreAllMocks();
process.env = { ...savedEnv };
});
const ensure = (driver: VinpinDriverService, page: unknown) =>
((driver as unknown as AnyDriver).ensureRpartstore as (p: unknown) => Promise<boolean>).call(
driver,
page,
);
it("does NOT declare Rpartstore open on the FLYOUT — it clicks the Rpartstore entry (584,779)", async () => {
const driver = new VinpinDriverService();
const page = fakePage();
// Flyout is open OVER the grid: brand tiles visible + the Renault submenu items
// "Rpartstore"/"Dialogys" — matches renaultSubmenu but has NO search-home content.
mockOcr
.mockResolvedValueOnce("Volkswagen Mitsubishi TecDoc Renault Rpartstore Dialogys")
.mockResolvedValue("Şasi no ile arama Güncel araçlar"); // then the LOADED home
const ok = await ensure(driver, page);
expect(ok).toBe(true);
// The flyout Rpartstore entry was clicked (old code short-circuited without it).
expect(page.mouse.click).toHaveBeenCalledWith(
VINPIN_COORDS.renaultRpartstore.x,
VINPIN_COORDS.renaultRpartstore.y,
);
});
it("short-circuits (no flyout/tile click) when the LOADED search-home content is already on screen", async () => {
const driver = new VinpinDriverService();
const page = fakePage();
mockOcr.mockResolvedValue("Şasi no ile arama Ne arıyorsunuz Güncel araçlar");
expect(await ensure(driver, page)).toBe(true);
expect(page.mouse.click).not.toHaveBeenCalledWith(
VINPIN_COORDS.renaultRpartstore.x,
VINPIN_COORDS.renaultRpartstore.y,
);
expect(page.mouse.move).not.toHaveBeenCalledWith(
VINPIN_COORDS.renaultBrand.x,
VINPIN_COORDS.renaultBrand.y,
);
});
it("treats an open Rpartstore WINDOW (title only, no grid behind) as present without re-clicking the flyout", async () => {
const driver = new VinpinDriverService();
const page = fakePage();
// Window title bar "Renault Rpartstore" matches renaultSubmenu too, but there's
// NO grid behind it → must be handled by the open-window branch, not the flyout.
mockOcr.mockResolvedValue("Renault Rpartstore");
expect(await ensure(driver, page)).toBe(true);
expect(page.mouse.click).not.toHaveBeenCalledWith(
VINPIN_COORDS.renaultRpartstore.x,
VINPIN_COORDS.renaultRpartstore.y,
);
});
it("bails on the FIRST iteration when the DOWN launch-error modal is over the grid (no repeated flyout clicks)", async () => {
const driver = new VinpinDriverService();
const page = fakePage();
// DOWN Rpartstore: the launch-error modal sits OVER the brand grid. The FULL-frame
// read (no clip) sees the grid tiles + the modal TITLE "Renault Rpartstore" → it
// matches brandGrid AND renaultSubmenu, which — without the fix — makes the flyout
// branch re-click renaultRpartstore(584,779) on all ~6 iterations. The UPSCALED
// modal crop (clip passed) reads the Cyrillic launch error, so the launch-error
// short-circuit must fire and return false on iteration 1.
mockOcr.mockImplementation(async (_page: unknown, clip?: unknown) =>
clip
? "Owwu6ka 3anycka KaTanora" // upscaled modal crop → matches rpartstoreLaunchError
: "Volkswagen Mitsubishi Renault Rpartstore Dialogys",
);
const ok = await ensure(driver, page);
expect(ok).toBe(false);
// Never re-clicked the flyout Rpartstore entry (would be up to 6× without the fix).
expect(page.mouse.click).not.toHaveBeenCalledWith(
VINPIN_COORDS.renaultRpartstore.x,
VINPIN_COORDS.renaultRpartstore.y,
);
// Exactly ONE full-frame OCR read (no clip) proves it bailed on the first iteration
// rather than looping the 6-try budget.
const fullFrameReads = mockOcr.mock.calls.filter(([, clip]) => clip === undefined);
expect(fullFrameReads).toHaveLength(1);
});
it("still enters the flyout branch when the modal crop is ILLEGIBLE (no ffmpeg) — behaviour unchanged", async () => {
const driver = new VinpinDriverService();
const page = fakePage();
// Same grid+flyout-title screen, but the crop OCR yields no launch-error text (the
// no-ffmpeg / illegible case). The launch-error short-circuit must NOT fire, so the
// proven flyout path still runs and clicks the Rpartstore entry.
mockOcr.mockImplementation(async (_page: unknown, clip?: unknown) =>
clip
? "" // illegible crop → rpartstoreLaunchErrorPresent === false
: "Volkswagen Mitsubishi Renault Rpartstore Dialogys",
);
// Bounded loop; we only assert the flyout entry was clicked (grid+submenu branch).
await ensure(driver, page);
expect(page.mouse.click).toHaveBeenCalledWith(
VINPIN_COORDS.renaultRpartstore.x,
VINPIN_COORDS.renaultRpartstore.y,
);
});
});
describe("VinpinDriverService — closeRpartstoreTab never hits the language selector (change 3)", () => {
const savedEnv = { ...process.env };
beforeEach(() => {
process.env.VINPIN_ENABLED = "true";
mockOcr.mockReset();
});
afterEach(() => {
vi.restoreAllMocks();
process.env = { ...savedEnv };
});
const close = (driver: VinpinDriverService, page: unknown) =>
((driver as unknown as AnyDriver).closeRpartstoreTab as (p: unknown) => Promise<void>).call(
driver,
page,
);
it("uses the tab-✕ (93,45) + Escape and NEVER clicks windowClose (1298,14) on a stuck spinner", async () => {
const driver = new VinpinDriverService();
const page = fakePage();
// Chrome/spinner only (no search-home content) → the second close must NOT fire.
mockOcr.mockResolvedValue("Renault Rpartstore");
await close(driver, page);
expect(page.mouse.click).toHaveBeenCalledWith(
VINPIN_COORDS.catalogTabClose.x,
VINPIN_COORDS.catalogTabClose.y,
);
expect(page.mouse.click).not.toHaveBeenCalledWith(
VINPIN_COORDS.windowClose.x,
VINPIN_COORDS.windowClose.y,
);
expect(page.keyboard.press).toHaveBeenCalledWith("Escape");
// Exactly ONE close click (no content → no retry).
const closeClicks = page.mouse.click.mock.calls.filter(
([x, y]) => x === VINPIN_COORDS.catalogTabClose.x && y === VINPIN_COORDS.catalogTabClose.y,
);
expect(closeClicks).toHaveLength(1);
});
it("retries the tab-✕ (NOT windowClose) when a LOADED home is still up after the first close", async () => {
const driver = new VinpinDriverService();
const page = fakePage();
mockOcr.mockResolvedValue("Şasi no ile arama Güncel araçlar"); // loaded home persists
await close(driver, page);
const closeClicks = page.mouse.click.mock.calls.filter(
([x, y]) => x === VINPIN_COORDS.catalogTabClose.x && y === VINPIN_COORDS.catalogTabClose.y,
);
expect(closeClicks).toHaveLength(2); // first + one content-gated retry
expect(page.mouse.click).not.toHaveBeenCalledWith(
VINPIN_COORDS.windowClose.x,
VINPIN_COORDS.windowClose.y,
);
});
});
describe("VinpinDriverService — Rpartstore-down cooldown routes Renault → Dialogys (change 6)", () => {
const savedEnv = { ...process.env };
const FAR_DEADLINE = () => Date.now() + 5 * 60_000;
beforeEach(() => {
process.env.VINPIN_ENABLED = "true";
process.env.VINPIN_USER = "user";
process.env.VINPIN_PASS = "pass";
mockOcr.mockReset();
});
afterEach(() => {
vi.restoreAllMocks();
process.env = { ...savedEnv };
});
const inCooldown = (driver: VinpinDriverService) =>
((driver as unknown as AnyDriver).rpartstoreInCooldown as () => boolean).call(driver);
const acquire = (driver: VinpinDriverService, page: unknown, warm: boolean) =>
(
(driver as unknown as AnyDriver).acquireLoadedRpartstore as (
p: unknown,
c: unknown,
d: number,
w: boolean,
) => Promise<boolean>
).call(driver, page, {}, FAR_DEADLINE(), warm);
it("while in cooldown, warm Renault decode SKIPS Rpartstore entirely and uses Dialogys", async () => {
const driver = new VinpinDriverService();
const any = driver as unknown as AnyDriver;
any.rpartstoreCooldownUntil = Date.now() + 60_000; // cooldown active
const acquireSpy = vi.spyOn(any as never, "acquireLoadedRpartstore");
const runRpartstore = vi.spyOn(any as never, "runRpartstore");
vi.spyOn(any as never, "ensureWarmWindow").mockResolvedValue(true as never);
vi.spyOn(any as never, "runDialogysSearch").mockResolvedValue({
status: "found",
parsed: { brand: "RENAULT", model: "MEGANE", modelYear: null },
rawText: "Megane",
via: "dialogys",
} as never);
const page = { keyboard: { press: vi.fn(async () => undefined) } };
const result = await (
any.warmRenaultDecode as (p: unknown, v: string, c: unknown, d: number) => Promise<unknown>
).call(driver, page, "VF1LM1B0A37829019", { rpartstoreEnabled: true }, FAR_DEADLINE());
expect(acquireSpy).not.toHaveBeenCalled(); // Rpartstore never opened during the outage
expect(runRpartstore).not.toHaveBeenCalled();
expect(result).toMatchObject({
brand: "RENAULT",
model: "MEGANE",
raw: { source: "vinpin-dialogys" },
});
});
it("a hard launch-error SETS the cooldown", async () => {
const driver = new VinpinDriverService();
const any = driver as unknown as AnyDriver;
vi.spyOn(any as never, "raiseWarmWindow").mockResolvedValue(true as never);
vi.spyOn(any as never, "pollRpartstoreState").mockResolvedValue({
loaded: false,
launchError: true,
text: "Owwu6ka 3anycka KaTanora",
} as never);
const page = fakePage();
expect(inCooldown(driver)).toBe(false);
expect(await acquire(driver, page, true)).toBe(false);
expect(inCooldown(driver)).toBe(true); // → next Renault VIN routes straight to Dialogys
});
it("a confirmed Rpartstore load CLEARS an active cooldown", async () => {
const driver = new VinpinDriverService();
const any = driver as unknown as AnyDriver;
any.rpartstoreCooldownUntil = Date.now() + 60_000; // pretend it was marked down
vi.spyOn(any as never, "raiseWarmWindow").mockResolvedValue(true as never);
vi.spyOn(any as never, "pollRpartstoreState").mockResolvedValue({
loaded: true,
launchError: false,
text: "Şasi no ile arama",
} as never);
const page = fakePage();
expect(inCooldown(driver)).toBe(true);
expect(await acquire(driver, page, true)).toBe(true);
expect(inCooldown(driver)).toBe(false); // healthy again → Rpartstore resumes as primary
});
it("a transient born-stuck-spinner streak (maxOpens exhausted) does NOT set the cooldown", async () => {
// A born-stuck spinner is a TRANSIENT reopen-recoverable blip, not a server
// outage — exhausting maxOpens must fall back to Dialogys for THIS vin only and
// leave Rpartstore healthy for the next one, NOT suppress it for the full
// cooldown (which can't self-clear while it's being skipped).
const driver = new VinpinDriverService();
const any = driver as unknown as AnyDriver;
vi.spyOn(any as never, "raiseWarmWindow").mockResolvedValue(true as never);
vi.spyOn(any as never, "reopenFreshRpartstore").mockResolvedValue(true as never);
vi.spyOn(any as never, "closeRpartstoreTab").mockResolvedValue(undefined as never);
// Every poll = still spinning (never loaded, no launch error) → born-stuck path.
vi.spyOn(any as never, "pollRpartstoreState").mockResolvedValue({
loaded: false,
launchError: false,
text: "",
} as never);
const page = fakePage();
expect(inCooldown(driver)).toBe(false);
expect(await acquire(driver, page, true)).toBe(false); // gave up → Dialogys
expect(inCooldown(driver)).toBe(false); // but NOT cooled down → next VIN retries Rpartstore
});
});
/**
* Ambiguous-retry cheap in-session reset (the dirty-resume relaunch-thrash fix).
* An AMBIGUOUS Renault outcome is transient/state-dependent, so the retry must NOT
* tear the browser down (a full teardown forces a ~60–90s relaunch + re-login that
* re-hits the seat's "catalog window resumed open" dirty-resume every attempt →
* 3 attempts blow the 180s budget → not_found). Instead it returns to a clean
* VinPower brand grid on the SAME live session via ensureBrandGrid (which runs the
* closeStrayRunningApps DOM recovery first), and re-runs runRenaultFlow — no
* close()/relaunch. GRADUATED safety: only when that cheap reset can't reach a clean
* grid does it fall back to close() + cold re-establish. OCR is mocked so the grid
* confirmation is controllable.
*/
describe("VinpinDriverService — ambiguous Renault retry is a CHEAP in-session grid reset (no relaunch)", () => {
const savedEnv = { ...process.env };
const FAR_DEADLINE = () => Date.now() + 5 * 60_000;
const RENAULT_VIN = "VF1RFE00653633190"; // the live-trace VIN that thrashed on relaunch
beforeEach(() => {
process.env.VINPIN_ENABLED = "true";
process.env.VINPIN_USER = "user";
process.env.VINPIN_PASS = "pass";
mockOcr.mockReset();
});
afterEach(() => {
vi.restoreAllMocks();
process.env = { ...savedEnv };
});
// Present the driver as a live, authenticated session so the cheap reset's
// precheck (browser connected + context + open page + authed) passes and it never
// short-circuits to a cold re-establish.
function liveSession(driver: VinpinDriverService): AnyDriver {
const any = driver as unknown as AnyDriver;
any.browser = { isConnected: () => true };
any.context = {};
any.page = fakePage();
any.authed = true;
return any;
}
const decodeRenault = (driver: VinpinDriverService, vin: string) =>
(
(driver as unknown as AnyDriver).decodeRenaultLocked as (
v: string,
c: unknown,
d: number,
) => Promise<unknown>
).call(driver, vin, { maxAttempts: 3, budgetMs: 5 * 60_000 }, FAR_DEADLINE());
it("first ambiguous retry returns to the grid IN-SESSION (ensureBrandGrid) and re-runs runRenaultFlow WITHOUT close()/relaunch", async () => {
const driver = new VinpinDriverService();
const any = liveSession(driver);
// ensureAuthenticated is a no-op (session already up → NO relaunch, NO web login).
vi.spyOn(any as never, "ensureAuthenticated").mockResolvedValue(undefined as never);
// The cheap reset reaches a clean grid: ensureBrandGrid runs on the SAME session
// and the OCR read confirms the brand grid.
const ensureGrid = vi
.spyOn(any as never, "ensureBrandGrid")
.mockResolvedValue(undefined as never);
mockOcr.mockResolvedValue("Volkswagen Mitsubishi TecDoc"); // matches VINPIN_OCR.brandGrid
const close = vi.spyOn(any as never, "close").mockResolvedValue(undefined as never);
// attempt 1 → ambiguous (transient); attempt 2, same live session → found.
const runFlow = vi
.spyOn(any as never, "runRenaultFlow")
.mockResolvedValueOnce({ status: "ambiguous" } as never)
.mockResolvedValueOnce({
status: "found",
parsed: { brand: "RENAULT", model: "KADJAR", modelYear: null },
rawText: "RENAULT Kadjar",
via: "dialogys",
} as never);
const result = await decodeRenault(driver, RENAULT_VIN);
expect(result).toMatchObject({ brand: "RENAULT", model: "KADJAR" });
expect(runFlow).toHaveBeenCalledTimes(2); // ambiguous, then a cheap in-session re-run
expect(ensureGrid).toHaveBeenCalled(); // the in-session grid reset ran (closeStrayRunningApps path)
expect(close).not.toHaveBeenCalled(); // NO teardown/relaunch on the cheap first retry
});
it("GRADUATED fallback: when the cheap grid reset can't confirm a clean grid, it close()s + cold re-establishes", async () => {
const driver = new VinpinDriverService();
const any = liveSession(driver);
vi.spyOn(any as never, "ensureAuthenticated").mockResolvedValue(undefined as never);
// ensureBrandGrid runs but the grid is NEVER confirmed (OCR reads no grid) → the
// cheap reset returns false → the graduated hard reset (close) must fire.
const ensureGrid = vi
.spyOn(any as never, "ensureBrandGrid")
.mockResolvedValue(undefined as never);
mockOcr.mockResolvedValue(""); // no brand grid → cheap reset fails
const close = vi.spyOn(any as never, "close").mockResolvedValue(undefined as never);
const runFlow = vi
.spyOn(any as never, "runRenaultFlow")
.mockResolvedValueOnce({ status: "ambiguous" } as never)
.mockResolvedValueOnce({
status: "found",
parsed: { brand: "RENAULT", model: "MEGANE", modelYear: null },
rawText: "Megane",
via: "dialogys",
} as never);
const result = await decodeRenault(driver, RENAULT_VIN);
expect(result).toMatchObject({ brand: "RENAULT", model: "MEGANE" });
expect(ensureGrid).toHaveBeenCalled(); // the CHEAP reset was attempted first…
expect(close).toHaveBeenCalledTimes(1); // …then the graduated hard reset fired exactly once
expect(runFlow).toHaveBeenCalledTimes(2);
});
it("does NOT cheap-reset when the session is already gone — falls straight to close() (graduated)", async () => {
const driver = new VinpinDriverService();
const any = liveSession(driver);
// Session looks broken: the page is closed → the cheap reset's precheck fails and
// it returns false without touching ensureBrandGrid, so the hard reset runs.
(any.page as { isClosed: () => boolean }).isClosed = () => true;
vi.spyOn(any as never, "ensureAuthenticated").mockResolvedValue(undefined as never);
const ensureGrid = vi
.spyOn(any as never, "ensureBrandGrid")
.mockResolvedValue(undefined as never);
const close = vi.spyOn(any as never, "close").mockResolvedValue(undefined as never);
vi.spyOn(any as never, "runRenaultFlow")
.mockResolvedValueOnce({ status: "ambiguous" } as never)
.mockResolvedValueOnce({ status: "not_found" } as never);
const result = await decodeRenault(driver, RENAULT_VIN);
expect(result).toBeNull(); // 2nd attempt not_found → null
expect(ensureGrid).not.toHaveBeenCalled(); // broken session → no in-session grid work
expect(close).toHaveBeenCalledTimes(1); // graduated hard reset on the broken session
});
});
/**
* runRenaultFlow definitive-not_found gate (the budget-burn + seat-poison fix).
* When Rpartstore is UNAVAILABLE (down-cooldown, or it never loaded so `primary`
* is only the placeholder ambiguous), a CLEAN Dialogys not_found is DEFINITIVE on
* its own — the old gate required BOTH catalogs to say not_found, so every
* undecodable Renault while Rpartstore was down got downgraded to ambiguous →
* retry loop → 180s budget → sessionPoisoned. A genuinely-ambiguous Dialogys
* (couldn't be reached) still returns ambiguous so the transient-failure retry
* survives. When Rpartstore actually RAN, the both-must-agree gate is preserved.
*/
describe("VinpinDriverService — runRenaultFlow definitive not_found when Rpartstore unavailable", () => {
const savedEnv = { ...process.env };
const FAR_DEADLINE = () => Date.now() + 5 * 60_000;
const VIN = "VF1553K05TR596166"; // old (~1996) Renault 19 — the live budget-burn case
beforeEach(() => {
process.env.VINPIN_ENABLED = "true";
mockOcr.mockReset();
});
afterEach(() => {
vi.restoreAllMocks();
process.env = { ...savedEnv };
});
const runFlow = (driver: VinpinDriverService, page: unknown) =>
(
(driver as unknown as AnyDriver).runRenaultFlow as (
p: unknown,
v: string,
c: unknown,
d: number,
) => Promise<{ status: string }>
).call(driver, page, VIN, { rpartstoreEnabled: true }, FAR_DEADLINE());
it("cooldown (Rpartstore down) + Dialogys not_found → DEFINITIVE not_found, no Rpartstore, no retry", async () => {
const driver = new VinpinDriverService();
const any = driver as unknown as AnyDriver;
any.rpartstoreCooldownUntil = Date.now() + 60_000; // Rpartstore in down-cooldown
const acquire = vi.spyOn(any as never, "acquireLoadedRpartstore");
const runRpartstore = vi.spyOn(any as never, "runRpartstore");
const runDialogys = vi
.spyOn(any as never, "runDialogys")
.mockResolvedValue({ status: "not_found" } as never);
const outcome = await runFlow(driver, fakePage());
expect(outcome.status).toBe("not_found"); // definitive — no ambiguous downgrade
expect(acquire).not.toHaveBeenCalled(); // Rpartstore skipped during the outage
expect(runRpartstore).not.toHaveBeenCalled();
expect(runDialogys).toHaveBeenCalledTimes(1); // single shot — no budget-burn retry
});
it("Rpartstore never loaded (not cooldown) + Dialogys not_found → DEFINITIVE not_found", async () => {
const driver = new VinpinDriverService();
const any = driver as unknown as AnyDriver;
// Not in cooldown, but the acquire fails to load Rpartstore → primary never ran.
vi.spyOn(any as never, "acquireLoadedRpartstore").mockResolvedValue(false as never);
const runRpartstore = vi.spyOn(any as never, "runRpartstore");
vi.spyOn(any as never, "runDialogys").mockResolvedValue({ status: "not_found" } as never);
const outcome = await runFlow(driver, fakePage());
expect(outcome.status).toBe("not_found");
expect(runRpartstore).not.toHaveBeenCalled(); // acquire failed → primary placeholder only
});
it("Rpartstore unavailable + Dialogys AMBIGUOUS (unreachable) → still ambiguous (transient retry survives)", async () => {
const driver = new VinpinDriverService();
const any = driver as unknown as AnyDriver;
any.rpartstoreCooldownUntil = Date.now() + 60_000; // down-cooldown
vi.spyOn(any as never, "runDialogys").mockResolvedValue({ status: "ambiguous" } as never);
const outcome = await runFlow(driver, fakePage());
expect(outcome.status).toBe("ambiguous"); // couldn't confirm not_found → caller retries
});
it("REGRESSION: Rpartstore RAN + ambiguous, Dialogys not_found → still ambiguous (both-must-agree preserved)", async () => {
const driver = new VinpinDriverService();
const any = driver as unknown as AnyDriver;
// Rpartstore is UP: it loads and runs but is unsure (ambiguous). Dialogys then
// cleanly misses. Because Rpartstore actually ran, we must NOT treat this as a
// definitive not_found — the pre-fix both-must-agree behaviour is preserved.
vi.spyOn(any as never, "acquireLoadedRpartstore").mockResolvedValue(true as never);
vi.spyOn(any as never, "runRpartstore").mockResolvedValue({ status: "ambiguous" } as never);
vi.spyOn(any as never, "runDialogys").mockResolvedValue({ status: "not_found" } as never);
const outcome = await runFlow(driver, fakePage());
expect(outcome.status).toBe("ambiguous");
});
it("REGRESSION: Rpartstore RAN + not_found, Dialogys not_found → definitive not_found (unchanged)", async () => {
const driver = new VinpinDriverService();
const any = driver as unknown as AnyDriver;
vi.spyOn(any as never, "acquireLoadedRpartstore").mockResolvedValue(true as never);
vi.spyOn(any as never, "runRpartstore").mockResolvedValue({ status: "not_found" } as never);
vi.spyOn(any as never, "runDialogys").mockResolvedValue({ status: "not_found" } as never);
const outcome = await runFlow(driver, fakePage());
expect(outcome.status).toBe("not_found");
});
});
/**
* VINPIN_RPARTSTORE_ENABLED=false kill-switch (KNOWN Rpartstore outage). Unlike the
* in-memory down-cooldown (which resets on every worker restart, so the first decode
* after each restart pays the full Rpartstore launch cost + leaves a stuck app), this
* config flag persists: when set, BOTH Renault paths (warm + cold) skip opening
* Rpartstore entirely and go straight to Dialogys, and a clean Dialogys not_found is
* DEFINITIVE (a flag-disabled Rpartstore is "unavailable" exactly like the cooldown).
* Default (unset / not "false") is TRUE — behaviour completely unchanged.
*/
describe("VinpinDriverService — VINPIN_RPARTSTORE_ENABLED=false skips Rpartstore in both Renault paths", () => {
const savedEnv = { ...process.env };
const FAR_DEADLINE = () => Date.now() + 5 * 60_000;
beforeEach(() => {
process.env.VINPIN_ENABLED = "true";
mockOcr.mockReset();
});
afterEach(() => {
vi.restoreAllMocks();
process.env = { ...savedEnv };
});
it("COLD runRenaultFlow (flag=false): never opens Rpartstore, goes straight to Dialogys, and a Dialogys not_found is DEFINITIVE (no retry)", async () => {
const driver = new VinpinDriverService();
const any = driver as unknown as AnyDriver;
// NOT in cooldown — the ONLY reason to skip is the disabled flag.
const acquire = vi.spyOn(any as never, "acquireLoadedRpartstore");
const ensureR = vi.spyOn(any as never, "ensureRpartstore");
const runRpartstore = vi.spyOn(any as never, "runRpartstore");
const runDialogys = vi
.spyOn(any as never, "runDialogys")
.mockResolvedValue({ status: "not_found" } as never);
const outcome = await (
(any as AnyDriver).runRenaultFlow as (
p: unknown,
v: string,
c: unknown,
d: number,
) => Promise<{ status: string }>
).call(driver, fakePage(), "VF1553K05TR596166", { rpartstoreEnabled: false }, FAR_DEADLINE());
expect(acquire).not.toHaveBeenCalled(); // Rpartstore never opened
expect(ensureR).not.toHaveBeenCalled();
expect(runRpartstore).not.toHaveBeenCalled();
expect(runDialogys).toHaveBeenCalledTimes(1); // single shot — no budget-burn retry
expect(outcome.status).toBe("not_found"); // definitive — no ambiguous downgrade
});
it("WARM warmRenaultDecode (flag=false): never opens Rpartstore, decodes via Dialogys", async () => {
const driver = new VinpinDriverService();
const any = driver as unknown as AnyDriver;
const acquire = vi.spyOn(any as never, "acquireLoadedRpartstore");
const ensureR = vi.spyOn(any as never, "ensureRpartstore");
const runRpartstore = vi.spyOn(any as never, "runRpartstore");
vi.spyOn(any as never, "ensureWarmWindow").mockResolvedValue(true as never);
vi.spyOn(any as never, "runDialogysSearch").mockResolvedValue({
status: "found",
parsed: { brand: "RENAULT", model: "MEGANE", modelYear: null },
rawText: "Megane",
via: "dialogys",
} as never);
const page = { keyboard: { press: vi.fn(async () => undefined) } };
const result = await (
any.warmRenaultDecode as (p: unknown, v: string, c: unknown, d: number) => Promise<unknown>
).call(driver, page, "VF1LM1B0A37829019", { rpartstoreEnabled: false }, FAR_DEADLINE());
expect(acquire).not.toHaveBeenCalled(); // Rpartstore never opened
expect(ensureR).not.toHaveBeenCalled();
expect(runRpartstore).not.toHaveBeenCalled();
expect(result).toMatchObject({
brand: "RENAULT",
model: "MEGANE",
raw: { source: "vinpin-dialogys" },
});
});
it("DEFAULT (flag=true): COLD path still ATTEMPTS Rpartstore (behaviour unchanged)", async () => {
const driver = new VinpinDriverService();
const any = driver as unknown as AnyDriver;
const acquire = vi
.spyOn(any as never, "acquireLoadedRpartstore")
.mockResolvedValue(true as never);
vi.spyOn(any as never, "runRpartstore").mockResolvedValue({
status: "found",
parsed: { brand: "RENAULT", model: "CLIO", modelYear: null },
rawText: "Clio",
via: "rpartstore",
} as never);
const outcome = await (
(any as AnyDriver).runRenaultFlow as (
p: unknown,
v: string,
c: unknown,
d: number,
) => Promise<{ status: string }>
).call(driver, fakePage(), "VF1553K05TR596166", { rpartstoreEnabled: true }, FAR_DEADLINE());
expect(acquire).toHaveBeenCalledTimes(1); // Rpartstore still primary by default
expect(outcome.status).toBe("found");
});
});

View File

@@ -0,0 +1,707 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { VinpinDriverService, VinpinSessionDroppedError } from "./vinpin-driver.service";
import { VINPIN_COORDS, VINPIN_OCR, VINPIN_WINDOW_FOREGROUND } from "./vinpin.constants";
/**
* Livelock-breaker unit tests for the Vinpin decode driver. These exercise the
* failure/abort machinery (wall-clock budget, sessionPoisoned cold re-establish,
* VIN sanity gate) in isolation by stubbing the browser-driving privates — the
* shared Vinpin seat lives on prod and can't be driven from a test.
*/
describe("VinpinDriverService — livelock breakers", () => {
const savedEnv = { ...process.env };
const VALID_FIAT_VIN = "NM435600006H43436"; // 17 alphanumerics → fiat flow
beforeEach(() => {
// afterEach restores the full env snapshot, so VINPIN_DECODE_BUDGET_MS set by
// the budget test never leaks into the others.
process.env.VINPIN_ENABLED = "true";
process.env.VINPIN_USER = "user";
process.env.VINPIN_PASS = "pass";
});
afterEach(() => {
vi.restoreAllMocks();
process.env = { ...savedEnv };
});
it("aborts a single decode that blows past the wall-clock budget, tears down and poisons the seat", async () => {
process.env.VINPIN_DECODE_BUDGET_MS = "50";
const driver = new VinpinDriverService();
const anyDriver = driver as unknown as Record<string, unknown>;
const closeSpy = vi.spyOn(anyDriver as never, "close").mockResolvedValue(undefined as never);
// ensureReady succeeds cheaply, then runVinFlow hangs forever → the budget
// timer must win the race.
vi.spyOn(anyDriver as never, "ensureReady").mockImplementation((async () => {
anyDriver.page = { isClosed: () => false };
}) as never);
vi.spyOn(anyDriver as never, "runVinFlow").mockReturnValue(
new Promise(() => {}) as never, // never resolves
);
const started = Date.now();
const result = await driver.decode(VALID_FIAT_VIN);
const elapsed = Date.now() - started;
expect(result).toBeNull();
expect(closeSpy).toHaveBeenCalled(); // torn down on abort
expect(anyDriver.sessionPoisoned).toBe(true); // seat marked poisoned
// Aborted near the budget, not after minutes / all 3 internal attempts.
expect(elapsed).toBeLessThan(2_000);
});
it("forces a full cold re-establish (close) when the seat was poisoned by a prior decode", async () => {
const driver = new VinpinDriverService();
const anyDriver = driver as unknown as Record<string, unknown>;
anyDriver.sessionPoisoned = true;
const closeSpy = vi.spyOn(anyDriver as never, "close").mockResolvedValue(undefined as never);
const fiatSpy = vi
.spyOn(anyDriver as never, "decodeFiatLocked")
.mockResolvedValue({ brand: "Fiat", model: "EGEA" } as never);
const result = await driver.decode(VALID_FIAT_VIN);
expect(closeSpy).toHaveBeenCalledTimes(1); // the poison-forced teardown
expect(anyDriver.sessionPoisoned).toBe(false); // flag consumed
expect(fiatSpy).toHaveBeenCalledTimes(1);
expect(result).toEqual({ brand: "Fiat", model: "EGEA" });
});
it("does NOT tear down a healthy warm session when the seat is not poisoned", async () => {
const driver = new VinpinDriverService();
const anyDriver = driver as unknown as Record<string, unknown>;
anyDriver.sessionPoisoned = false;
const closeSpy = vi.spyOn(anyDriver as never, "close").mockResolvedValue(undefined as never);
vi.spyOn(anyDriver as never, "decodeFiatLocked").mockResolvedValue({
brand: "Fiat",
model: "EGEA",
} as never);
const result = await driver.decode(VALID_FIAT_VIN);
expect(closeSpy).not.toHaveBeenCalled(); // healthy path untouched
expect(result).toEqual({ brand: "Fiat", model: "EGEA" });
});
it("skips obviously-junk input before it ever touches the shared seat", async () => {
const driver = new VinpinDriverService();
const anyDriver = driver as unknown as Record<string, unknown>;
const fiatSpy = vi.spyOn(anyDriver as never, "decodeFiatLocked");
expect(await driver.decode("SHORT")).toBeNull();
expect(await driver.decode("VF1RFE0065363319")).toBeNull(); // 16 chars
expect(await driver.decode("NM4356 0006H43436")).toBeNull(); // space (non-alnum)
expect(fiatSpy).not.toHaveBeenCalled();
});
it("still runs a well-formed VIN through the decode loop (sanity gate is not over-filtering)", async () => {
const driver = new VinpinDriverService();
const anyDriver = driver as unknown as Record<string, unknown>;
const fiatSpy = vi
.spyOn(anyDriver as never, "decodeFiatLocked")
.mockResolvedValue(null as never);
expect(await driver.decode(VALID_FIAT_VIN)).toBeNull();
expect(fiatSpy).toHaveBeenCalledTimes(1);
});
});
/**
* Warm-session daemon behaviours on the driver: warm-vs-cold routing, the
* keepalive that must SKIP while a decode holds the seat, and health-recovery
* (session-drop → teardown + re-warm + single retry). The browser-driving privates
* are stubbed — the real seat lives on prod.
*/
describe("VinpinDriverService — warm session", () => {
const savedEnv = { ...process.env };
const VALID_FIAT_VIN = "NM435600006H43436";
beforeEach(() => {
process.env.VINPIN_ENABLED = "true";
process.env.VINPIN_USER = "user";
process.env.VINPIN_PASS = "pass";
process.env.VINPIN_WARM_DAEMON = "true";
});
afterEach(() => {
vi.restoreAllMocks();
process.env = { ...savedEnv };
});
function makeWarm(driver: VinpinDriverService) {
const any = driver as unknown as Record<string, unknown>;
any.warm = true;
any.browser = { isConnected: () => true };
any.page = { isClosed: () => false, mouse: { move: vi.fn(async () => undefined) } };
return any;
}
it("routes a decode to the WARM path when a healthy warm session is up", async () => {
const driver = new VinpinDriverService();
const any = makeWarm(driver);
const warmSpy = vi
.spyOn(any as never, "warmDecodeWithRecovery")
.mockResolvedValue({ brand: "Fiat", model: "EGEA" } as never);
const coldSpy = vi.spyOn(any as never, "decodeFiatLocked");
const result = await driver.decode(VALID_FIAT_VIN);
expect(warmSpy).toHaveBeenCalledTimes(1);
expect(coldSpy).not.toHaveBeenCalled(); // cold path bypassed while warm
expect(result).toEqual({ brand: "Fiat", model: "EGEA" });
});
it("falls back to the COLD path when VINPIN_WARM_DAEMON=false even if warm is set", async () => {
process.env.VINPIN_WARM_DAEMON = "false";
const driver = new VinpinDriverService();
const any = makeWarm(driver);
const warmSpy = vi.spyOn(any as never, "warmDecodeWithRecovery");
const coldSpy = vi
.spyOn(any as never, "decodeFiatLocked")
.mockResolvedValue({ brand: "Fiat", model: "EGEA" } as never);
await driver.decode(VALID_FIAT_VIN);
expect(warmSpy).not.toHaveBeenCalled();
expect(coldSpy).toHaveBeenCalledTimes(1);
});
it("keepalive SKIPS while a decode holds the seat (busy), and nudges when idle", async () => {
const driver = new VinpinDriverService();
const any = makeWarm(driver);
const move = (any.page as { mouse: { move: ReturnType<typeof vi.fn> } }).mouse.move;
// Busy (a decode is in flight) → no nudge, no lock contention.
any.busy = true;
await driver.keepalivePing();
expect(move).not.toHaveBeenCalled();
// Idle → the keepalive nudges the harmless in-window point.
any.busy = false;
await driver.keepalivePing();
expect(move).toHaveBeenCalledTimes(1);
});
it("on a dropped warm session, tears down + re-warms ONCE, then retries the decode once", async () => {
const driver = new VinpinDriverService();
const any = makeWarm(driver);
const warmDecode = vi
.spyOn(any as never, "warmDecode")
.mockRejectedValueOnce(new VinpinSessionDroppedError("dropped") as never)
.mockResolvedValueOnce({ brand: "Fiat", model: "EGEA" } as never);
const rewarm = vi.spyOn(any as never, "_warmUp").mockResolvedValue(true as never);
const result = await driver.decode(VALID_FIAT_VIN);
expect(warmDecode).toHaveBeenCalledTimes(2); // initial + one retry
expect(rewarm).toHaveBeenCalledTimes(1); // re-warmed exactly once
expect(result).toEqual({ brand: "Fiat", model: "EGEA" });
});
it("session-drop recovery gives up (null) when the re-warm fails — never throws", async () => {
const driver = new VinpinDriverService();
const any = makeWarm(driver);
vi.spyOn(any as never, "warmDecode").mockRejectedValue(
new VinpinSessionDroppedError("dropped") as never,
);
vi.spyOn(any as never, "_warmUp").mockResolvedValue(false as never);
const result = await driver.decode(VALID_FIAT_VIN);
expect(result).toBeNull();
expect(any.warm).toBe(false); // dropped seat marked not-warm → cold path next time
});
});
/**
* Rpartstore acquire-with-spinner-guard. A freshly-opened Rpartstore instance
* sometimes gets "born stuck" on an infinite spinner; the fix is to close the
* stuck instance and reopen a FRESH one, up to N times, inside the wall-clock
* budget, and only then fall back to Dialogys. These stub the browser-driving
* privates (real seat lives on prod) and drive the OCR-load verdict via a mocked
* pollRpartstoreState, which reads LOADED off the full frame and the HARD
* launch-error modal off an UPSCALED crop (spinner = {loaded:false,launchError:
* false}, loaded = {loaded:true}, DOWN = {launchError:true}).
*/
describe("VinpinDriverService — Rpartstore spinner guard", () => {
const savedEnv = { ...process.env };
const FAR_DEADLINE = () => Date.now() + 5 * 60_000;
beforeEach(() => {
process.env.VINPIN_ENABLED = "true";
process.env.VINPIN_USER = "user";
process.env.VINPIN_PASS = "pass";
});
afterEach(() => {
vi.restoreAllMocks();
process.env = { ...savedEnv };
});
function acquire(driver: VinpinDriverService, warm: boolean, deadline: number): Promise<boolean> {
const any = driver as unknown as Record<string, unknown>;
return (
any.acquireLoadedRpartstore as (
page: unknown,
cfg: unknown,
deadline: number,
warm: boolean,
) => Promise<boolean>
).call(driver, {}, {}, deadline, warm);
}
it("reuses Rpartstore when the FIRST open already loaded (no reopen, no close)", async () => {
const driver = new VinpinDriverService();
const any = driver as unknown as Record<string, unknown>;
vi.spyOn(any as never, "raiseWarmWindow").mockResolvedValue(true as never);
const reopen = vi.spyOn(any as never, "reopenFreshRpartstore");
const close = vi.spyOn(any as never, "closeRpartstoreTab");
vi.spyOn(any as never, "pollRpartstoreState").mockResolvedValue({
loaded: true,
launchError: false,
text: "Şasi no ile arama",
} as never);
expect(await acquire(driver, true, FAR_DEADLINE())).toBe(true);
expect(reopen).not.toHaveBeenCalled();
expect(close).not.toHaveBeenCalled();
});
it("closes a born-stuck spinner and reopens a FRESH instance that loads (warm)", async () => {
const driver = new VinpinDriverService();
const any = driver as unknown as Record<string, unknown>;
const raise = vi.spyOn(any as never, "raiseWarmWindow").mockResolvedValue(true as never);
const reopen = vi.spyOn(any as never, "reopenFreshRpartstore").mockResolvedValue(true as never);
const close = vi
.spyOn(any as never, "closeRpartstoreTab")
.mockResolvedValue(undefined as never);
// open 1 → spinner (not loaded); open 2 (fresh) → loaded.
vi.spyOn(any as never, "pollRpartstoreState")
.mockResolvedValueOnce({ loaded: false, launchError: false, text: "spinner" } as never)
.mockResolvedValueOnce({ loaded: true, launchError: false, text: "Ne arıyorsunuz" } as never);
expect(await acquire(driver, true, FAR_DEADLINE())).toBe(true);
expect(raise).toHaveBeenCalledTimes(1); // only the first attempt raises
expect(close).toHaveBeenCalledTimes(1); // the stuck instance was closed
expect(reopen).toHaveBeenCalledTimes(1); // one fresh reopen, which loaded
});
it("gives up (false) after maxOpens reopen attempts all spinner → caller falls to Dialogys", async () => {
const driver = new VinpinDriverService();
const any = driver as unknown as Record<string, unknown>;
vi.spyOn(any as never, "ensureRpartstore").mockResolvedValue(true as never); // cold open path
const reopen = vi.spyOn(any as never, "reopenFreshRpartstore").mockResolvedValue(true as never);
const close = vi
.spyOn(any as never, "closeRpartstoreTab")
.mockResolvedValue(undefined as never);
vi.spyOn(any as never, "pollRpartstoreState").mockResolvedValue({
loaded: false,
launchError: false,
text: "spinner",
} as never); // never loads
expect(await acquire(driver, false, FAR_DEADLINE())).toBe(false);
// maxOpens = 3: open 1 (ensureRpartstore) + 2 reopens; a close after each miss.
expect(reopen).toHaveBeenCalledTimes(2);
expect(close).toHaveBeenCalledTimes(3);
});
it("bails immediately (false) without opening when the budget is already spent (no livelock)", async () => {
const driver = new VinpinDriverService();
const any = driver as unknown as Record<string, unknown>;
const raise = vi.spyOn(any as never, "raiseWarmWindow").mockResolvedValue(true as never);
const poll = vi.spyOn(any as never, "pollRpartstoreState");
expect(await acquire(driver, true, Date.now() - 1)).toBe(false);
expect(raise).not.toHaveBeenCalled();
expect(poll).not.toHaveBeenCalled();
});
it("HARD launch error (Rpartstore DOWN) → returns false after ONE open, NO reopens, dismiss clicked → caller falls to Dialogys", async () => {
const driver = new VinpinDriverService();
const any = driver as unknown as Record<string, unknown>;
const raise = vi.spyOn(any as never, "raiseWarmWindow").mockResolvedValue(true as never);
const reopen = vi.spyOn(any as never, "reopenFreshRpartstore");
const close = vi.spyOn(any as never, "closeRpartstoreTab");
// Upscaled modal-crop OCR of "Ошибка запуска каталога" — the VERBATIM string
// captured live 2026-07-15 on seat trvinpin47828 (see rpartstoreLaunchError).
vi.spyOn(any as never, "pollRpartstoreState").mockResolvedValue({
loaded: false,
launchError: true,
text: "Rpartstore X Owwu6ka 3anycka KaTanora",
} as never);
const page = {
mouse: { click: vi.fn(async () => undefined) },
waitForTimeout: vi.fn(async () => undefined),
};
const result = await (
any.acquireLoadedRpartstore as (
p: unknown,
c: unknown,
d: number,
w: boolean,
) => Promise<boolean>
).call(driver, page, {}, FAR_DEADLINE(), true);
expect(result).toBe(false); // → warmRenaultDecode/runRenaultFlow go straight to Dialogys
expect(raise).toHaveBeenCalledTimes(1); // opened exactly ONCE
expect(reopen).not.toHaveBeenCalled(); // NO reopens burned (~54s saved)
expect(close).not.toHaveBeenCalled(); // not treated as a spinner
// The launch-error modal's OK button was clicked to dismiss it.
expect(page.mouse.click).toHaveBeenCalledWith(
VINPIN_COORDS.rpartstoreLaunchErrorOk.x,
VINPIN_COORDS.rpartstoreLaunchErrorOk.y,
);
});
it("genuine spinner (no launch-error string) STILL triggers the close+reopen loop (unchanged)", async () => {
const driver = new VinpinDriverService();
const any = driver as unknown as Record<string, unknown>;
vi.spyOn(any as never, "raiseWarmWindow").mockResolvedValue(true as never);
const reopen = vi.spyOn(any as never, "reopenFreshRpartstore").mockResolvedValue(true as never);
const close = vi
.spyOn(any as never, "closeRpartstoreTab")
.mockResolvedValue(undefined as never);
// Bare chrome, no content AND no launch-error → born-stuck spinner. Reopen loop.
vi.spyOn(any as never, "pollRpartstoreState")
.mockResolvedValueOnce({ loaded: false, launchError: false, text: "RPartStore" } as never)
.mockResolvedValueOnce({ loaded: true, launchError: false, text: "Ne arıyorsunuz" } as never);
expect(await acquire(driver, true, FAR_DEADLINE())).toBe(true);
expect(close).toHaveBeenCalledTimes(1); // stuck instance closed (spinner path intact)
expect(reopen).toHaveBeenCalledTimes(1); // one fresh reopen, which loaded
});
it("launch-error OCR pattern matches the real Cyrillic and its live-captured eng-OCR transliterations", () => {
expect(VINPIN_OCR.rpartstoreLaunchError.test("Ошибка запуска каталога")).toBe(true);
// VERBATIM upscaled-crop OCR captured live 2026-07-15 (seat trvinpin47828): the
// "Ошибка" head varies (Owwu6ka/OwwbKa) but "3anycka"+"KaTanora" are stable.
expect(VINPIN_OCR.rpartstoreLaunchError.test("Rpartstore X Owwu6ka 3anycka KaTanora")).toBe(
true,
);
expect(VINPIN_OCR.rpartstoreLaunchError.test("Volvo (X) OwwbKa 3anycka KaTanora VY")).toBe(
true,
);
expect(VINPIN_OCR.rpartstoreLaunchError.test("Owwnbka 3anycka KaTanora")).toBe(true);
// Must NOT fire on a healthy loaded Rpartstore home (no false short-circuit) —
// this is the exact full-frame text a LOADED home shows.
expect(VINPIN_OCR.rpartstoreLaunchError.test("Şasi no ile arama Güncel araçlar")).toBe(false);
// Nor on the brand grid alone (the tiles behind the modal, read on a 1× frame).
expect(
VINPIN_OCR.rpartstoreLaunchError.test("Audi Fiat Renault KIA SEAT Volkswagen Toyota"),
).toBe(false);
});
it("launch error over the grid (ensureRpartstore couldn't confirm a window) → bail to Dialogys, NO reopens", async () => {
const driver = new VinpinDriverService();
const any = driver as unknown as Record<string, unknown>;
// Cold path: ensureRpartstore returns false because the DOWN Rpartstore shows
// only the centered launch-error modal over the grid (no catalog chrome).
vi.spyOn(any as never, "ensureRpartstore").mockResolvedValue(false as never);
const reopen = vi.spyOn(any as never, "reopenFreshRpartstore");
const close = vi.spyOn(any as never, "closeRpartstoreTab");
// The upscaled modal crop DOES read the launch error → dismiss + bail.
vi.spyOn(any as never, "rpartstoreLaunchErrorPresent").mockResolvedValue(true as never);
const page = {
mouse: { click: vi.fn(async () => undefined) },
waitForTimeout: vi.fn(async () => undefined),
};
const result = await (
any.acquireLoadedRpartstore as (
p: unknown,
c: unknown,
d: number,
w: boolean,
) => Promise<boolean>
).call(driver, page, {}, FAR_DEADLINE(), false);
expect(result).toBe(false); // → straight to Dialogys
expect(reopen).not.toHaveBeenCalled(); // no reopens burned
expect(close).not.toHaveBeenCalled();
expect(page.mouse.click).toHaveBeenCalledWith(
VINPIN_COORDS.rpartstoreLaunchErrorOk.x,
VINPIN_COORDS.rpartstoreLaunchErrorOk.y,
);
});
it("warm Renault decode: loaded Rpartstore is PRIMARY — Dialogys is not touched on a hit", async () => {
const driver = new VinpinDriverService();
const any = driver as unknown as Record<string, unknown>;
vi.spyOn(any as never, "acquireLoadedRpartstore").mockResolvedValue(true as never);
vi.spyOn(any as never, "runRpartstore").mockResolvedValue({
status: "found",
parsed: { brand: "RENAULT", model: "KADJAR", modelYear: null },
rawText: "RENAULT Kadjar",
via: "rpartstore",
} as never);
const dialogys = vi.spyOn(any as never, "ensureWarmWindow");
const page = { keyboard: { press: vi.fn(async () => undefined) } };
const result = await (
any.warmRenaultDecode as (p: unknown, v: string, c: unknown, d: number) => Promise<unknown>
).call(driver, page, "VF1RFE00653633190", { rpartstoreEnabled: true }, FAR_DEADLINE());
expect(result).toMatchObject({
brand: "RENAULT",
model: "KADJAR",
raw: { source: "vinpin-rpartstore" },
});
expect(dialogys).not.toHaveBeenCalled(); // Rpartstore hit → Dialogys never consulted
});
it("warm Renault decode: exhausted Rpartstore → LAST-RESORT Dialogys fallback still decodes", async () => {
const driver = new VinpinDriverService();
const any = driver as unknown as Record<string, unknown>;
vi.spyOn(any as never, "acquireLoadedRpartstore").mockResolvedValue(false as never); // never loaded
const runRpartstore = vi.spyOn(any as never, "runRpartstore");
vi.spyOn(any as never, "ensureWarmWindow").mockResolvedValue(true as never);
vi.spyOn(any as never, "runDialogysSearch").mockResolvedValue({
status: "found",
parsed: { brand: "RENAULT", model: "MEGANE", modelYear: null },
rawText: "Megane II Classic",
via: "dialogys",
} as never);
const page = { keyboard: { press: vi.fn(async () => undefined) } };
const result = await (
any.warmRenaultDecode as (p: unknown, v: string, c: unknown, d: number) => Promise<unknown>
).call(driver, page, "VF1LM1B0A37829019", { rpartstoreEnabled: true }, FAR_DEADLINE());
expect(runRpartstore).not.toHaveBeenCalled(); // never ran the search on a stuck Rpartstore
expect(result).toMatchObject({
brand: "RENAULT",
model: "MEGANE",
raw: { source: "vinpin-dialogys" },
});
});
it("acquire give-up (budget-exhausted) DEFENSIVELY dismisses a leftover modal (Escape + launch-error OK) even when the OCR branch never fires", async () => {
const driver = new VinpinDriverService();
const any = driver as unknown as Record<string, unknown>;
// Budget already spent → the inner acquire returns false at its first budget
// check WITHOUT ever hitting the OCR error-detect branch (raise/poll not called).
const raise = vi.spyOn(any as never, "raiseWarmWindow").mockResolvedValue(true as never);
const poll = vi.spyOn(any as never, "pollRpartstoreState");
const page = {
keyboard: { press: vi.fn(async () => undefined) },
mouse: { click: vi.fn(async () => undefined) },
waitForTimeout: vi.fn(async () => undefined),
};
const result = await (
any.acquireLoadedRpartstore as (
p: unknown,
c: unknown,
d: number,
w: boolean,
) => Promise<boolean>
).call(driver, page, {}, Date.now() - 1, true);
expect(result).toBe(false);
expect(raise).not.toHaveBeenCalled(); // budget already gone → never opened
expect(poll).not.toHaveBeenCalled();
// The wrapper's unconditional defensive clear ran on the false path: Escape +
// click the centered launch-error OK, so no modal is left to wedge the grid-return.
expect(page.keyboard.press).toHaveBeenCalledWith("Escape");
expect(page.mouse.click).toHaveBeenCalledWith(
VINPIN_COORDS.rpartstoreLaunchErrorOk.x,
VINPIN_COORDS.rpartstoreLaunchErrorOk.y,
);
});
it("grid-return dismisses a blocking modal BEFORE each tab-✕ close (can't wedge into a relogin thrash)", async () => {
const driver = new VinpinDriverService();
const any = driver as unknown as Record<string, unknown>;
const order: string[] = [];
// ocrRegion on a fake page fails-safe to "" (never the brand grid) → the loop runs.
const dismiss = vi.spyOn(any as never, "dismissBlockingModal").mockImplementation((async () => {
order.push("dismiss");
}) as never);
vi.spyOn(any as never, "ensureBrandGrid").mockResolvedValue(undefined as never);
const page = {
mouse: {
click: vi.fn(async () => {
order.push("click");
}),
},
keyboard: { press: vi.fn(async () => undefined) },
waitForTimeout: vi.fn(async () => undefined),
};
await (any.returnToBrandGrid as (p: unknown, c: unknown) => Promise<void>).call(
driver,
page,
{},
);
expect(dismiss).toHaveBeenCalled();
// The modal-clear precedes the tab-✕ click on the very first iteration.
expect(order[0]).toBe("dismiss");
expect(order[1]).toBe("click");
expect(page.mouse.click).toHaveBeenCalledWith(
VINPIN_COORDS.catalogTabClose.x,
VINPIN_COORDS.catalogTabClose.y,
);
});
it("caps the resumed-desktop escalation (closeStrayRunningApps, NOT logout+relogin) to ONE attempt per decode (no thrash)", async () => {
const driver = new VinpinDriverService();
const any = driver as unknown as Record<string, unknown>;
// Fresh decode → escalation budget starts unused.
any.reloginUsedThisDecode = false;
vi.spyOn(any as never, "submitVinPowerLogin").mockResolvedValue(false as never);
vi.spyOn(any as never, "dismissDisconnected").mockResolvedValue(undefined as never);
// logout+relogin is retired — it must not exist as a method any more.
expect(any.logoutAndRelogin).toBeUndefined();
// The escalation itself fails — the point is it's only TRIED once across two returns.
const escalate = vi
.spyOn(any as never, "closeStrayRunningApps")
.mockResolvedValue(false as never);
const page = {
waitForTimeout: vi.fn(async () => undefined),
keyboard: { press: vi.fn(async () => undefined) },
mouse: { click: vi.fn(async () => undefined) },
};
const ensureGrid = (p: unknown, c: unknown, allow?: boolean) =>
(any.ensureBrandGrid as (p: unknown, c: unknown, a?: boolean) => Promise<void>).call(
driver,
p,
c,
allow,
);
// Two grid-returns inside ONE decode (as returnToBrandGrid's loop would do). The
// 2nd must NOT re-escalate → no repeated recovery thrash.
await ensureGrid(page, {}, true);
await ensureGrid(page, {}, true);
expect(escalate).toHaveBeenCalledTimes(1); // one escalation only — the 2nd is capped
expect(any.reloginUsedThisDecode).toBe(true);
expect(any.sessionPoisoned).toBe(true); // capped path poisons for a clean cold restart
});
});
/**
* Warm-path Fiat fixes: the disambiguated foreground regex (Defect B) and the
* warmDecode Fiat branch that must never fail silently (Defect A) — genuine
* not-found → null, wrong/garbled window → cold fallback, no Fiat warm window →
* cold fallback.
*/
describe("VinpinDriverService — warm Fiat not-found / wrong-window hardening", () => {
const savedEnv = { ...process.env };
const VALID_FIAT_VIN = "NM435600006H43436"; // 17 alphanumerics → fiat warm window
const FAR_DEADLINE = () => Date.now() + 5 * 60_000;
beforeEach(() => {
process.env.VINPIN_ENABLED = "true";
process.env.VINPIN_USER = "user";
process.env.VINPIN_PASS = "pass";
});
afterEach(() => {
vi.restoreAllMocks();
process.env = { ...savedEnv };
});
function fakePage() {
return { isClosed: () => false, keyboard: { press: vi.fn(async () => undefined) } };
}
function callWarmDecode(driver: VinpinDriverService, vin: string, deadline: number) {
const any = driver as unknown as Record<string, unknown>;
return (any.warmDecode as (v: string, c: unknown, d: number) => Promise<unknown>).call(
driver,
vin,
{},
deadline,
);
}
it("FIX 1: VINPIN_WINDOW_FOREGROUND.fiat does NOT match a Dialogys 'ПОИСК' string but DOES match Fiat 'Dealer'/'ePER'/'TIPO-EGEA'", () => {
const fg = VINPIN_WINDOW_FOREGROUND.fiat;
// The shared-token bug: the Dialogys ПОИСК search button must NOT read as the
// Fiat foreground (this false-positive typed the VIN into Dialogys — Defect B).
expect(fg.test("ПОИСК Dialogys ИЗМЕНИТЬ")).toBe(false);
expect(fg.test("ПОИСК")).toBe(false);
// Fiat-window-only chrome + VIN-panel model tokens still match.
expect(fg.test("Fiat Dealer")).toBe(true);
expect(fg.test("ePER window")).toBe(true);
expect(fg.test("6J - TIPO - EGEA (2015-2021)")).toBe(true);
expect(fg.test("Spare Parts Catalogue")).toBe(true);
// Sanity: the Dialogys foreground regex STILL recognises ПОИСК (its own detection
// is unaffected — only the Fiat regex dropped the shared token).
expect(VINPIN_WINDOW_FOREGROUND.dialogys.test("ПОИСК Dialogys ИЗМЕНИТЬ")).toBe(true);
});
it("FIX 2: Fiat unusable-parse NOT-on-panel (wrong/garbled window) → falls back to decodeFiatLocked, not a silent null", async () => {
const driver = new VinpinDriverService();
const any = driver as unknown as Record<string, unknown>;
any.warm = true;
any.page = fakePage();
any.warmWindows = { fiat: true }; // has a Fiat window → not the FIX-4 route
vi.spyOn(any as never, "assertSessionAlive").mockResolvedValue(undefined as never);
vi.spyOn(any as never, "ensureWarmWindow").mockResolvedValue(true as never);
vi.spyOn(any as never, "runVinFlow").mockResolvedValue(null as never); // no usable parse
// Frame shows the DIALOGYS window (Defect B), not the Fiat VIN panel.
vi.spyOn(any as never, "ocrFrame").mockResolvedValue("ПОИСК Dialogys ИЗМЕНИТЬ" as never);
const close = vi.spyOn(any as never, "close").mockResolvedValue(undefined as never);
const cold = vi
.spyOn(any as never, "decodeFiatLocked")
.mockResolvedValue({ brand: "Fiat", model: "TIPO" } as never);
const result = await callWarmDecode(driver, VALID_FIAT_VIN, FAR_DEADLINE());
expect(cold).toHaveBeenCalledTimes(1); // cold fallback, NOT a silent null
expect(result).toMatchObject({ brand: "Fiat", model: "TIPO" });
expect(any.warm).toBe(false); // warm dropped (untrusted Fiat window)
expect(close).toHaveBeenCalled();
});
it("FIX 2: Fiat genuine not-found (on the VIN panel + not-found string) → returns null, no cold fallback", async () => {
const driver = new VinpinDriverService();
const any = driver as unknown as Record<string, unknown>;
any.warm = true;
any.page = fakePage();
any.warmWindows = { fiat: true };
vi.spyOn(any as never, "assertSessionAlive").mockResolvedValue(undefined as never);
vi.spyOn(any as never, "ensureWarmWindow").mockResolvedValue(true as never);
vi.spyOn(any as never, "runVinFlow").mockResolvedValue(null as never);
// Positively on the Fiat Spare-Parts catalogue AND a genuine "не найден" miss.
vi.spyOn(any as never, "ocrFrame").mockResolvedValue(
"Spare Parts Catalogue TIPO не найден" as never,
);
const cold = vi.spyOn(any as never, "decodeFiatLocked");
const result = await callWarmDecode(driver, VALID_FIAT_VIN, FAR_DEADLINE());
expect(result).toBeNull(); // a real miss is correctly null
expect(cold).not.toHaveBeenCalled(); // NOT re-driven cold
});
it("FIX 4: routes a Fiat VIN straight to the cold path when warmWindows.fiat is false (no Fiat warm window)", async () => {
const driver = new VinpinDriverService();
const any = driver as unknown as Record<string, unknown>;
any.warm = true;
any.page = fakePage();
any.warmWindows = { fiat: false, dialogys: true }; // Renault-only partial warm
vi.spyOn(any as never, "assertSessionAlive").mockResolvedValue(undefined as never);
const ensure = vi.spyOn(any as never, "ensureWarmWindow");
const runVinFlow = vi.spyOn(any as never, "runVinFlow");
const close = vi.spyOn(any as never, "close").mockResolvedValue(undefined as never);
const cold = vi
.spyOn(any as never, "decodeFiatLocked")
.mockResolvedValue({ brand: "Fiat", model: "EGEA" } as never);
const result = await callWarmDecode(driver, VALID_FIAT_VIN, FAR_DEADLINE());
expect(cold).toHaveBeenCalledTimes(1); // straight to cold — never touched a warm window
expect(ensure).not.toHaveBeenCalled();
expect(runVinFlow).not.toHaveBeenCalled();
expect(result).toMatchObject({ brand: "Fiat", model: "EGEA" });
expect(any.warm).toBe(false);
expect(close).toHaveBeenCalled();
});
});

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,328 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
/**
* Clean-teardown + grid-return reliability tests for the Vinpin driver. These
* exercise the warm-establish fix: the clean-teardown routine (close resumed
* catalog windows via the corrected tab-✕, then log out of the RDS session before
* dropping the browser) and ensureBrandGrid's escalation to logout+relogin. OCR is
* mocked so the screen-state sequence is fully controllable — the real seat lives
* on prod and can't be driven from a test.
*/
vi.mock("./vinpin.ocr", () => ({
ocrRegion: vi.fn(async () => ""),
pollForText: vi.fn(async () => ({ matched: false, text: "" })),
terminateOcr: vi.fn(async () => undefined),
}));
import { VinpinDriverService } from "./vinpin-driver.service";
import { ocrRegion } from "./vinpin.ocr";
const mockOcr = vi.mocked(ocrRegion);
type AnyDriver = Record<string, unknown>;
function fakePage(sink: (x: number, y: number) => void) {
return {
isClosed: () => false,
frames: () => [] as unknown[],
mouse: { click: vi.fn(async (x: number, y: number) => sink(x, y)) },
keyboard: { press: vi.fn(async () => undefined) },
waitForTimeout: vi.fn(async () => undefined),
};
}
describe("VinpinDriverService — clean teardown", () => {
const savedEnv = { ...process.env };
beforeEach(() => {
process.env.VINPIN_ENABLED = "true";
process.env.VINPIN_USER = "user";
process.env.VINPIN_PASS = "pass";
process.env.VINPIN_WARM_DAEMON = "true";
mockOcr.mockReset();
});
afterEach(() => {
vi.restoreAllMocks();
process.env = { ...savedEnv };
});
it("teardownWarm closes each resumed catalog window (tab-✕) then logs out BEFORE closing the browser", async () => {
const driver = new VinpinDriverService();
const any = driver as unknown as AnyDriver;
const events: string[] = [];
vi.spyOn(any as never, "close").mockImplementation((async () => {
events.push("close");
}) as never);
any.browser = { isConnected: () => true };
any.context = {};
any.warm = true;
any.page = fakePage((x, y) => {
if (x === 93 && y === 45) events.push("tabClose");
if (x === 1543 && y === 877) events.push("logout");
});
// Two catalog windows open, then a clear desktop.
mockOcr
.mockResolvedValueOnce("RPartStore")
.mockResolvedValueOnce("ePER Dealer")
.mockResolvedValue("");
await driver.teardownWarm();
// Both windows closed via the corrected tab-✕, then logout, then browser close.
expect(events).toEqual(["tabClose", "tabClose", "logout", "close"]);
expect(any.warm).toBe(false);
});
it("clean-teardown still logs out when no catalog window is open (bounded, no-op close loop)", async () => {
const driver = new VinpinDriverService();
const any = driver as unknown as AnyDriver;
const clicks: Array<[number, number]> = [];
any.browser = { isConnected: () => true };
any.context = {};
any.page = fakePage((x, y) => clicks.push([x, y]));
mockOcr.mockResolvedValue(""); // desktop already clear
await (any.cleanTeardown as () => Promise<void>).call(driver);
expect(clicks.filter(([x, y]) => x === 93 && y === 45)).toHaveLength(0); // nothing to close
expect(clicks).toContainEqual([1543, 877]); // still logs out to end the RDS session
});
it("logout dismisses any blocking modal FIRST, and recovers a Disconnected drop by closing it + relaunching VINPIN for a fresh grid", async () => {
const driver = new VinpinDriverService();
const any = driver as unknown as AnyDriver;
const events: string[] = [];
any.browser = { isConnected: () => true };
any.context = {};
any.page = fakePage((x, y) => {
if (x === 868 && y === 530) events.push("dismissModal"); // rpartstoreLaunchErrorOk
if (x === 1543 && y === 877) events.push("logout"); // Çıkış yap
if (x === 953 && y === 505) events.push("disconnectedClose");
if (x === 40 && y === 256) events.push("relaunchVinpin"); // vinpinApp
});
// (1) close-loop: desktop already clear → break. (2) after logout: a Disconnected
// dialog surfaced (dirty channel drop). (3) closing it lands on the launcher.
mockOcr
.mockResolvedValueOnce("") // close-loop: nothing open
.mockResolvedValueOnce("You have been disconnected") // after Çıkış yap
.mockResolvedValueOnce("No Running Items Available"); // launcher after Close
await (any.cleanTeardown as () => Promise<void>).call(driver);
// Modal dismissed BEFORE logout; then the disconnect is closed and VINPIN relaunched.
expect(events).toEqual(["dismissModal", "logout", "disconnectedClose", "relaunchVinpin"]);
});
it("logout does NOT relaunch VINPIN when logout was a clean log-off (no Disconnected dialog)", async () => {
const driver = new VinpinDriverService();
const any = driver as unknown as AnyDriver;
const clicks: Array<[number, number]> = [];
any.browser = { isConnected: () => true };
any.context = {};
any.page = fakePage((x, y) => clicks.push([x, y]));
mockOcr.mockResolvedValue(""); // clear desktop, and no Disconnected dialog after logout
await (any.cleanTeardown as () => Promise<void>).call(driver);
expect(clicks).toContainEqual([1543, 877]); // logged out
expect(clicks).not.toContainEqual([953, 505]); // no disconnect to close
expect(clicks).not.toContainEqual([40, 256]); // VINPIN not relaunched
});
it("does NOT relaunch VINPIN when logout lands on the HTML-Access launcher (clean log-off, not a drop)", async () => {
// The clean-logout launcher OCRs its "HTML Access" branding, which the broad
// sessionDropped token matches — but the launcher tokens must veto the recovery
// so a clean log-off is never mistaken for a Disconnected drop (would spuriously
// relaunch VinPower and leave a dirty resumed session).
const driver = new VinpinDriverService();
const any = driver as unknown as AnyDriver;
const clicks: Array<[number, number]> = [];
any.browser = { isConnected: () => true };
any.context = {};
any.page = fakePage((x, y) => clicks.push([x, y]));
mockOcr
.mockResolvedValueOnce("") // close-loop: nothing open
.mockResolvedValueOnce("VMware Horizon HTML Access — No Running Items Available"); // clean launcher after logout
await (any.cleanTeardown as () => Promise<void>).call(driver);
expect(clicks).toContainEqual([1543, 877]); // logged out
expect(clicks).not.toContainEqual([953, 505]); // NOT treated as a disconnect
expect(clicks).not.toContainEqual([40, 256]); // VINPIN NOT relaunched
});
it("clean-teardown is a no-op when the browser/page is already gone", async () => {
const driver = new VinpinDriverService();
const any = driver as unknown as AnyDriver;
any.browser = null;
any.context = null;
any.page = null;
// Must not throw and must not touch OCR.
await expect((any.cleanTeardown as () => Promise<void>).call(driver)).resolves.toBeUndefined();
expect(mockOcr).not.toHaveBeenCalled();
});
});
/**
* A running-app row handle for the Horizon "Running" panel. `$` resolves the
* name element (textContent) and the per-app close ✕; clicking the ✕ removes the
* app from the shared running list (models a real window teardown).
*/
function fakeRunningApp(name: string, onClose: (n: string) => void) {
return {
$: async (sel: string) => {
if (/running-app-name|focused-app-name/.test(sel)) {
return { textContent: async () => name };
}
if (/icon-close-app-image/.test(sel)) {
return { click: async () => onClose(name) };
}
return null;
},
};
}
/**
* A fake page that also exposes the Horizon client-chrome DOM (`$`, `$$`,
* `page.click`) used by closeStrayRunningApps. `apps` is the mutable running list;
* closing a stray removes it. `closed` records the order strays were terminated.
*/
function fakeDomPage(apps: string[], sink?: (x: number, y: number) => void) {
const running = [...apps];
const closed: string[] = [];
const domClicks: string[] = [];
const page = {
isClosed: () => false,
frames: () => [] as unknown[],
mouse: { click: vi.fn(async (x: number, y: number) => sink?.(x, y)) },
keyboard: { press: vi.fn(async () => undefined) },
waitForTimeout: vi.fn(async () => undefined),
$: async (sel: string) =>
sel === "#sidebar-toggler" || sel === "#available-VINPIN" ? {} : null,
$$: async (sel: string) =>
sel === "ul.running-app"
? running.map((n) =>
fakeRunningApp(n, (name) => {
closed.push(name);
const idx = running.indexOf(name);
if (idx >= 0) running.splice(idx, 1);
}),
)
: [],
click: vi.fn(async (sel: string) => {
domClicks.push(sel);
}),
};
return { page, running, closed, domClicks };
}
describe("VinpinDriverService — ensureBrandGrid stray-app (Running-panel) recovery", () => {
const savedEnv = { ...process.env };
const cfg = { url: "https://vinpin.test", user: "user", pass: "pass" };
beforeEach(() => {
process.env.VINPIN_ENABLED = "true";
mockOcr.mockReset();
});
afterEach(() => {
vi.restoreAllMocks();
process.env = { ...savedEnv };
});
it("closeStrayRunningApps closes every non-VinPower app via the DOM ✕ and leaves only VinPower", async () => {
const driver = new VinpinDriverService();
const any = driver as unknown as AnyDriver;
const { page, running, closed } = fakeDomPage([
"VinPower",
"Renault Rpartstore",
"Loading application...",
]);
// After the strays close + the sidebar collapses, the canvas is on the brand grid.
mockOcr.mockResolvedValue("Volkswagen SsangYong TecDoc");
const ok = await (
any.closeStrayRunningApps as (p: unknown, c: unknown) => Promise<boolean>
).call(driver, page, cfg);
expect(ok).toBe(true);
// Both non-VinPower apps terminated via their per-app ✕, in row order.
expect(closed).toEqual(["Renault Rpartstore", "Loading application..."]);
expect(running).toEqual(["VinPower"]); // VinPower kept
expect(any.sessionPoisoned).toBe(false); // reached a confirmed-clean grid
});
it("closeStrayRunningApps degrades gracefully (false, no throw) when the sidebar DOM is absent", async () => {
const driver = new VinpinDriverService();
const any = driver as unknown as AnyDriver;
const page = fakePage(() => undefined); // no $ / $$ / page.click — canvas-only render
mockOcr.mockResolvedValue("");
await expect(
(any.closeStrayRunningApps as (p: unknown, c: unknown) => Promise<boolean>).call(
driver,
page,
cfg,
),
).resolves.toBe(false); // → caller falls back to the canvas tab-✕ / OCR path
});
it("ensureBrandGrid escalates via closeStrayRunningApps (NOT logout+relogin) + falls back to the tab-✕ (93,45), never the language-selector (1298,14)", async () => {
const driver = new VinpinDriverService();
const any = driver as unknown as AnyDriver;
const clicks: Array<[number, number]> = [];
const page = fakePage((x, y) => clicks.push([x, y]));
// Always a catalog window open → grid never reached → in-branch recovery + escalation.
mockOcr.mockResolvedValue("RPartStore catalog open");
// logout+relogin is retired — the method must not exist any more.
expect((any as Record<string, unknown>).logoutAndRelogin).toBeUndefined();
// DOM absent → the primary Running-panel recovery returns false → tab-✕ fallback.
const escalate = vi.spyOn(any as never, "closeStrayRunningApps");
await (any.ensureBrandGrid as (p: unknown, c: unknown, allow?: boolean) => Promise<void>).call(
driver,
page,
cfg,
true,
);
expect(escalate).toHaveBeenCalled(); // primary + escalation is the Running-panel recovery
expect(clicks).toContainEqual([93, 45]); // tab-✕ fallback still used
expect(clicks).not.toContainEqual([1298, 14]); // language-selector coord NEVER clicked
expect(any.sessionPoisoned).toBe(true); // recovery failed (DOM absent) → poison, no relogin
});
it("ensureBrandGrid clears the poison when closeStrayRunningApps reaches a clean grid", async () => {
const driver = new VinpinDriverService();
const any = driver as unknown as AnyDriver;
const page = fakePage(() => undefined);
mockOcr.mockResolvedValue("RPartStore catalog open"); // never reaches grid by OCR
// The escalation succeeds (Running-panel recovery reached a fresh grid).
const escalate = vi
.spyOn(any as never, "closeStrayRunningApps")
.mockResolvedValue(true as never);
await (any.ensureBrandGrid as (p: unknown, c: unknown, allow?: boolean) => Promise<void>).call(
driver,
page,
cfg,
true,
);
expect(escalate).toHaveBeenCalled();
expect(any.sessionPoisoned).toBe(false); // recovery reached a confirmed-clean grid
});
it("with allowRelogin=false it does NOT run the end-of-loop escalation and poisons the seat (one-shot, no livelock)", async () => {
const driver = new VinpinDriverService();
const any = driver as unknown as AnyDriver;
const page = fakePage(() => undefined);
mockOcr.mockResolvedValue("RPartStore catalog open"); // never reaches grid
await (any.ensureBrandGrid as (p: unknown, c: unknown, allow?: boolean) => Promise<void>).call(
driver,
page,
cfg,
false,
);
expect(any.sessionPoisoned).toBe(true); // poisoned → next decode cold-restarts
});
});

View File

@@ -12,6 +12,8 @@
* coordinate if the brand-grid layout ever changes. * coordinate if the brand-grid layout ever changes.
*/ */
import { getBrandFromWmi } from "@sase/shared";
/** Viewport the coordinates are calibrated for. */ /** Viewport the coordinates are calibrated for. */
export const VINPIN_VIEWPORT = { width: 1600, height: 900 } as const; export const VINPIN_VIEWPORT = { width: 1600, height: 900 } as const;
@@ -42,12 +44,106 @@ export const VINPIN_COORDS = {
vinSubmitArrow: { x: 1283, y: 189 }, vinSubmitArrow: { x: 1283, y: 189 },
/** "OK" button of the "vehicles not found" alert (genuine not-found result). */ /** "OK" button of the "vehicles not found" alert (genuine not-found result). */
notFoundOk: { x: 816, y: 448 }, notFoundOk: { x: 816, y: 448 },
// ─── Renault flow (Rpartstore primary + Dialogys fallback) ───
// Coordinates below are 1600x900 STARTING POINTS from the live benchmark on the
// permanent seat (trvinpin41080). They are OCR-verified+retried at runtime like
// the Fiat flow, so minor drift self-heals — but re-verify if layout changes.
// TUNE.
/** Window-close (X) button of an open catalog window. ⚠️ DO NOT USE on the
* HTML-Access desktop: this coord actually hits the LANGUAGE SELECTOR (it opens a
* dropdown that makes the brand grid unrecognizable and wedges the ensureBrandGrid
* thrash). It is NO LONGER clicked by ANY path — the browser-tab ✕ below is the
* only close action. Kept documented so the bad coordinate isn't re-introduced. */
windowClose: { x: 1298, y: 14 },
/** Browser-tab ✕ of an open catalog app — the PRIMARY window-close action. The
* tab sits just under the window title bar, e.g. "Renault Rpartstore ✕".
* Validated live: clicking (93,45) closed the catalog and returned to the clean
* brand grid (the old {135,45} missed the ✕). TUNE. */
catalogTabClose: { x: 93, y: 45 },
/** "Çıkış yap" logout button (bottom-right of the RDS/Horizon desktop). Ends the
* remote session so the NEXT warm-up starts from a fresh login/grid instead of
* resuming into the last-open dirty catalog desktop. Used by the clean-teardown
* routine. ⚠️ With a blocking modal up (e.g. the Rpartstore launch-error dialog)
* this becomes a channel DISCONNECT rather than a clean RDS log-off — so the
* teardown dismisses any modal BEFORE clicking it. TUNE. */
logoutButton: { x: 1543, y: 877 },
/** "Close" button of the Horizon "You have been disconnected" dialog. If "Çıkış
* yap" turned into a channel disconnect (dirty RDS resume), clicking this lands
* back on the HTML-Access launcher ("No Running Items") from which the VINPIN app
* is relaunched for a fresh VinPower grid. Verified @ 1600x900. TUNE. */
disconnectedClose: { x: 953, y: 505 },
/** Renault brand tile on the VinPower grid (opens the Rpartstore/Dialogys
* submenu). mousedown/up like the Fiat tile. TUNE. */
renaultBrand: { x: 450, y: 707 },
/** Rpartstore entry in the Renault submenu (PRIMARY catalog). TUNE. */
renaultRpartstore: { x: 584, y: 779 },
/** Dialogys entry in the Renault submenu (FALLBACK catalog). TUNE. */
renaultDialogys: { x: 584, y: 733 },
/** Both Renault catalogs pop a Russian-language dialog on open → its OK. TUNE. */
renaultLangOk: { x: 746, y: 454 },
/** Rpartstore "Şasi no ile arama" VIN field. Submit with Enter (NOT the yellow
* button — it moves). TUNE. */
rpartstoreVinField: { x: 735, y: 194 },
/** Rpartstore "RPartStore" home/logo (top-left) — resets to the search home
* between VINs (more reliable than close+reopen). TUNE. */
rpartstoreHome: { x: 110, y: 92 },
/** Rpartstore error-card close (✕) — dismisses the "Şasi seçilmedi" /
* "bulunamadı" overlay that otherwise covers the VIN field. TUNE. */
rpartstoreErrorClose: { x: 928, y: 167 },
/** Rpartstore yellow search button (fallback to Enter submit). TUNE. */
rpartstoreSearchBtn: { x: 975, y: 195 },
/** "OK" button of the Rpartstore hard launch-error modal ("Ошибка запуска
* каталога" / title "Renault Rpartstore") that fires when Rpartstore is DOWN
* server-side. Verified live @ 1600x900 (viewport frame) — dismisses the modal
* so the driver can fall straight back to Dialogys. TUNE. */
rpartstoreLaunchErrorOk: { x: 868, y: 530 },
/** Dialogys VIN field. TUNE. */
dialogysVinField: { x: 457, y: 258 },
/** Dialogys ПОИСК (search) button. TUNE. */
dialogysSearch: { x: 590, y: 382 },
/** Dialogys Home button (reset step 1). TUNE. */
dialogysHome: { x: 78, y: 102 },
/** Dialogys ИЗМЕНИТЬ А/М — change-vehicle (reset step 2). TUNE. */
dialogysChangeVehicle: { x: 1217, y: 160 },
} as const;
/** Screenshot clip (px) of the Renault Rpartstore/Dialogys vehicle-page HEADER
* region, fed to OCR. Rpartstore renders "RENAULT <model> (<code>)" /
* "DACIA <model>" + "Şasi: <VIN>" in x280–960,y182–258; Dialogys renders
* "<Model> (<platform>), <engine>" slightly higher. Captured a bit wider/taller
* than the benchmark box to tolerate drift. TUNE. */
export const VINPIN_RENAULT_HEADER_REGION = {
x: 260,
y: 150,
width: 720,
height: 140,
} as const; } as const;
/** Screenshot clip (px) of the decode-result modal body, fed to OCR. Captures /** Screenshot clip (px) of the decode-result modal body, fed to OCR. Captures
* the model line ("6J - TIPO - EGEA (2015-2021)"), SINCOM, trim, prod-date and * the model line ("6J - TIPO - EGEA (2015-2021)"), SINCOM, trim, prod-date and
* the echoed VIN. Verified live. */ * the echoed VIN. Verified live. Widened to ~900px for the warm-session daemon
export const VINPIN_MODAL_REGION = { x: 250, y: 120, width: 820, height: 480 } as const; * (some decode modals render wider on the permanent seat). */
export const VINPIN_MODAL_REGION = { x: 250, y: 120, width: 900, height: 500 } as const;
/** Screenshot clip (px) of the CENTERED Rpartstore hard launch-error modal
* ("Renault Rpartstore" / "Ошибка запуска каталога", OK ~868,530), fed to OCR
* UPSCALED (ocrRegion's default 3×). ⚠️ ROOT-CAUSE NOTE (verified live 2026-07-15
* on seat trvinpin47828): the modal is a small (~220×140px) centered Cyrillic
* dialog. OCR'ing the FULL 1600×900 frame at 1× (what the old load-poll did)
* CANNOT read it — tesseract returns the surrounding brand-grid tiles and drops
* the tiny modal text, so `rpartstoreLaunchError` never matched → the DOWN
* Rpartstore was misclassified as a "born-stuck spinner" and 3 reopens (~54s) were
* burned before Dialogys. Cropping to THIS region + 3× upscale makes the string
* legible ("Owwu6ka 3anycka KaTanora"), so the launch error is detected on the
* FIRST open and the flow bails straight to Dialogys. Sized generously around the
* screen-centered dialog to tolerate drift while excluding the right sidebar. */
export const VINPIN_RPARTSTORE_ERROR_REGION = {
x: 540,
y: 370,
width: 560,
height: 230,
} as const;
/** OCR keyword sets for state detection (case-insensitive). */ /** OCR keyword sets for state detection (case-insensitive). */
export const VINPIN_OCR = { export const VINPIN_OCR = {
@@ -70,14 +166,236 @@ export const VINPIN_OCR = {
/** The decode modal actually carries a result (a model / prod-date / MVS). */ /** The decode modal actually carries a result (a model / prod-date / MVS). */
modalHit: modalHit:
/MVS|найден|Prod\.?\s*date|TIPO|EGEA|DOBLO|PALIO|PANDA|PUNTO|LINEA|DUCATO|QUBO|FIORINO|ULYSSE/i, /MVS|найден|Prod\.?\s*date|TIPO|EGEA|DOBLO|PALIO|PANDA|PUNTO|LINEA|DUCATO|QUBO|FIORINO|ULYSSE/i,
/** Genuine "no vehicle found" outcome (the catalog has no record). */ /** Genuine "no vehicle found" outcome (the catalog has no record). Used against
* the cropped decode-modal region in runVinFlow, where the loose `Catalogue`
* token is a useful settle signal. */
notFound: /не\s*найден|not\s*found|Catalogue/i, notFound: /не\s*найден|not\s*found|Catalogue/i,
/** STRICT genuine not-found — requires an actual "не найден"/"not found" string,
* WITHOUT the loose `Catalogue` token. Use this against the FULL frame (where
* the "Spare Parts Catalogue" header is always present, so `notFound` would
* false-match), e.g. the warm-Fiat genuine-miss-vs-garble decision — so an
* on-panel transient garble falls through to the cold retry instead of null. */
notFoundStrict: /не\s*найден|not\s*found/i,
// ─── Renault flow OCR sets ───
/** A catalog app window (Rpartstore / Dialogys / Fiat ePER) is open OVER the
* brand grid — its chrome must be closed to fall back to the grid. Covers the
* Rpartstore/Dialogys titles + the ePER "Spare Parts" / "Son araca geri dön"
* navigation that only appear inside an open catalog. */
catalogWindowOpen:
/RPartStore|Rpartstore|Dialogys|Son\s*araca|Spare\s*Parts|Yedek\s*par|ePER|Üniversal\s*ürün/i,
/** Renault submenu is open (Rpartstore + Dialogys entries visible). */
renaultSubmenu: /Rpartstore|Rpart|Dialogys|Dialog/i,
/** Rpartstore app/window is open (home OR a vehicle page) — its chrome tokens
* ("RPartStore", "Güncel araçlar", "Ne arıyorsunuz", "Grup siparişi",
* "Şasi") appear only inside Rpartstore. */
rpartstoreOpen: /RPartStore|Rpartstore|Güncel\s*ara|Grup\s*sipariş|arıyor|Şasi|Sasi/i,
/** Rpartstore home/search page (the VIN search field is up). */
rpartstoreReady: /Güncel\s*ara|arıyor|Grup\s*sipariş|Şasi\s*no|Sasi\s*no|Ara\b/i,
/** Rpartstore search-home actually RENDERED its landing markers ("Şasi no ile
* arama" / "Ne arıyorsunuz" / "Güncel araçlar" / "Grup siparişi"). This is the
* spinner-guard signal: it distinguishes a LOADED home from the "born-stuck"
* infinite spinner, which shows only the window CHROME ("RPartStore" title —
* matched by rpartstoreOpen) with no search-home content. Kept strictly to
* content-only tokens so a spinning-but-titled window never false-passes. */
rpartstoreLoaded:
/Şasi\s*no\s*ile|Sasi\s*no\s*ile|Ne\s*arıyor|Ne\s*ariyor|Güncel\s*ara(ç|c)|Guncel\s*ara(ç|c)|Grup\s*sipariş|arıyorsunuz/i,
/** Rpartstore HARD launch-error modal — the Russian "Ошибка запуска каталога"
* (Catalog launch error) dialog that fires within ~8-10s of opening when
* Rpartstore is DOWN server-side (entitlement/backend failure). Reopening never
* helps, so detecting this must SHORT-CIRCUIT straight to Dialogys instead of
* burning the reopen budget. ⚠️ This must be read from an UPSCALED crop of
* `VINPIN_RPARTSTORE_ERROR_REGION` — on a full 1×frame the modal is illegible
* (see that region's note). The eng-OCR of the Cyrillic "Ошибка запуска
* каталога" transliterates to "Owwu6ka 3anycka KaTanora" / "OwwbKa 3anycka
* KaTanora" (captured verbatim live 2026-07-15). The `3anycka`+`KaTanora` tokens
* are the stable anchors; the "Ошибка" head transliterates variably
* (Owwu6ka/OwwbKa/Owwnbka) so all seen forms are listed. Its title alone
* ("Renault Rpartstore") false-matches rpartstoreOpen — this content string is
* what disambiguates the error. */
rpartstoreLaunchError: /запуска\s*катал|Ошибка\s*запуск|3anycka|KaTanora|Owwu6ka|OwwbKa|Owwnbka/i,
/** Rpartstore decoded a vehicle — header shows RENAULT/DACIA <model> + Şasi. */
rpartstoreHit: /RENAULT|DACIA|Şasi\s*:|Sasi\s*:/i,
/** Rpartstore genuine not-found — the error card ("İlişikli araç bulunamadı" /
* "Şasi ... bulunamadı" / "Şasi seçilmedi"). */
rpartstoreNotFound: /bulunamad|İlişikli|Ilisikli|araç\s*bulun|seçilmedi|secilmedi/i,
/** Dialogys form/vehicle page reached (Cyrillic UI, ПОИСК / ИЗМЕНИТЬ). */
dialogysReady: /ПОИСК|ПОИC|Dialogys|VIN|ИЗМЕНИТЬ/i,
// ─── Warm-session daemon OCR sets ───
/** The RDS/Horizon session is still ALIVE — the desktop status panel shows the
* host/seat identifiers ("HORIZON-RDST01"/"HORIZON-RDST02" / "trvinpin41080").
* The seat now LOAD-BALANCES across RDST01 and RDST02, so both host tags count.
* Their ABSENCE combined with a `sessionDropped` marker means the session dropped. */
sessionAlive: /HORIZON[- ]?RDST0[12]|RDST0[12]|trvinpin\d*/i,
/** The RDS/Horizon session DROPPED — a "Disconnected"/reconnect dialog or the
* "no free sessions" gate. Triggers a teardown + re-warm + single retry. */
sessionDropped:
/Disconnected|nofreesession|no\s*free\s*session|reconnect|Session\s*(has\s*)?(been\s*)?(disconnected|ended|expired|timed\s*out)|HTML\s*Access/i,
} as const; } as const;
/**
* Which taskbar button belongs to which catalog window. The warm daemon OCRs the
* bottom taskbar and matches these labels to bind brand→coordinate at runtime
* (the button ORDER depends on the open sequence, so we never hardcode the
* mapping — see `orderTaskbarWindows`). `grid` matches the VinPower brand-grid
* button used to open the next catalog without closing the current one.
*/
export const VINPIN_WINDOW_LABELS = {
fiat: /ePER|Dealer|Fiat/i,
rpartstore: /RPartStore|Rpart/i,
dialogys: /Dialogys|Dialog/i,
grid: /VinPower|VINPIN|Marka|Brand/i,
} as const;
export type VinpinWindowKey = keyof typeof VINPIN_WINDOW_LABELS;
/**
* OCR keyword that confirms a given catalog window is now in the FOREGROUND after
* a taskbar raise (reuses the existing state sets). Used to verify a raise landed
* on the right window before running a decode on it.
*/
export const VINPIN_WINDOW_FOREGROUND: Record<"fiat" | "rpartstore" | "dialogys", RegExp> = {
// ⚠️ Fiat-window-ONLY tokens. The old `Поиск` token was SHARED with the Dialogys
// "ПОИСК" search button (`/Поиск/i.test("ПОИСК") === true`), so in a partial-warm
// session where Dialogys ends up foreground the Fiat raise falsely reported success
// and the VIN was typed into Dialogys → silent garbage. `Dealer`/`ePER` are Fiat
// ePER chrome (never on Dialogys/Rpartstore); the rest are VIN-panel model tokens.
fiat: /Spare\s*Parts\s*Catalogue|GRANDE\s*PANDA|TIPO|EGEA|DOBLO|Dealer|ePER/i,
rpartstore: /RPartStore|Rpartstore|Güncel\s*ara|Grup\s*sipariş|Şasi|Sasi/i,
dialogys: /ПОИСК|ПОИC|Dialogys|ИЗМЕНИТЬ/i,
};
/**
* Horizon HTML-Access client-chrome DOM selectors (REAL DOM, outside the Blast
* canvas — hidden until the sidebar is opened). Used by the state-agnostic
* stray-app recovery (`closeStrayRunningApps`): the sidebar "Running" panel lists
* each RDS app with a per-app close ✕ that TERMINATES that specific app window
* regardless of its internal modal/spinner/loading state. Proven live to cleanly
* close both a Fiat "Fiat Dealer" window and a Renault Rpartstore launch-error
* resume, each returning to a pristine brand grid — the root fix for the
* dirty-resume failure the canvas tab-✕ (only hits a TABBED window's ✕) could not
* recover. Treated as GIVEN from the live probe; every use is guarded (try/catch +
* presence check) so a wrong/absent selector degrades to the canvas/OCR fallback
* rather than throwing. ⚠️ A Connection-Server logout+relogin is NOT a recovery
* here: the seat publishes apps-only (no desktop → no Start-menu Log Off), so the
* RDS session ends ONLY on server-side idle timeout — logout+relogin provably
* RESUMES the same dirty window. This DOM path is the recovery instead. */
export const VINPIN_DOM = {
/** Left-edge grip (~10,450) that reveals/collapses the Horizon sidebar. */
sidebarToggler: "#sidebar-toggler",
/** One <ul> per running RDS app in the sidebar "Running" panel. */
runningApp: "ul.running-app",
/** The app's display name inside a running-app row ("VinPower", "Fiat Dealer",
* "Renault Rpartstore", "Dialogys", "Loading application..."). */
runningAppName: "li.running-app-name, li.focused-app-name",
/** Per-app close ✕ inside a running-app row — terminates THAT app window. */
appCloseImage: "li.icon-close-app-image",
/** "Available → VINPIN" launch tile (relaunch VinPower if it was closed). */
availableVinpin: "#available-VINPIN",
/** App name to KEEP — every OTHER running app is a stray to terminate. */
vinPowerAppName: /VinPower/i,
/** Bounded passes over the Running panel (rows shift as apps close). */
maxClosePasses: 6,
} as const;
/** Bottom Horizon/RDS taskbar clip (px), fed to OCR to read the open windows'
* button labels left→right. TUNE against the permanent seat @ 1600x900. */
export const VINPIN_TASKBAR_REGION = { x: 0, y: 866, width: 1600, height: 34 } as const;
/** Candidate taskbar button CENTERS along the bottom bar, left→right. The daemon
* binds each open window to a slot by the OCR'd label order. Extra slots give
* headroom for drift; a raise is OCR-verified and re-tried on the next slot.
* TUNE against the permanent seat @ 1600x900. */
export const VINPIN_TASKBAR_SLOTS = [
{ x: 220, y: 884 },
{ x: 360, y: 884 },
{ x: 500, y: 884 },
{ x: 640, y: 884 },
{ x: 780, y: 884 },
] as const;
/** Global "VIN veya katalog ara" router box on the VinPower grid (~1455,96). Only
* used to OPEN a brand's window the first time (it routes, it does NOT decode and
* the VIN does not carry into the catalog). TUNE. */
export const VINPIN_ROUTER_BOX = { x: 1455, y: 96 } as const;
/** Warm-session daemon tunables. */
export const VINPIN_WARM = {
/** Business-hours window (Europe/Istanbul) the seat is held warm. */
businessStartHour: 8,
businessEndHour: 21,
/** Idle keepalive cadence — a `mouse.move` every ~75s held the RDS session
* 12.6 min with zero disconnect in the live proof. */
keepaliveIntervalMs: 75_000,
/** Harmless in-window point the keepalive nudges the cursor to. TUNE. */
keepalivePoint: { x: 800, y: 500 },
/** How often the scheduler reconciles warm-vs-hours. */
schedulerIntervalMs: 60_000,
/** Retries when verifying/re-trying a taskbar raise across slots. */
raiseVerifyRetries: 3,
/** After a taskbar-raise click, wait for the window to come forward. */
afterRaiseMs: 1_200,
/** Backoff after a FAILED warmUp: reconcile() and decode()'s warm-on-demand both
* skip re-warming until the cooldown elapses, so a failing seat is not hammered
* every ~60s (which leaves a fresh dirty window each attempt). Starts at the base
* and doubles per consecutive failure up to the max; a successful warm resets it. */
warmBackoffBaseMs: 60_000,
warmBackoffMaxMs: 300_000,
} as const;
/**
* Given the OCR'd taskbar text and the window labels, return the windows in the
* left→right order they appear in the bar. Pure + injectable so the brand→slot
* binding is unit-testable without a live seat. Windows whose label isn't found
* are omitted (the daemon then falls back to open-order for the missing ones).
*/
export function orderTaskbarWindows(
taskbarText: string,
keys: readonly ("fiat" | "rpartstore" | "dialogys")[] = ["fiat", "rpartstore", "dialogys"],
): ("fiat" | "rpartstore" | "dialogys")[] {
const found: { key: "fiat" | "rpartstore" | "dialogys"; idx: number }[] = [];
for (const key of keys) {
const label = VINPIN_WINDOW_LABELS[key];
const m = label.exec(taskbarText);
if (m) found.push({ key, idx: m.index });
}
return found.sort((a, b) => a.idx - b.idx).map((f) => f.key);
}
/**
* Pick which warm catalog WINDOW a VIN should be decoded on. Mirrors
* `selectVinpinBrandFlow`: Renault/Dacia → the Rpartstore window (Dialogys is the
* in-flow fallback), everything else (incl. Fiat) → the ePER window. Pure/testable.
*/
export function selectVinpinWarmWindow(vin: string): "fiat" | "rpartstore" {
return selectVinpinBrandFlow(vin) === "renault" ? "rpartstore" : "fiat";
}
/** Current hour (0–23) in Europe/Istanbul. Injectable clock for tests. */
export function vinpinIstanbulHour(now: Date = new Date()): number {
const hourStr = new Intl.DateTimeFormat("en-US", {
timeZone: "Europe/Istanbul",
hour: "numeric",
hour12: false,
}).format(now);
// Some runtimes emit "24" for midnight with hour12:false — normalise to 0–23.
return Number.parseInt(hourStr, 10) % 24;
}
/** Whether the seat should be held warm right now (08:00–21:00 Europe/Istanbul). */
export function isVinpinBusinessHours(now: Date = new Date()): boolean {
const h = vinpinIstanbulHour(now);
return h >= VINPIN_WARM.businessStartHour && h < VINPIN_WARM.businessEndHour;
}
/** Wait budgets (ms) for each step. Verified live @ 1600x900. */ /** Wait budgets (ms) for each step. Verified live @ 1600x900. */
export const VINPIN_WAITS = { export const VINPIN_WAITS = {
afterGoto: 7_000, afterGoto: 7_000,
afterLogin: 20_000, /** After submitting the web login: wait for the post-login screen (Horizon
* launcher or VinPower brand grid) to render. The real grid render measured
* ~32–46s on the permanent seat, so the old 20s always timed out (noise). */
afterLogin: 45_000,
/** After clicking the launcher's VINPIN app: wait for VinPower to connect and /** After clicking the launcher's VINPIN app: wait for VinPower to connect and
* raise its login dialog (permanent seat only). */ * raise its login dialog (permanent seat only). */
afterVinpinLaunch: 14_000, afterVinpinLaunch: 14_000,
@@ -87,9 +405,91 @@ export const VINPIN_WAITS = {
afterLangDismiss: 2_500, afterLangDismiss: 2_500,
afterSearchOpen: 5_000, afterSearchOpen: 5_000,
afterVinSubmit: 7_000, afterVinSubmit: 7_000,
afterAlertDismiss: 700, afterAlertDismiss: 250,
/** After toggling the Horizon sidebar open/closed (real DOM chrome reveal). */
afterSidebarToggle: 1_000,
/** Between per-app closes in the Horizon "Running" panel (window teardown settles). */
afterRunningAppClose: 2_000,
/** OCR poll cadence when waiting for a detectable end-state. Each poll is
* CAPPED at the corresponding fixed-wait budget above (kept as a fallback), so
* if OCR never catches the transition the total wait == the old fixed sleep and
* worst-case behaviour is unchanged. */
pollIntervalMs: 700,
// ─── Renault flow waits ───
/** After clicking the window-close (X) of an open catalog window. */
afterWindowClose: 3_500,
/** After clicking the Renault brand tile (submenu animates in). */
afterRenaultTile: 2_500,
/** After picking Rpartstore/Dialogys from the submenu (catalog window opens). */
afterRenaultCatalogOpen: 12_000,
/** After a Rpartstore (re)open — poll for the search-home landing markers to
* confirm it actually LOADED (vs the "born-stuck" infinite spinner). Short so
* a stuck instance is detected fast and reopened fresh within the budget. */
afterRpartstoreLoad: 12_000,
/** After submitting the Rpartstore VIN (Enter) — wait for the vehicle page. */
afterRpartstoreSubmit: 8_000,
/** After submitting the Dialogys VIN (ПОИСК) — wait for the vehicle page. */
afterDialogysSubmit: 8_000,
} as const; } as const;
/**
* Hard wall-clock budget (ms) for a SINGLE decode(vin) call, spanning all of its
* internal attempts. A single Vinpin seat is shared by every decode, so one VIN
* that gets stuck in a re-establish/relaunch livelock must never grind for
* minutes and starve real decodes. When the budget is exceeded the driver aborts,
* tears the browser down, poisons the seat (forcing the next decode to cold
* re-establish) and returns null. Kept well above the healthy p90 (a warm decode
* is seconds; a full cold re-establish is ~60-80s) so it only ever fires on a
* genuine stall. Bumped 150s→180s to leave a cheap safety margin for a slow cold
* establish stacking on the Rpartstore launch-error probe + the Dialogys fallback
* decode (~25s) — the Rpartstore launch-error short-circuit means we no longer
* waste ~54s of reopens, but the extra headroom covers a cold-establish edge.
* Override with VINPIN_DECODE_BUDGET_MS. */
export const VINPIN_DECODE_BUDGET_MS = 180_000;
/**
* Rpartstore acquire-with-spinner-guard tunables. A freshly-opened Rpartstore
* instance sometimes gets "born stuck" on an infinite spinner (survives
* raise/maximize); the only reliable fix is to CLOSE the stuck instance and
* reopen a FRESH one. `maxOpens` bounds the initial-open-plus-reopen attempts;
* `acquireBudgetMs` sub-caps the whole acquire loop so a hopeless Rpartstore
* still leaves wall-clock headroom (inside VINPIN_DECODE_BUDGET_MS) to fall back
* to Dialogys rather than burning the entire decode budget on reopens.
*/
export const VINPIN_RPARTSTORE = {
// Rpartstore has two failure modes: a genuine born-stuck spinner (reopen can
// recover it) and a hard server-side launch error "Ошибка запуска каталога"
// (reopen NEVER helps — Rpartstore is DOWN). Detecting the tiny centered error
// modal by OCR proved unreliable across renderings, and burning reopens on a
// DOWN Rpartstore (a) wastes ~54s and (b) dirties the RDS desktop so the
// Dialogys fallback then can't finish inside the budget.
// `maxOpens` still bounds reopen attempts (a real transient spinner can recover
// on a reopen), but `acquireBudgetMs` is the hard lever: one open+load-poll is
// ~22s, so a 14s wall-clock sub-cap makes the loop bail after the FIRST open if
// it hasn't loaded — straight to Dialogys on a still-clean seat (~25–52s decode)
// — instead of grinding 3 reopens. A healthy Rpartstore loads within the first
// open's poll and is used as before; the cap only prevents wasted reopens.
maxOpens: 3,
acquireBudgetMs: 14_000,
/** In-memory cooldown after a Rpartstore HARD launch-error (or repeated
* load-failure across all reopens): Rpartstore-down is server-side and
* PERSISTENT, so reopening it on every Renault VIN just re-dirties the RDS
* desktop (each failed open leaves a resumed window / launch-error modal). While
* the cooldown is active, Renault decodes route STRAIGHT to the proven ~30s
* Dialogys path (Rpartstore is never opened). A successful Rpartstore load clears
* it immediately, so a transient blip self-heals on the next decode. */
launchErrorCooldownMs: 10 * 60_000,
} as const;
/** Per-key delay (ms) when typing a VIN into a focused canvas field. A focused
* field keeps up at ~20ms; the old 45-50ms was conservative padding (17-char VIN
* ≈ 340ms vs ≈ 850ms). */
export const VINPIN_TYPE_DELAY_MS = 20;
/** Backspaces used to clear a VIN field after Ctrl+A + Delete. A few for
* insurance on a focused field — the old 40 was overkill. */
export const VINPIN_FIELD_CLEAR_BACKSPACES = 5;
/** /**
* Known Fiat model tokens used to extract the model name from the decode modal * Known Fiat model tokens used to extract the model name from the decode modal
* text. The modal interleaves Cyrillic boilerplate, a platform code, the model * text. The modal interleaves Cyrillic boilerplate, a platform code, the model
@@ -125,11 +525,92 @@ export const FIAT_MODEL_TOKENS = [
] as const; ] as const;
/** /**
* Brands for which the Vinpin fallback is enabled. Fiat-only for now (the * Known Renault/Dacia model tokens used to extract the model name from the
* Egea/NM4356 no-catalog cluster); a Set so it's trivially extensible later. * Rpartstore/Dialogys vehicle-page header. Same token-matching strategy as the
* Compared case-insensitively against the canonical browse brand. * Fiat parser (far more robust than positional parsing against OCR noise).
* Generation numbers / roman numerals in the header are ignored — PL24 catalog
* rows carry their own generation suffixes and matching is best-effort.
*/ */
export const VINPIN_BRAND_ALLOWLIST = new Set<string>(["fiat"]); export const RENAULT_MODEL_TOKENS = [
"CLIO",
"LUTECIA", // Clio's JP/TR export name — appears in PL24 rows ("CLIO 4 / LUTECIA 4")
"MEGANE",
"SCENIC",
"KANGOO",
"LAGUNA",
"LATITUDE",
"SAFRANE",
"FLUENCE",
"SYMBOL",
"THALIA",
"KADJAR",
"CAPTUR",
"DUSTER",
"SANDERO",
"LOGAN",
"TALISMAN",
"ESPACE",
"TWINGO",
"MODUS",
"KOLEOS",
"TRAFIC",
"MASTER",
"TALIANT",
"ARKANA",
"AUSTRAL",
"VELSATIS",
"TWIZY",
"ZOE",
"EXPRESS",
// Dacia
"DOKKER",
"LODGY",
"SPRING",
// Old R-number platforms + TR-market badges (pre-2000). These genuinely need
// Rpartstore to VIN-resolve, so this mostly future-proofs the header parse for
// an old Renault (e.g. VF1553… R19). The parser tokenises on non-alphanumerics,
// so a BARE "19" would collide with year/engine digits — the R-prefixed form
// ("R19") is required so it only matches the actual model badge, never a number.
"R5",
"R9",
"R11",
"R12",
"R19",
"R21",
"R25",
"EUROPA", // R19 Europa (TR)
"BROADWAY", // R9 Broadway (TR)
"TOROS", // R12 Toros (TR)
"FLASH", // R11 Flash (TR)
] as const;
/** WMIs that route to the Renault (Rpartstore/Dialogys) flow. VF1/VF2 are the
* common Renault WMIs; VF6/VF7 are included per the benchmark (some Renault/
* Dacia LCVs and older platforms). Dacia-badged cars often carry a Renault WMI
* (e.g. VF1 Duster) — the RENAULT-vs-DACIA distinction is read from the decode
* header, not the WMI. UU1 is the dedicated Dacia WMI. */
const RENAULT_FLOW_WMIS = new Set<string>(["VF1", "VF2", "VF6", "VF7", "UU1"]);
/**
* Pick the Vinpin catalog flow for a VIN by brand. Renault/Dacia → the new
* Rpartstore/Dialogys flow; everything else (including Fiat) → the existing ePER
* flow, so Fiat behaviour is byte-identical. Derived from the WMI: trusts
* `getBrandFromWmi` first (Renault/Dacia), then a Renault-WMI allowlist.
*/
export function selectVinpinBrandFlow(vin: string): "renault" | "fiat" {
const wmi = (vin || "").toUpperCase().slice(0, 3);
const brand = getBrandFromWmi(wmi);
if (brand === "Renault" || brand === "Dacia") return "renault";
if (RENAULT_FLOW_WMIS.has(wmi)) return "renault";
return "fiat";
}
/**
* Brands for which the Vinpin fallback is enabled. Fiat (Egea/NM4356 no-catalog
* cluster) + Renault/Dacia (Rpartstore/Dialogys flow). A Set so it's trivially
* extensible. Compared case-insensitively against the canonical browse brand.
*/
export const VINPIN_BRAND_ALLOWLIST = new Set<string>(["fiat", "renault", "dacia"]);
export function isVinpinBrandAllowed(brand: string | null | undefined): boolean { export function isVinpinBrandAllowed(brand: string | null | undefined): boolean {
if (!brand) return false; if (!brand) return false;

View File

@@ -85,4 +85,103 @@ describe("pickBestCatalogMatch", () => {
// Identical tokens + no year → equal score → recency decides. // Identical tokens + no year → equal score → recency decides.
expect(pickBestCatalogMatch({ model: "PUNTO", modelYear: null }, puntos)).toBe("punto-new"); expect(pickBestCatalogMatch({ model: "PUNTO", modelYear: null }, puntos)).toBe("punto-new");
}); });
it("breaks a score tie toward the richer catalog (more categories)", () => {
const koleos: CatalogCandidate[] = [
{ id: "koleos-thin", model: "KOLEOS", year: null, categoryCount: 12 },
{ id: "koleos-full", model: "KOLEOS", year: null, categoryCount: 44 },
];
// Identical tokens + no year → equal score → category count decides.
expect(pickBestCatalogMatch({ model: "KOLEOS", modelYear: null }, koleos)).toBe("koleos-full");
});
});
describe("pickBestCatalogMatch — market-qualifier precision (Renault/Dacia)", () => {
it("prefers the EXACT model over a wrong-market superset (KADJAR beats KADJAR ÇİN)", () => {
// The confirmed prod bug: a European VF1 Renault decoded as "KADJAR" landed
// on the China-market "KADJAR ÇİN" catalog (fewer categories, wrong parts).
const candidates: CatalogCandidate[] = [
{ id: "kadjar-cn", model: "KADJAR ÇİN", year: null, categoryCount: 22 },
{ id: "kadjar-eu", model: "KADJAR", year: null, categoryCount: 44 },
];
expect(pickBestCatalogMatch({ model: "KADJAR", modelYear: "2018" }, candidates)).toBe(
"kadjar-eu",
);
});
it("still picks the exact model even when the market candidate is richer", () => {
// Market penalty must dominate — an exact match wins regardless of category
// count or ordering.
const candidates: CatalogCandidate[] = [
{ id: "kadjar-cn", model: "KADJAR ÇİN", year: null, categoryCount: 999 },
{ id: "kadjar-eu", model: "KADJAR", year: null, categoryCount: 1 },
];
expect(pickBestCatalogMatch({ model: "KADJAR", modelYear: null }, candidates)).toBe(
"kadjar-eu",
);
});
it("penalizes a market qualifier but NOT a generation token (CLIO)", () => {
const candidates: CatalogCandidate[] = [
{ id: "clio-cn", model: "CLIO ÇİN", year: null },
{ id: "clio", model: "CLIO", year: null },
];
// Exact "CLIO" beats the China-market superset.
expect(pickBestCatalogMatch({ model: "CLIO", modelYear: null }, candidates)).toBe("clio");
});
it("keeps generations matchable — a generation extra token is not a market penalty", () => {
// Decoded "CLIO" with only generation-qualified catalogs (no exact bare CLIO)
// and one China catalog. The generation candidate must win over the market one,
// proving the market penalty doesn't collateral-damage generations.
const candidates: CatalogCandidate[] = [
{ id: "clio-cn", model: "CLIO ÇİN", year: null },
{
id: "clio-4",
model: "CLIO 4 / LUTECIA 4 (2012-2019)",
year: "2012-2019",
categoryCount: 40,
},
{
id: "clio-3",
model: "CLIO 3 / LUTECIA 3 (2005-2014)",
year: "2005-2014",
categoryCount: 30,
},
];
const id = pickBestCatalogMatch({ model: "CLIO", modelYear: "2015" }, candidates);
// Year-overlap picks the 2012-2019 gen-4; the China catalog is penalized out.
expect(id).toBe("clio-4");
});
it("matches an exact generation model and penalizes only the market superset (DUSTER II)", () => {
// Roman-numeral generations survive tokenization (single digits are dropped by
// the length>=2 filter, an existing behavior). Decoded "DUSTER II" is exact on
// duster-2; "DUSTER II ÇİN" carries an extra market token and is penalized out.
const candidates: CatalogCandidate[] = [
{ id: "duster-2", model: "DUSTER II", year: null, categoryCount: 30 },
{ id: "duster-cn", model: "DUSTER II ÇİN", year: null, categoryCount: 30 },
];
expect(pickBestCatalogMatch({ model: "DUSTER II", modelYear: null }, candidates)).toBe(
"duster-2",
);
});
it("falls back to a market catalog only when it is the sole candidate", () => {
// If the ONLY catalog for a decoded model is a regional one, still match it —
// the penalty lowers the score but does not disqualify.
const candidates: CatalogCandidate[] = [{ id: "x62-cn", model: "X62 CHINE", year: null }];
expect(pickBestCatalogMatch({ model: "X62", modelYear: null }, candidates)).toBe("x62-cn");
});
});
describe("modelTokens — diacritic folding", () => {
it("folds Turkish diacritics so market qualifiers survive as ASCII tokens", () => {
// Without folding, ÇİN loses Ç/İ to the ASCII strip and collapses to a
// dropped 1-char "N", making KADJAR ÇİN tokenize identically to KADJAR.
expect(modelTokens("KADJAR ÇİN")).toEqual(["KADJAR", "CIN"]);
expect(modelTokens("ARKANA RUSYA")).toEqual(["ARKANA", "RUSYA"]);
// The single-digit "2" is dropped by the length>=2 filter (existing behavior).
expect(modelTokens("KOLEOS 2 - ÇİN")).toEqual(["KOLEOS", "CIN"]);
});
}); });

View File

@@ -18,11 +18,68 @@ export interface CatalogCandidate {
id: string; id: string;
model: string | null; model: string | null;
year: string | null; year: string | null;
/** How many catalog categories this vehicle has fetched. Used only as a final
* tiebreak among otherwise-equal candidates — the fuller catalog is the
* mainstream one. Optional so the pure picker can be unit-tested without it. */
categoryCount?: number | null;
} }
/**
* Market/region qualifier tokens (diacritic-folded, upper-case). A catalog model
* that carries one of these tokens BEYOND the decoded model targets a specific
* regional market — e.g. "KADJAR ÇİN" is the China-market Kadjar catalog (source
* XZH, 22 categories) vs the mainstream European "KADJAR" (XFE, 44 categories).
* For a European (VF1…) VIN the regional catalog serves the wrong parts, so a
* candidate whose EXTRA tokens are region qualifiers is heavily penalized — but
* only when the token is extra (the decode itself doesn't carry a market today).
*
* Generation tokens (roman numerals, digits, platform codes like "II"/"3"/"XM3")
* are deliberately NOT here, so multi-generation models stay fully matchable;
* only MARKET qualifiers get the penalty.
*
* Grounded in prod data — the real Renault/Dacia catalog models that carry a
* region qualifier are: KADJAR ÇİN, CAPTUR II ÇİN, KOLEOS 2 - ÇİN, ARKANA RUSYA
* and X62 CHINE. ("EUROPE" appears too — ARKANA EUROPE, CAPTUR II EUROPE — but
* that is the mainstream market and is never penalized.)
*/
export const MARKET_QUALIFIERS = new Set<string>([
// China — "ÇİN" folds to CIN via diacritic normalization; CHINE is the French
// spelling seen in "X62 CHINE".
"CIN",
"CHINA",
"CHINE",
"CN",
// Russia
"RUSYA",
"RUSSIA",
"RU",
// Brazil
"BREZILYA",
"BRAZIL",
"BR",
// India
"HINDISTAN",
"INDIA",
"IN",
// Korea
"KORE",
"KOREA",
// Mexico / Mercosur
"MEKSIKA",
"MEXICO",
"MERCOSUR",
// Other regional
"GCC",
"USA",
"AMERIKA",
]);
export interface DecodedForMatch { export interface DecodedForMatch {
model: string | null; model: string | null;
modelYear: string | null; modelYear: string | null;
/** Brand to match against (catalog_vehicles.brand_name). Defaults to Fiat when
* omitted, preserving the original Fiat-only behaviour. */
brand?: string | null;
} }
/** Tokenize a model string into upper-case model tokens, dropping parenthetical /** Tokenize a model string into upper-case model tokens, dropping parenthetical
@@ -34,14 +91,23 @@ export interface DecodedForMatch {
* tiebreak over the modern Egea. */ * tiebreak over the modern Egea. */
export function modelTokens(s: string | null | undefined): string[] { export function modelTokens(s: string | null | undefined): string[] {
if (!s) return []; if (!s) return [];
return s return (
.toUpperCase() s
.replace(/\([^)]*\)/g, " ") // drop parenthetical year ranges .toUpperCase()
.replace(/\b(19[5-9]\d|20[0-3]\d)\b/g, " ") // drop bare YEARS 1950-2039; keep displacements // Fold diacritics to ASCII so market qualifiers survive tokenization. Without
.replace(/[^A-Z0-9]+/g, " ") // this the Turkish "ÇİN" (China) loses its Ç/İ to the [^A-Z0-9] strip below
.split(" ") // and collapses to a dropped 1-char "N" — making "KADJAR ÇİN" tokenize
.map((t) => t.trim()) // IDENTICALLY to "KADJAR" and defeating both the specificity tiebreak and the
.filter((t) => t.length >= 2); // market penalty. NFD + combining-mark removal maps ÇİN→CIN, Ş→S, Ğ→G, Ö→O …
.normalize("NFD")
.replace(/\p{M}/gu, "") // strip the combining marks NFD split off
.replace(/\([^)]*\)/g, " ") // drop parenthetical year ranges
.replace(/\b(19[5-9]\d|20[0-3]\d)\b/g, " ") // drop bare YEARS 1950-2039; keep displacements
.replace(/[^A-Z0-9]+/g, " ")
.split(" ")
.map((t) => t.trim())
.filter((t) => t.length >= 2)
);
} }
/** Parse a year range from free text. Returns {start, end} where end===null /** Parse a year range from free text. Returns {start, end} where end===null
@@ -74,8 +140,18 @@ function yearInRange(year: number, range: { start: number; end: number | null })
/** /**
* Pick the best catalog_vehicles row for a decoded model + year. A candidate * Pick the best catalog_vehicles row for a decoded model + year. A candidate
* qualifies only when EVERY decoded model token appears in the candidate's * qualifies only when EVERY decoded model token appears in the candidate's
* model tokens (subset match). Among qualifiers, prefer year-range overlap, * model tokens (subset match). Scoring, strongest signal first:
* then the most specific (fewest extra tokens). Returns the id or null. * 1. Year-range overlap — the strongest signal; routes multi-generation models
* (a 2022 "TIPO-EGEA" → the 2020+ MCA catalog, not the 2015-2021 one).
* 2. EXACT normalized model match (candidate tokens ≡ decoded tokens) — a
* smaller bonus that breaks the tie in favour of a plain "KADJAR" over the
* superset "KADJAR ÇİN" when no year distinguishes them.
* 3. Market-qualifier penalty — extra tokens that are region qualifiers (ÇİN,
* RUSYA, …) make this a WRONG-market catalog; penalized hard so it only ever
* wins as the sole candidate. Generation / other extra tokens keep only the
* mild "fewer extras = more specific" penalty, so generations stay matchable.
* 4. Tiebreaks on equal score: richer catalog (more categories), then newer.
* Returns the id or null.
*/ */
export function pickBestCatalogMatch( export function pickBestCatalogMatch(
decoded: DecodedForMatch, decoded: DecodedForMatch,
@@ -85,7 +161,12 @@ export function pickBestCatalogMatch(
if (decTokens.length === 0) return null; if (decTokens.length === 0) return null;
const decYear = decoded.modelYear ? Number.parseInt(decoded.modelYear, 10) : null; const decYear = decoded.modelYear ? Number.parseInt(decoded.modelYear, 10) : null;
let best: { id: string; score: number; startYear: number } | null = null; let best: {
id: string;
score: number;
categoryCount: number;
startYear: number;
} | null = null;
for (const cand of candidates) { for (const cand of candidates) {
const candText = `${cand.model ?? ""} ${cand.year ?? ""}`; const candText = `${cand.model ?? ""} ${cand.year ?? ""}`;
@@ -95,21 +176,47 @@ export function pickBestCatalogMatch(
// Subset requirement — all decoded model tokens must be present. // Subset requirement — all decoded model tokens must be present.
if (!decTokens.every((t) => candSet.has(t))) continue; if (!decTokens.every((t) => candSet.has(t))) continue;
const extraTokens = candTokens.filter((t) => !decTokens.includes(t));
let score = 1000; // base for any qualifying candidate let score = 1000; // base for any qualifying candidate
// (1) EXACT normalized model-name match: candidate carries NO tokens beyond
// the decoded model. This breaks the tie in favour of the plain model over a
// superset (e.g. "KADJAR" over "KADJAR ÇİN" when neither has a distinguishing
// year). Kept SMALLER than the year-range swing (±700) on purpose, so a
// decisive model-year still routes generations correctly — a 2022 "TIPO-EGEA"
// must still land on the 2020+ MCA catalog, not the exact-named 2015-2021 one.
if (extraTokens.length === 0) score += 300;
// (2) Year-range overlap.
const range = parseYearRange(candText); const range = parseYearRange(candText);
if (decYear && Number.isFinite(decYear) && range) { if (decYear && Number.isFinite(decYear) && range) {
score += yearInRange(decYear, range) ? 500 : -200; score += yearInRange(decYear, range) ? 500 : -200;
} }
// Tiebreak: fewer extra tokens = more specific match.
const extra = candTokens.filter((t) => !decTokens.includes(t)).length;
score -= extra;
// Final tiebreak on equal score: prefer the newer catalog. Without a year // (3) Extra-token penalties. A region-qualifier extra token means the
// signal an ambiguous model (e.g. bare "TIPO") must never fall back onto an // candidate is a wrong-market catalog for a decode that carries no market —
// ancient generation — modern is the overwhelmingly likelier intent. // penalize hard so it can only win when it is the ONLY candidate. Everything
// else (generation numerals, platform codes) keeps the mild specificity
// penalty, leaving multi-generation models fully matchable.
const marketExtras = extraTokens.filter((t) => MARKET_QUALIFIERS.has(t)).length;
const otherExtras = extraTokens.length - marketExtras;
score -= otherExtras;
score -= marketExtras * 5000;
// (4) Tiebreaks on equal score: prefer the richer catalog (more categories —
// the fuller catalog is the mainstream one), then the newer generation. A
// bare, year-less model (e.g. "TIPO") must never fall back onto an ancient
// generation — modern is the overwhelmingly likelier intent.
const categoryCount = cand.categoryCount ?? 0;
const startYear = range?.start ?? 0; const startYear = range?.start ?? 0;
if (!best || score > best.score || (score === best.score && startYear > best.startYear)) { const better =
best = { id: cand.id, score, startYear }; !best ||
score > best.score ||
(score === best.score && categoryCount > best.categoryCount) ||
(score === best.score && categoryCount === best.categoryCount && startYear > best.startYear);
if (better) {
best = { id: cand.id, score, categoryCount, startYear };
} }
} }
@@ -123,25 +230,35 @@ export class VinpinCatalogMatcher {
constructor(@Inject(DATABASE) private readonly db: Database) {} constructor(@Inject(DATABASE) private readonly db: Database) {}
/** /**
* Find the best PL24 Fiat catalog_vehicle for a decoded model + year. * Find the best PL24 catalog_vehicle (of the decoded brand — Fiat by default,
* Returns the catalog_vehicle id, or null when nothing matches. * or Renault/Dacia) for a decoded model + year. Returns the id, or null.
*/ */
async match(decoded: DecodedForMatch): Promise<string | null> { async match(decoded: DecodedForMatch): Promise<string | null> {
if (!decoded.model) return null; if (!decoded.model) return null;
const brand = (decoded.brand ?? "Fiat").toLowerCase();
const rows = await this.db const rows = await this.db
.select({ .select({
id: catalogVehicles.id, id: catalogVehicles.id,
model: catalogVehicles.model, model: catalogVehicles.model,
year: catalogVehicles.year, year: catalogVehicles.year,
// Category count feeds the richer-catalog tiebreak (more categories = the
// mainstream catalog). Correlated subquery keeps the row shape flat.
categoryCount: sql<number>`(
SELECT count(*)::int FROM categories
WHERE categories.catalog_vehicle_id = ${catalogVehicles.id}
)`,
}) })
.from(catalogVehicles) .from(catalogVehicles)
.where( .where(
and(sql`lower(${catalogVehicles.brandName}) = 'fiat'`, eq(catalogVehicles.source, "pl24")), and(
sql`lower(${catalogVehicles.brandName}) = ${brand}`,
eq(catalogVehicles.source, "pl24"),
),
); );
const id = pickBestCatalogMatch(decoded, rows as CatalogCandidate[]); const id = pickBestCatalogMatch(decoded, rows as CatalogCandidate[]);
this.logger.log( this.logger.log(
`match model="${decoded.model}" year=${decoded.modelYear ?? "?"} → ${id ?? "null"} (over ${rows.length} Fiat catalog vehicles)`, `match brand=${brand} model="${decoded.model}" year=${decoded.modelYear ?? "?"} → ${id ?? "null"} (over ${rows.length} ${brand} catalog vehicles)`,
); );
return id; return id;
} }

View File

@@ -0,0 +1,76 @@
import { describe, expect, it } from "vitest";
import { pollForText } from "./vinpin.ocr";
/** Deterministic fake clock: `sleep` advances virtual time; `now` reads it. */
function makeClock() {
let t = 0;
const slept: number[] = [];
return {
now: () => t,
sleep: async (ms: number) => {
slept.push(ms);
t += ms;
},
slept,
total: () => slept.reduce((a, b) => a + b, 0),
};
}
describe("pollForText", () => {
it("returns early as soon as the predicate matches (fast path)", async () => {
const clock = makeClock();
const reads = ["no", "no", "hit"];
let i = 0;
const res = await pollForText({
read: async () => reads[i++] ?? "",
predicate: (t) => t === "hit",
capMs: 10_000,
intervalMs: 700,
sleep: clock.sleep,
now: clock.now,
});
expect(res.matched).toBe(true);
expect(res.text).toBe("hit");
// Stopped at the 3rd read — well under the cap.
expect(i).toBe(3);
expect(clock.total()).toBe(2100);
expect(clock.total()).toBeLessThan(10_000);
});
it("caps total sleep at capMs when the predicate never matches (fallback == old fixed wait)", async () => {
const clock = makeClock();
let reads = 0;
const res = await pollForText({
read: async () => {
reads++;
return "no";
},
predicate: (t) => t === "hit",
capMs: 2_000,
intervalMs: 700,
sleep: clock.sleep,
now: clock.now,
});
expect(res.matched).toBe(false);
expect(res.text).toBe("no");
// Total sleep is exactly the cap — never longer than the old fixed wait.
expect(clock.total()).toBe(2_000);
// The final interval was clamped to the remaining budget (no overshoot).
expect(Math.max(...clock.slept)).toBeLessThanOrEqual(700);
expect(reads).toBeGreaterThan(0);
});
it("matches on the very first read without over-sleeping", async () => {
const clock = makeClock();
const res = await pollForText({
read: async () => "ready",
predicate: (t) => t.includes("ready"),
capMs: 12_000,
intervalMs: 750,
sleep: clock.sleep,
now: clock.now,
});
expect(res.matched).toBe(true);
expect(clock.total()).toBe(750); // one interval, then matched
});
});

View File

@@ -133,6 +133,43 @@ export async function ocrRegion(page: Page, clip?: OcrClip, scale = 3): Promise<
} }
} }
/**
* Poll a text `read` until `predicate(text)` holds, or the `capMs` budget is
* exhausted. Returns as soon as the predicate matches (the common, fast case);
* otherwise the total elapsed sleep equals `capMs` — the SAME fallback wait the
* old fixed `waitForTimeout(capMs)` used, so worst-case behaviour is unchanged.
*
* Pure/injectable (no Playwright/OCR deps) so it can be unit-tested directly:
* pass a fake `read`, `sleep` and `now`. The driver wraps it with an OCR read.
*/
export interface PollForTextOptions {
read: () => Promise<string>;
predicate: (text: string) => boolean;
/** Fallback cap — total sleep never exceeds this (== the old fixed wait). */
capMs: number;
/** Cadence between reads. */
intervalMs: number;
sleep: (ms: number) => Promise<void>;
/** Injectable clock (defaults to Date.now) — for deterministic tests. */
now?: () => number;
}
export async function pollForText(
opts: PollForTextOptions,
): Promise<{ matched: boolean; text: string }> {
const now = opts.now ?? (() => Date.now());
const interval = Math.max(1, opts.intervalMs);
const deadline = now() + opts.capMs;
let text = "";
while (now() < deadline) {
const remaining = deadline - now();
await opts.sleep(Math.min(interval, remaining));
text = await opts.read();
if (opts.predicate(text)) return { matched: true, text };
}
return { matched: false, text };
}
/** Tear down the shared tesseract worker (best-effort). */ /** Tear down the shared tesseract worker (best-effort). */
export async function terminateOcr(): Promise<void> { export async function terminateOcr(): Promise<void> {
if (!workerPromise) return; if (!workerPromise) return;

View File

@@ -1,5 +1,10 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { isUsableParse, parseVinpinModal } from "./vinpin.parser"; import {
isUsableParse,
isUsableRenaultParse,
parseRenaultHeader,
parseVinpinModal,
} from "./vinpin.parser";
const SAMPLE = const SAMPLE =
"MVS, найденные по vin NM435600006H43436 6J - TIPO - EGEA (2015-2021) 356G37001162 - 3V HIGH PLUS 1.6 120CV D5 CM E6 GS TR Двигатель: 8165300 Автомобиль: 279476 Prod. date: 2/8/2017 Vin: NM435600006H43436"; "MVS, найденные по vin NM435600006H43436 6J - TIPO - EGEA (2015-2021) 356G37001162 - 3V HIGH PLUS 1.6 120CV D5 CM E6 GS TR Двигатель: 8165300 Автомобиль: 279476 Prod. date: 2/8/2017 Vin: NM435600006H43436";
@@ -50,3 +55,56 @@ describe("parseVinpinModal", () => {
expect(isUsableParse(p)).toBe(false); // → not a real decode expect(isUsableParse(p)).toBe(false); // → not a real decode
}); });
}); });
describe("parseRenaultHeader", () => {
it("parses an Rpartstore RENAULT header (model + brand)", () => {
const p = parseRenaultHeader("RENAULT KADJAR (RFE) Şasi: VF1RFE00653633190");
expect(p.model).toBe("KADJAR");
expect(p.brand).toBe("RENAULT");
expect(isUsableRenaultParse(p)).toBe(true);
});
it("reads DACIA as the brand when the header carries it", () => {
const p = parseRenaultHeader("DACIA DUSTER (HSA) Şasi: VF1HJD40865644941");
expect(p.model).toBe("DUSTER");
expect(p.brand).toBe("DACIA");
});
it("extracts the base model and ignores the generation numeral (CLIO IV)", () => {
const p = parseRenaultHeader("RENAULT CLIO IV (R0G) Şasi: VF15R0G0H49335605");
expect(p.model).toBe("CLIO");
expect(p.brand).toBe("RENAULT");
});
it("handles a Dialogys header with no explicit brand (defaults RENAULT)", () => {
const p = parseRenaultHeader("Clio II (X65), 1.5 dCi");
expect(p.model).toBe("CLIO");
expect(p.brand).toBe("RENAULT");
});
it("captures a model year when the header carries one", () => {
const p = parseRenaultHeader("RENAULT LATITUDE (2011-2015)");
expect(p.model).toBe("LATITUDE");
expect(p.modelYear).toBe("2011");
});
it("does NOT mis-grab the status-bar license-expiry date as the model year", () => {
// The full-frame OCR fallback sweeps in the Rpartstore/Dialogys status bar,
// whose license EXPIRY date ("…14.07.2026") used to be read as the model year.
const p = parseRenaultHeader("RENAULT KADJAR (RFE) Şasi: VF1RFE00653633190 Lisans: 14.07.2026");
expect(p.model).toBe("KADJAR");
expect(p.modelYear).toBeNull(); // NOT "2026" from the expiry date
});
it("still prefers a genuine generation range even when an expiry date is present", () => {
const p = parseRenaultHeader("RENAULT LATITUDE (2011-2015) Lisans: 14.07.2026");
expect(p.modelYear).toBe("2011"); // the (2011-2015) range wins over the date
});
it("returns no model / unusable for headers without a known token", () => {
const p = parseRenaultHeader("İlişikli araç bulunamadı");
expect(p.model).toBeNull();
expect(isUsableRenaultParse(p)).toBe(false);
expect(isUsableRenaultParse(parseRenaultHeader(""))).toBe(false);
});
});

View File

@@ -13,7 +13,7 @@
* Kept dependency-free and side-effect-free so it can be unit-tested directly. * Kept dependency-free and side-effect-free so it can be unit-tested directly.
*/ */
import { FIAT_MODEL_TOKENS } from "./vinpin.constants"; import { FIAT_MODEL_TOKENS, RENAULT_MODEL_TOKENS } from "./vinpin.constants";
export interface VinpinParsed { export interface VinpinParsed {
model: string | null; model: string | null;
@@ -106,3 +106,68 @@ export function parseVinpinModal(rawText: string | null | undefined): VinpinPars
export function isUsableParse(p: VinpinParsed): boolean { export function isUsableParse(p: VinpinParsed): boolean {
return Boolean(p.sincom); return Boolean(p.sincom);
} }
// ─── Renault (Rpartstore / Dialogys) header parser ───────────────
export interface VinpinRenaultParsed {
/** Extracted model, e.g. "KADJAR", "CLIO", "DUSTER". */
model: string | null;
/** "RENAULT" | "DACIA" — read from the header, else defaulted to "RENAULT". */
brand: "RENAULT" | "DACIA";
/** Model year if the header carried one (best-effort). */
modelYear: string | null;
}
const RENAULT_TOKEN_SET = new Set<string>(RENAULT_MODEL_TOKENS as readonly string[]);
/**
* Extract the Renault/Dacia model from an OCR'd vehicle-page header.
*
* Rpartstore header (primary): "RENAULT KADJAR (RFE)" / "DACIA DUSTER (...)" +
* "Şasi: VF1RFE00653633190".
* Dialogys header (fallback): "Clio II (X65), 1.5 dCi" (no explicit brand).
*
* Strategy (mirrors the Fiat token-run parser): collect the contiguous run of
* KNOWN Renault/Dacia model tokens (so "GRAND KOLEOS" → "KOLEOS", "CLIO II" →
* "CLIO"), and read the brand from a leading RENAULT/DACIA token (Dialogys omits
* it → default RENAULT). Generation numbers / roman numerals are intentionally
* dropped — PL24 rows carry their own generation suffixes and matching is
* best-effort.
*/
export function parseRenaultHeader(rawText: string | null | undefined): VinpinRenaultParsed {
const text = (rawText ?? "").replace(/\s+/g, " ").trim();
const upper = text.toUpperCase();
const brand: "RENAULT" | "DACIA" = /\bDACIA\b/.test(upper) ? "DACIA" : "RENAULT";
const tokens = upper.split(/[^A-Z0-9]+/).filter(Boolean);
const collected: string[] = [];
for (const tok of tokens) {
if (RENAULT_TOKEN_SET.has(tok)) {
collected.push(tok);
} else if (collected.length > 0) {
// Stop at the first non-model token after the model run has started.
break;
}
}
// De-dup consecutive repeats (e.g. "CLIO CLIO" OCR doubling) preserving order.
const deduped = collected.filter((t, i) => i === 0 || t !== collected[i - 1]);
const model = deduped.length > 0 ? deduped.join("-") : null;
// Model year: prefer an explicit generation range "(2015-2021)" from the header.
// A BARE year is only taken as a fallback AND only after stripping full calendar
// dates — the Rpartstore/Dialogys STATUS BAR carries the license EXPIRY date
// ("…14.07.2026") which the full-frame OCR fallback would otherwise mis-grab as
// the model year (the "2026" bug). Stripping dd.mm.yyyy / dd/mm/yyyy / dd-mm-yyyy
// first constrains the bare-year scan to real header text.
const withoutDates = text.replace(/\b\d{1,2}[./-]\d{1,2}[./-]\d{4}\b/g, " ");
const modelYear =
text.match(YEAR_RANGE_RE)?.[1] ?? withoutDates.match(/\b(19|20)\d{2}\b/)?.[0] ?? null;
return { model, brand, modelYear };
}
/** A Renault parse is usable once we have a model token. */
export function isUsableRenaultParse(p: VinpinRenaultParsed): boolean {
return Boolean(p.model);
}

View File

@@ -0,0 +1,94 @@
import { describe, expect, it } from "vitest";
import {
isVinpinBrandAllowed,
isVinpinBusinessHours,
orderTaskbarWindows,
selectVinpinBrandFlow,
selectVinpinWarmWindow,
} from "./vinpin.constants";
describe("selectVinpinBrandFlow", () => {
it("routes Renault WMIs (VF1/VF2) to the renault flow", () => {
expect(selectVinpinBrandFlow("VF1RFE00653633190")).toBe("renault"); // Kadjar
expect(selectVinpinBrandFlow("VF15R0G0H49335605")).toBe("renault"); // Clio IV
expect(selectVinpinBrandFlow("VF1LB030523661167")).toBe("renault"); // Clio II
expect(selectVinpinBrandFlow("VF2ABCDEFGH123456")).toBe("renault");
});
it("routes a Dacia-badged VF1 VIN to the renault flow (brand read from header)", () => {
expect(selectVinpinBrandFlow("VF1HJD40865644941")).toBe("renault"); // Dacia Duster
});
it("routes the dedicated Dacia WMI (UU1) to the renault flow", () => {
expect(selectVinpinBrandFlow("UU1ABCDEFGH123456")).toBe("renault");
});
it("keeps Fiat VINs on the fiat flow (byte-identical behaviour)", () => {
expect(selectVinpinBrandFlow("NM435600006H43436")).toBe("fiat"); // Tofaş Egea
expect(selectVinpinBrandFlow("ZFA31200000000000")).toBe("fiat");
});
it("defaults unknown/other WMIs to the fiat flow", () => {
expect(selectVinpinBrandFlow("WVWZZZ1JZ3W597935")).toBe("fiat"); // VW
expect(selectVinpinBrandFlow("")).toBe("fiat");
});
});
describe("isVinpinBrandAllowed", () => {
it("allows Fiat, Renault and Dacia (case-insensitive)", () => {
expect(isVinpinBrandAllowed("Fiat")).toBe(true);
expect(isVinpinBrandAllowed("renault")).toBe(true);
expect(isVinpinBrandAllowed("DACIA")).toBe(true);
expect(isVinpinBrandAllowed(" Renault ")).toBe(true);
});
it("rejects other brands and empty input", () => {
expect(isVinpinBrandAllowed("Peugeot")).toBe(false);
expect(isVinpinBrandAllowed(null)).toBe(false);
expect(isVinpinBrandAllowed(undefined)).toBe(false);
});
});
describe("selectVinpinWarmWindow — brand → taskbar window routing", () => {
it("routes Renault/Dacia VINs to the Rpartstore window (Dialogys is the in-flow fallback)", () => {
expect(selectVinpinWarmWindow("VF1RFE00653633190")).toBe("rpartstore"); // Renault Kadjar
expect(selectVinpinWarmWindow("UU1ABCDEFGH123456")).toBe("rpartstore"); // Dacia
});
it("routes Fiat (and everything else) to the ePER window", () => {
expect(selectVinpinWarmWindow("NM435600006H43436")).toBe("fiat"); // Tofaş Egea
expect(selectVinpinWarmWindow("WVWZZZ1JZ3W597935")).toBe("fiat"); // VW → fiat default
});
});
describe("orderTaskbarWindows — OCR-order taskbar binding", () => {
it("returns the windows in their left→right OCR order", () => {
const bar = "VinPower Fiat Dealer ePER Renault RPartStore Renault Dialogys";
expect(orderTaskbarWindows(bar)).toEqual(["fiat", "rpartstore", "dialogys"]);
});
it("respects a different open order (order is read, not hardcoded)", () => {
const bar = "Dialogys | RPartStore | ePER";
expect(orderTaskbarWindows(bar)).toEqual(["dialogys", "rpartstore", "fiat"]);
});
it("omits windows whose label isn't on the bar", () => {
const bar = "some noise ePER more noise RPartStore";
expect(orderTaskbarWindows(bar)).toEqual(["fiat", "rpartstore"]);
expect(orderTaskbarWindows("nothing recognizable")).toEqual([]);
});
});
describe("isVinpinBusinessHours — 08:00–21:00 Europe/Istanbul (UTC+3, no DST)", () => {
it("is true from 08:00 up to (not including) 21:00 local", () => {
expect(isVinpinBusinessHours(new Date("2026-07-14T05:00:00Z"))).toBe(true); // 08:00
expect(isVinpinBusinessHours(new Date("2026-07-14T12:00:00Z"))).toBe(true); // 15:00
expect(isVinpinBusinessHours(new Date("2026-07-14T17:59:00Z"))).toBe(true); // 20:59
});
it("is false before 08:00 and at/after 21:00 local", () => {
expect(isVinpinBusinessHours(new Date("2026-07-14T04:59:00Z"))).toBe(false); // 07:59
expect(isVinpinBusinessHours(new Date("2026-07-14T18:00:00Z"))).toBe(false); // 21:00
expect(isVinpinBusinessHours(new Date("2026-07-14T22:00:00Z"))).toBe(false); // 01:00
});
});

View File

@@ -17,17 +17,30 @@ function makeDb(limitResults: unknown[][]) {
} }
function makeDeps(opts: { waiting: number; limitResults: unknown[][] }) { function makeDeps(opts: { waiting: number; limitResults: unknown[][] }) {
const queue = { // A queue double: getJob returns null (nothing deduped) and the ioredis client
// stub answers the delayed-ZSET zcount the pressure gate takes.
const makeQueue = (name: string, waiting: number) => ({
name,
// typed args so `.mock.calls[i]` is `unknown[]` (not a 0-length tuple) — the // typed args so `.mock.calls[i]` is `unknown[]` (not a 0-length tuple) — the
// production `nest build` compiles spec files and rejects tuple-index access. // production `nest build` compiles spec files and rejects tuple-index access.
add: vi.fn((..._args: unknown[]) => Promise.resolve(undefined)), add: vi.fn((..._args: unknown[]) => Promise.resolve(undefined)),
getJobCounts: vi.fn(async () => ({ waiting: opts.waiting, delayed: 0, active: 0 })), getJob: vi.fn(async (..._args: unknown[]): Promise<unknown> => null),
}; getJobCounts: vi.fn(async (..._args: unknown[]) => ({
waiting,
delayed: 0,
active: 0,
prioritized: 0,
})),
toKey: (t: string) => `bull:${name}:${t}`,
client: Promise.resolve({ zcount: vi.fn(async (..._args: unknown[]) => 0) }),
});
const queue = makeQueue("catalog-prefetch", opts.waiting);
const redis = { const redis = {
// typed args (like queue.add) so mockImplementation((k)=>…) type-checks under // typed args (like queue.add) so mockImplementation((k)=>…) type-checks under
// the production nest build, which compiles spec files. // the production nest build, which compiles spec files.
exists: vi.fn(async (..._args: unknown[]) => false), // no cooldown / guard / complete marker exists: vi.fn(async (..._args: unknown[]) => false), // no cooldown / guard / complete marker
get: vi.fn(async () => null), // no no-result residue // null → no no-result residue AND daily budget counters read as 0 (unspent).
get: vi.fn(async (..._args: unknown[]): Promise<string | null> => null),
set: vi.fn(async (..._args: unknown[]) => undefined), set: vi.fn(async (..._args: unknown[]) => undefined),
del: vi.fn(async (..._args: unknown[]) => undefined), del: vi.fn(async (..._args: unknown[]) => undefined),
incr: vi.fn(async (..._args: unknown[]) => 1), // per-source rate window counter incr: vi.fn(async (..._args: unknown[]) => 1), // per-source rate window counter
@@ -39,7 +52,7 @@ function makeDeps(opts: { waiting: number; limitResults: unknown[][] }) {
}; };
const posthog = { payload: vi.fn(async () => ({})) }; // compiled-in defaults const posthog = { payload: vi.fn(async () => ({})) }; // compiled-in defaults
const db = makeDb(opts.limitResults); const db = makeDb(opts.limitResults);
const fastQueue = { add: vi.fn(async (..._args: unknown[]) => ({ id: "fastjob" })) }; const fastQueue = makeQueue("catalog-prefetch-fast", 0);
const service = new PrefetchWorkerService( const service = new PrefetchWorkerService(
queue as never, queue as never,
fastQueue as never, fastQueue as never,
@@ -238,11 +251,10 @@ describe("PrefetchWorkerService — fast lane (lifo) + backlog gating", () => {
describe("poison guard (Faz 6: category cap — brand-agnostic anti-explosion)", () => { describe("poison guard (Faz 6: category cap — brand-agnostic anti-explosion)", () => {
type PC = { processChildren: (j: unknown) => Promise<void> }; type PC = { processChildren: (j: unknown) => Promise<void> };
it("processChildren marks poison once progress.total exceeds CATEGORY_CAP", async () => { it("processChildren marks poison once the STORED tree exceeds CATEGORY_CAP", async () => {
const { service, queue, redis } = makeDeps({ waiting: 0, limitResults: [] }); // The cap is now measured from the DB (categories count), not the ephemeral
redis.getJson.mockImplementation(async (...a: unknown[]) => // progress.total which every processInit resets to 0.
String(a[0]).includes("progress") ? { total: 5000 } : null, const { service, queue, redis } = makeDeps({ waiting: 0, limitResults: [[{ n: 5000 }]] });
);
await (service as never as PC).processChildren({ await (service as never as PC).processChildren({
data: { vehicleId: "op1", categoryId: "c1", source: "pl24", depth: 1 }, data: { vehicleId: "op1", categoryId: "c1", source: "pl24", depth: 1 },
} as never); } as never);

View File

@@ -53,8 +53,51 @@ const MAX_DEPTH = Number(process.env.PREFETCH_MAX_DEPTH) || 12;
const BACKFILL_BATCH_SIZE = 40; const BACKFILL_BATCH_SIZE = 40;
/** Skip the wave entirely if the queue already has more than this many jobs pending. */ /** Skip the wave entirely if the queue already has more than this many jobs pending. */
const BACKFILL_MAX_BACKLOG = 1000; const BACKFILL_MAX_BACKLOG = 1000;
/** In-flight guard TTL (seconds) — safety net if a run dies without clearing. */ /**
const BACKFILL_SCHEDULED_TTL = 6 * 60 * 60; * In-flight guard TTL (seconds) — safety net if a run dies without clearing.
*
* 36h, NOT 6h: a chain deferred on the daily budget lives until the next UTC
* midnight (~24h). With a 6h TTL the guard expired mid-chain, the scan re-picked
* the vehicle, processInit reset progress.total, and the in-flight jobs'
* incrementCompleted then compared `completed >= total` against the NEW total —
* corrupting completion accounting for a still-partial vehicle.
*/
const BACKFILL_SCHEDULED_TTL = Number(process.env.PREFETCH_SCHEDULED_TTL_H || 36) * 60 * 60;
/**
* Only delayed jobs due within this horizon count as queue PRESSURE.
*
* `delayed` lumps two very different things together: per-minute source-rate
* defers (<60s) and retry backoff (30/60s), which ARE load, versus daily-budget
* and off-hours defers (hours, parked on the next UTC midnight), which are merely
* THROTTLED FUTURE WORK. Counting the latter as backlog froze Phase-2 for most of
* the day (2026-08-01: delayed=11495, all pcat, all parked at 00:00:01 UTC; the
* partial drain fell to ~25 vehicles/day, ETA 79 days).
*/
const PRESSURE_HORIZON_MS = Number(process.env.PREFETCH_PRESSURE_HORIZON_MS) || 10 * 60_000;
/**
* Absolute ceiling on TOTAL pending jobs (waiting+active+delayed+prioritized)
* across BOTH lanes — the runaway backstop that `delayed` used to provide by
* accident. Excluding long defers from the pressure gate removes the only
* negative feedback on production, so the pool needs its own hard stop: Phase-2
* can otherwise produce ~288k jobs/day against ~65k/day of budget. 50k ≈ 15h of
* the combined daily budgets, so the pool always drains inside a window; 1/9 of
* the guard-less BFS runaway (470k, months to drain). Set 0 to disable Phase-2.
*/
const HARD_MAX_TOTAL_JOBS = Number(process.env.PREFETCH_MAX_TOTAL_JOBS ?? 50_000);
/**
* Rough fan-out of one Phase-2 re-drill. Admission control is done in JOB units,
* not vehicle units: 40 vehicles/wave is meaningless when one vehicle is 100-3000
* jobs (p95 tree = 744 categories).
*/
const EST_JOBS_PER_VEHICLE = Number(process.env.PREFETCH_EST_JOBS_PER_VEHICLE) || 400;
/**
* Share of each source's daily budget reserved for the FAST lane. The daily
* counter has no lane component, so backfill spending the budget also parked the
* user's fresh-decode chain until midnight. One shared counter (the total
* upstream/bandwidth ceiling stays exactly SOURCE_DAILY_MAX) but two thresholds:
* the main (backfill) lane stops at 80%, the fast lane may use 100%.
*/
const DAILY_FAST_RESERVE = 0.2;
/** Only these decode sources have catalogs worth prefetching. */ /** Only these decode sources have catalogs worth prefetching. */
const BACKFILL_SOURCES = ["pl24", "emex", "parts-catalogs"]; const BACKFILL_SOURCES = ["pl24", "emex", "parts-catalogs"];
/** Redis key holding the rolling rescan cursor (last createdAt seen). */ /** Redis key holding the rolling rescan cursor (last createdAt seen). */
@@ -98,6 +141,29 @@ const SOURCE_RATE_MAX: Record<string, number> = {
// (2026-07-08: 93k backlog %89 pcat idi — 20/min + 5s pace drenaja yetmiyordu). // (2026-07-08: 93k backlog %89 pcat idi — 20/min + 5s pace drenaja yetmiyordu).
"parts-catalogs": Number(process.env.PREFETCH_RATE_PCAT) || 90, "parts-catalogs": Number(process.env.PREFETCH_RATE_PCAT) || 90,
}; };
/**
* Per-source ROLLING-DAY budget (backfill jobs/source/UTC-day). A storm guard on
* top of the per-minute ceilings: those cap burst rate but not the daily TOTAL,
* so a source running near its ceiling for many hours drains the proxy budget
* (2026-07-09: a backlog drain pushed pcat to ~74k calls / ~10 GB in one day).
* When a source hits its daily budget, further backfill jobs defer until the
* window rolls. User-facing decodes are unaffected — they don't pass through the
* worker. Only counts jobs that already cleared the per-minute gate, so
* rate-limited retries don't inflate it. 0 = unlimited. Env-tunable: raise to
* drain a backlog faster, lower to conserve proxy budget harder.
*/
const SOURCE_DAILY_MAX: Record<string, number> = {
pl24: Number(process.env.PREFETCH_DAILY_PL24) || 15_000,
emex: Number(process.env.PREFETCH_DAILY_EMEX) || 20_000,
// 45k (1.5x): the 2026-07-09 incident that created this guard was ~74k calls /
// ~10 GB in a day, so 45k ≈ 61% of that — a reversible step at ~6 GB/day. With
// DAILY_FAST_RESERVE the backfill (main) lane gets 36k, i.e. +20% over the old
// effective 30k while still leaving 9k for user decodes. Burst rate is
// UNCHANGED (SOURCE_RATE_MAX pcat 90/min), so per-IP ban pressure is the same —
// this only sustains that pace for more of the day. Rollback signal: any hour
// with >2 pcat HTTP 402 (DataImpulse quota) → back to 30_000.
"parts-catalogs": Number(process.env.PREFETCH_DAILY_PCAT) || 45_000,
};
/** /**
* Per-job pacing for parts-catalogs only (its browser/JWT capture is heavy). * Per-job pacing for parts-catalogs only (its browser/JWT capture is heavy).
* Set 0 to disable. Other sources are paced by the limiter + cooldown alone. * Set 0 to disable. Other sources are paced by the limiter + cooldown alone.
@@ -196,7 +262,7 @@ export class PrefetchWorkerService implements OnModuleInit, OnModuleDestroy {
this.logger.log( this.logger.log(
`[prefetch] Worker started (concurrency=${WORKER_CONCURRENCY}, global ${WORKER_RATE_MAX}/min, ` + `[prefetch] Worker started (concurrency=${WORKER_CONCURRENCY}, global ${WORKER_RATE_MAX}/min, ` +
`per-source ${JSON.stringify(SOURCE_RATE_MAX)}, pcatPace=${PCAT_PACE_MS}ms)`, `per-source ${JSON.stringify(SOURCE_RATE_MAX)}, daily ${JSON.stringify(SOURCE_DAILY_MAX)}, pcatPace=${PCAT_PACE_MS}ms)`,
); );
// Hourly backfill scan — run IN-PROCESS, not as a BullMQ cron job. A cron // Hourly backfill scan — run IN-PROCESS, not as a BullMQ cron job. A cron
@@ -252,10 +318,14 @@ export class PrefetchWorkerService implements OnModuleInit, OnModuleDestroy {
job.name === "prefetch-children" || job.name === "prefetch-children" ||
job.name === "prefetch-parts") job.name === "prefetch-parts")
) { ) {
await this.checkSourceRate( const lane = (job.data as { fast?: boolean }).fast ? "fast" : "main";
data.source, await this.checkSourceRate(data.source, lane);
(job.data as { fast?: boolean }).fast ? "fast" : "main", // Daily budget AFTER the per-minute gate: a job deferred on the minute
); // ceiling above never reaches here, so rate-limited retries don't inflate
// the daily counter — only jobs about to do real work are counted. The
// lane decides which threshold applies (backfill stops at the main limit,
// the user's fast lane may use the full budget).
await this.checkSourceDailyBudget(data.source, lane);
} }
if (data.source === "parts-catalogs" && PCAT_PACE_MS > 0) { if (data.source === "parts-catalogs" && PCAT_PACE_MS > 0) {
await new Promise((r) => setTimeout(r, PCAT_PACE_MS)); await new Promise((r) => setTimeout(r, PCAT_PACE_MS));
@@ -387,8 +457,9 @@ export class PrefetchWorkerService implements OnModuleInit, OnModuleDestroy {
for (const child of children) { for (const child of children) {
if (child.unavailable) continue; if (child.unavailable) continue;
await this.queueCategoryJob(child, vehicleId, source, 1, fast); // Count jobs ACTUALLY queued, not nodes walked — see addJob's doc: an
queued++; // inflated progress.total makes the chain never reach "finished".
queued += await this.queueCategoryJob(child, vehicleId, source, 1, fast);
} }
} else if (this.isLeafLinkPath(cat.linkPath, cat.source, cat.hasSubgroups)) { } else if (this.isLeafLinkPath(cat.linkPath, cat.source, cat.hasSubgroups)) {
// Leaf — check if parts already fetched // Leaf — check if parts already fetched
@@ -398,32 +469,46 @@ export class PrefetchWorkerService implements OnModuleInit, OnModuleDestroy {
.where(eq(parts.categoryId, cat.id)) .where(eq(parts.categoryId, cat.id))
.limit(1); .limit(1);
if (!partCheck && cat.linkPath) { if (
await this.addJob("prefetch-parts", { !partCheck &&
cat.linkPath &&
(await this.addJob("prefetch-parts", {
vehicleId, vehicleId,
categoryId: cat.id, categoryId: cat.id,
source, source,
action: "parts" as const, action: "parts" as const,
depth: 0, depth: 0,
fast, fast,
}); }))
) {
queued++; queued++;
} }
} else if (cat.linkPath) { } else if (
cat.linkPath &&
// Non-leaf without children — needs children fetch // Non-leaf without children — needs children fetch
await this.addJob("prefetch-children", { (await this.addJob("prefetch-children", {
vehicleId, vehicleId,
categoryId: cat.id, categoryId: cat.id,
source, source,
action: "children" as const, action: "children" as const,
depth: 0, depth: 0,
fast, fast,
}); }))
) {
queued++; queued++;
} }
} }
await updateProgress(this.redis, vehicleId, { total: queued }); await updateProgress(this.redis, vehicleId, { total: queued });
if (queued === 0) {
// Nothing left to fetch — the tree is already complete in DB. Without this
// there is no job to fire incrementCompleted, so progress sits at {0,0}, the
// vehicle is never marked fullyFetched, and the scan re-picks it every wave
// forever while burning a daily-budget slot each time.
this.logger.log(`[prefetch] Nothing to queue for vehicle=${vehicleId} — already complete`);
await this.finalizeVehicle(vehicleId);
return;
}
this.logger.log(`[prefetch] Queued ${queued} sub-jobs for vehicle=${vehicleId}`); this.logger.log(`[prefetch] Queued ${queued} sub-jobs for vehicle=${vehicleId}`);
} }
@@ -442,14 +527,19 @@ export class PrefetchWorkerService implements OnModuleInit, OnModuleDestroy {
return; return;
} }
// Anti-poison cap: progress.total tracks every sub-job queued for this vehicle // Anti-poison cap measured from the DB, NOT from progress.total: the ephemeral
// (≈ its discovered tree size). Once it blows past the ceiling the vehicle is a // counter is reset to 0 by every processInit, so a re-picked vehicle could
// generic-catalog explosion — stop drilling and mark it poison so the rest of // drill another CATEGORY_CAP nodes per round and never trip the guard (the
// its (part-less) tree is never fetched and it's never re-picked. // generic-ROOT Opels: 420k/102k/21k categories, ZERO parts). The stored tree
const prog = await this.redis.getJson<{ total: number }>(`prefetch:progress:${vehicleId}`); // is the real, cumulative size.
if ((prog?.total ?? 0) >= CATEGORY_CAP) { const [capRow] = await this.db
.select({ n: sql<number>`count(*)::int` })
.from(categories)
.where(eq(categories.vehicleId, vehicleId))
.limit(1);
if ((capRow?.n ?? 0) >= CATEGORY_CAP) {
this.logger.warn( this.logger.warn(
`[prefetch] Category cap ${CATEGORY_CAP} hit for vehicle=${vehicleId} (tree≈${prog?.total}) — marking poison, stop drilling`, `[prefetch] Category cap ${CATEGORY_CAP} hit for vehicle=${vehicleId} (tree=${capRow?.n}) — marking poison, stop drilling`,
); );
await this.markPoison(vehicleId); await this.markPoison(vehicleId);
return; return;
@@ -461,8 +551,9 @@ export class PrefetchWorkerService implements OnModuleInit, OnModuleDestroy {
let queued = 0; let queued = 0;
for (const child of children) { for (const child of children) {
if (child.unavailable) continue; if (child.unavailable) continue;
await this.queueCategoryJob(child, vehicleId, source, depth + 1, fast); // Real queued-job count (see addJob) — walking a node that dedupes or
queued++; // already has parts must not inflate progress.total.
queued += await this.queueCategoryJob(child, vehicleId, source, depth + 1, fast);
} }
if (queued > 0) { if (queued > 0) {
@@ -541,19 +632,57 @@ export class PrefetchWorkerService implements OnModuleInit, OnModuleDestroy {
// genuinely-empty vehicles keep getting onboarded through the fast lane even // genuinely-empty vehicles keep getting onboarded through the fast lane even
// while a large deep-drill backlog is still draining — otherwise a single // while a large deep-drill backlog is still draining — otherwise a single
// backlog spike freezes new-vehicle coverage until the whole queue clears. // backlog spike freezes new-vehicle coverage until the whole queue clears.
const counts = await this.queue.getJobCounts("waiting", "delayed", "active"); // Two INDEPENDENT ceilings (Phase-1 fast lane is never gated, so genuinely
const backlog = (counts.waiting ?? 0) + (counts.delayed ?? 0) + (counts.active ?? 0); // empty vehicles keep getting onboarded):
const phase2Allowed = backlog <= maxBacklog; // 1. pressure = waiting + active + delayed-due-within-PRESSURE_HORIZON_MS,
// both lanes, vs maxBacklog — "are the workers actually swamped?".
// Budget/off-hours defers are parked hours out and no longer count, so a
// spent daily budget stops freezing Phase-2 for the rest of the day.
// 2. total = every pending job, both lanes, vs HARD_MAX_TOTAL_JOBS — the
// runaway backstop that `delayed` used to provide by accident.
const depth = await this.getQueueDepth();
const headroom = Math.max(0, HARD_MAX_TOTAL_JOBS - depth.total);
// Admission control in JOB units: one wave fans out to batchSize * ~400 jobs
// long before the next hourly scan can react, so shrink the wave as the pool
// fills instead of stepping over the cap by a whole batch.
const phase2Budget = Math.min(batchSize, Math.floor(headroom / EST_JOBS_PER_VEHICLE));
const phase2Allowed = depth.pressure <= maxBacklog && phase2Budget > 0;
if (!phase2Allowed) { if (!phase2Allowed) {
this.logger.log(`[backfill] Backlog ${backlog} > ${maxBacklog} — Phase-1 (fast lane) only`); this.logger.log(
`[backfill] Phase-1 (fast lane) only — pressure=${depth.pressure}/${maxBacklog}, ` +
`total=${depth.total}/${HARD_MAX_TOTAL_JOBS} (delayed=${depth.delayed}, imminent=${depth.imminent})`,
);
}
if (HARD_MAX_TOTAL_JOBS > 0 && depth.total > HARD_MAX_TOTAL_JOBS * 1.5) {
// Should be unreachable — admission control caps intake once per hour. If it
// fires, real fan-out is far above EST_JOBS_PER_VEHICLE.
this.logger.error(
`[backfill] Queue pool ${depth.total} > 1.5x hard cap ${HARD_MAX_TOTAL_JOBS} — investigate fan-out`,
);
} }
// Only target sources eligible right now: not in cooldown (user active) and // Only target sources eligible right now: not in cooldown (user active),
// inside their scrape window (PL24/parts-catalogs office hours; EMEX always). // inside their scrape window, AND still inside today's main-lane budget.
// The budget check is THE key guard: deferring at job level only MOVES work
// into `delayed`, it does not stop PRODUCING it — and budget defers never
// exhaust attempts (moveToDelayed skipAttempt), so nothing drops them. Once a
// source's main-lane budget is spent the scan must stop feeding it for the
// rest of the UTC day; feeding a throttled source is exactly how the 470k
// runaway was built. This also preserves the fast-lane reserve for real users.
const eligible: string[] = []; const eligible: string[] = [];
for (const s of BACKFILL_SOURCES) { for (const s of BACKFILL_SOURCES) {
if (await this.redis.exists(`prefetch:activity:${s}`)) continue; if (await this.redis.exists(`prefetch:activity:${s}`)) continue;
if (cfg.businessHoursOnly !== false && !isWithinTimeWindow(s)) continue; if (cfg.businessHoursOnly !== false && !isWithinTimeWindow(s)) continue;
const mainLimit = this.dailyMainLimit(s);
if (mainLimit > 0) {
const spent = Number((await this.redis.get(this.dailyKey(s))) ?? 0);
if (spent >= mainLimit) {
this.logger.log(
`[backfill] ${s} daily budget spent (${spent}/${mainLimit}) — source skipped this wave`,
);
continue;
}
}
eligible.push(s); eligible.push(s);
} }
if (eligible.length === 0) { if (eligible.length === 0) {
@@ -568,9 +697,17 @@ export class PrefetchWorkerService implements OnModuleInit, OnModuleDestroy {
const tryPick = async ( const tryPick = async (
v: { id: string; source: string | null }, v: { id: string; source: string | null },
fast: boolean, fast: boolean,
limit: number = batchSize,
): Promise<void> => { ): Promise<void> => {
if (picked.length >= batchSize || seen.has(v.id) || !v.source) return; if (picked.length >= limit || seen.has(v.id) || !v.source) return;
if (await this.redis.exists(`prefetch:scheduled:${v.id}`)) return; // already in flight // TWO different in-flight guards, both must be clear:
// - prefetch:scheduled:backfill:<id> — ours (36h, covers a budget-parked chain)
// - prefetch:scheduled:<id> — the USER decode path's (vehicles.service.ts
// schedulePrefetch, short TTL). We deliberately stopped WRITING the bare
// key: our long TTL made schedulePrefetch() silently skip the user's
// fresh-decode fast-lane init.
if (await this.redis.exists(this.scheduledKey(v.id))) return;
if (await this.redis.exists(`prefetch:scheduled:${v.id}`)) return; // user chain in flight
// Skip exhausted residue: vehicles whose prefetch keeps finishing with zero // Skip exhausted residue: vehicles whose prefetch keeps finishing with zero
// parts (no catalog data). They'd otherwise be re-picked every wave forever. // parts (no catalog data). They'd otherwise be re-picked every wave forever.
const noResult = await this.redis.get(this.noResultKey(v.id)); const noResult = await this.redis.get(this.noResultKey(v.id));
@@ -603,17 +740,27 @@ export class PrefetchWorkerService implements OnModuleInit, OnModuleDestroy {
for (const v of noParts) await tryPick(v, true); for (const v of noParts) await tryPick(v, true);
// Phase 2 — rolling rescan of ALL decoded vehicles to gap-fill partially-fetched // Phase 2 — rolling rescan of vehicles that are NOT fully fetched, to gap-fill
// ones. A createdAt cursor walks forward and wraps around at the end. Gated by // partials. Targets the DURABLE `fullyFetched` flag (indexed) instead of
// the backlog ceiling (above) so it doesn't pile on while the queue is deep. // walking the whole fleet and relying only on the ephemeral 21-day
if (phase2Allowed && picked.length < batchSize) { // `prefetch:complete:` marker — a Redis flush would otherwise re-drill every
// vehicle at once. The fullyFetchedAt clause keeps the periodic re-validation
// the TTL used to provide. Gated by the ceilings above + a JOB-unit budget.
const phase2Limit = Math.min(batchSize, picked.length + phase2Budget);
if (phase2Allowed && picked.length < phase2Limit) {
const cursorObj = await this.redis.getJson<{ ts: string }>(BACKFILL_CURSOR_KEY); const cursorObj = await this.redis.getJson<{ ts: string }>(BACKFILL_CURSOR_KEY);
const cursor = cursorObj?.ts ? new Date(cursorObj.ts) : new Date(0); const cursor = cursorObj?.ts ? new Date(cursorObj.ts) : new Date(0);
const rolling = await this.db const rolling = await this.db
.select({ id: vehicles.id, source: vehicles.source, createdAt: vehicles.createdAt }) .select({ id: vehicles.id, source: vehicles.source, createdAt: vehicles.createdAt })
.from(vehicles) .from(vehicles)
.where(and(inArray(vehicles.source, eligible), gt(vehicles.createdAt, cursor))) .where(
and(
inArray(vehicles.source, eligible),
gt(vehicles.createdAt, cursor),
sql`(${vehicles.fullyFetched} = false OR ${vehicles.fullyFetchedAt} < now() - interval '21 days')`,
),
)
.orderBy(asc(vehicles.createdAt)) .orderBy(asc(vehicles.createdAt))
.limit(overfetch); .limit(overfetch);
@@ -629,7 +776,7 @@ export class PrefetchWorkerService implements OnModuleInit, OnModuleDestroy {
let lastTs: Date | null = null; let lastTs: Date | null = null;
for (const v of rolling) { for (const v of rolling) {
lastTs = v.createdAt; lastTs = v.createdAt;
await tryPick(v, false); await tryPick(v, false, phase2Limit);
} }
if (lastTs) { if (lastTs) {
await this.redis.setJson(BACKFILL_CURSOR_KEY, { ts: lastTs.toISOString() }, 30 * 86400); await this.redis.setJson(BACKFILL_CURSOR_KEY, { ts: lastTs.toISOString() }, 30 * 86400);
@@ -645,7 +792,8 @@ export class PrefetchWorkerService implements OnModuleInit, OnModuleDestroy {
const fastCount = picked.filter((v) => v.fast).length; const fastCount = picked.filter((v) => v.fast).length;
this.logger.log( this.logger.log(
`[backfill] Queued ${picked.length} vehicle(s) (${fastCount} fast-lane, ` + `[backfill] Queued ${picked.length} vehicle(s) (${fastCount} fast-lane, ` +
`sources=${eligible.join(",")}, backlog=${backlog})`, `sources=${eligible.join(",")}, pressure=${depth.pressure}, total=${depth.total}, ` +
`phase2Budget=${phase2Budget})`,
); );
} }
@@ -664,7 +812,7 @@ export class PrefetchWorkerService implements OnModuleInit, OnModuleDestroy {
}, },
); );
// Guard cleared on completion (incrementCompleted) or by TTL if the run dies. // Guard cleared on completion (incrementCompleted) or by TTL if the run dies.
await this.redis.set(`prefetch:scheduled:${vehicleId}`, "1", BACKFILL_SCHEDULED_TTL); await this.redis.set(this.scheduledKey(vehicleId), "1", BACKFILL_SCHEDULED_TTL);
} }
// ==================== Helpers ==================== // ==================== Helpers ====================
@@ -681,8 +829,8 @@ export class PrefetchWorkerService implements OnModuleInit, OnModuleDestroy {
source: string, source: string,
depth: number, depth: number,
fast = false, fast = false,
): Promise<void> { ): Promise<number> {
if (cat.unavailable) return; if (cat.unavailable) return 0;
if (this.isLeafLinkPath(cat.linkPath, cat.source, cat.hasSubgroups)) { if (this.isLeafLinkPath(cat.linkPath, cat.source, cat.hasSubgroups)) {
// Leaf — check if already has parts // Leaf — check if already has parts
@@ -693,16 +841,20 @@ export class PrefetchWorkerService implements OnModuleInit, OnModuleDestroy {
.limit(1); .limit(1);
if (!partCheck && cat.linkPath) { if (!partCheck && cat.linkPath) {
await this.addJob("prefetch-parts", { return (await this.addJob("prefetch-parts", {
vehicleId, vehicleId,
categoryId: cat.id, categoryId: cat.id,
source: source as "pl24" | "emex", source: source as "pl24" | "emex",
action: "parts" as const, action: "parts" as const,
depth, depth,
fast, fast,
}); }))
? 1
: 0;
} }
} else if (cat.linkPath && depth < MAX_DEPTH) { return 0;
}
if (cat.linkPath && depth < MAX_DEPTH) {
// Non-leaf within the depth cap — explore children. The `depth < MAX_DEPTH` // Non-leaf within the depth cap — explore children. The `depth < MAX_DEPTH`
// gate mirrors processChildren's early-return: without it we'd enqueue a // gate mirrors processChildren's early-return: without it we'd enqueue a
// prefetch-children job that processChildren just drops, burning a rate-limit // prefetch-children job that processChildren just drops, burning a rate-limit
@@ -720,21 +872,25 @@ export class PrefetchWorkerService implements OnModuleInit, OnModuleDestroy {
.from(categories) .from(categories)
.where(eq(categories.parentId, cat.id)); .where(eq(categories.parentId, cat.id));
let n = 0;
for (const child of children) { for (const child of children) {
if (child.unavailable) continue; if (child.unavailable) continue;
await this.queueCategoryJob(child, vehicleId, source, depth + 1, fast); n += await this.queueCategoryJob(child, vehicleId, source, depth + 1, fast);
} }
} else { return n;
await this.addJob("prefetch-children", {
vehicleId,
categoryId: cat.id,
source: source as "pl24" | "emex",
action: "children" as const,
depth,
fast,
});
} }
return (await this.addJob("prefetch-children", {
vehicleId,
categoryId: cat.id,
source: source as "pl24" | "emex",
action: "children" as const,
depth,
fast,
}))
? 1
: 0;
} }
return 0;
} }
private isLeafLinkPath( private isLeafLinkPath(
@@ -765,12 +921,25 @@ export class PrefetchWorkerService implements OnModuleInit, OnModuleDestroy {
); );
} }
private async addJob(name: string, data: PrefetchCategoryJobData): Promise<void> { /**
* Queue one sub-job. Returns whether a NEW job was actually created.
*
* The return value is the fix for a completion-accounting bug: `progress.total`
* is the chain's denominator (incrementCompleted fires "finished" at
* `completed >= total`), but callers used to increment it for every node they
* WALKED — including nodes where this deterministic jobId deduped the add, and
* leaves that already had parts. An inflated total means the chain never
* reaches "finished", so the vehicle is never marked fullyFetched and the scan
* re-picks it every wave forever (the ~25 vehicles/day plateau). Queue
* behaviour is UNCHANGED — BullMQ already no-op'd a duplicate jobId.
*/
private async addJob(name: string, data: PrefetchCategoryJobData): Promise<boolean> {
// BullMQ rejects custom job IDs containing ":" (its key separator), so use
// "-" instead. The values are UUIDs — the ID only needs to be deterministic
// (for dedup), not parseable.
const jobId = `prefetch-${data.vehicleId}-${data.categoryId}-${data.action}`;
const opts: Record<string, unknown> = { const opts: Record<string, unknown> = {
// BullMQ rejects custom job IDs containing ":" (its key separator), so use jobId,
// "-" instead. The values are UUIDs — the ID only needs to be deterministic
// (for dedup), not parseable.
jobId: `prefetch-${data.vehicleId}-${data.categoryId}-${data.action}`,
// Fast lane (Phase-1 / reactive): add with `lifo` so the job RPUSHes to the // Fast lane (Phase-1 / reactive): add with `lifo` so the job RPUSHes to the
// TAIL of the wait list, where BullMQ's RPOPLPUSH picks it next — i.e. ahead // TAIL of the wait list, where BullMQ's RPOPLPUSH picks it next — i.e. ahead
// of the deep deep-drill backlog already sitting in wait. (BullMQ 5 drains // of the deep deep-drill backlog already sitting in wait. (BullMQ 5 drains
@@ -778,16 +947,15 @@ export class PrefetchWorkerService implements OnModuleInit, OnModuleDestroy {
// OPPOSITE here and starve the job behind the backlog; lifo is correct.) // OPPOSITE here and starve the job behind the backlog; lifo is correct.)
...(data.fast ? { lifo: true } : {}), ...(data.fast ? { lifo: true } : {}),
}; };
if (data.fast) { const q = data.fast ? this.fastQueue : this.queue;
await this.fastQueue.add(name, data, opts); if (await q.getJob(jobId)) return false;
return;
}
// parts-catalogs pacing is handled per-job in process() (PCAT_PACE_MS) + the // parts-catalogs pacing is handled per-job in process() (PCAT_PACE_MS) + the
// limiter. The old cumulative `index * 20s` delay was pathological (the Nth // limiter. The old cumulative `index * 20s` delay was pathological (the Nth
// leaf of a vehicle waited N*20s) and is gone. // leaf of a vehicle waited N*20s) and is gone.
await this.queue.add(name, data, opts); await q.add(name, data, opts);
return true;
} }
private async incrementCompleted(vehicleId: string): Promise<void> { private async incrementCompleted(vehicleId: string): Promise<void> {
@@ -807,29 +975,47 @@ export class PrefetchWorkerService implements OnModuleInit, OnModuleDestroy {
if (isFinished) { if (isFinished) {
this.logger.log(`[prefetch] Completed all jobs for vehicle=${vehicleId}`); this.logger.log(`[prefetch] Completed all jobs for vehicle=${vehicleId}`);
// Genuine residue: the whole chain finished but the vehicle still has no await this.finalizeVehicle(vehicleId);
// parts (all leaves empty / no catalog data). Count it so Phase-1 stops
// re-picking it every wave.
const [hasPart] = await this.db
.select({ id: parts.id })
.from(parts)
.where(eq(parts.vehicleId, vehicleId))
.limit(1);
if (hasPart) {
// Fully fetched with parts → mark complete so the Phase-2 rescan skips it
// (re-validates after the TTL). A chain with any failed job never reaches
// isFinished, so partially-fetched vehicles are never marked — they keep
// getting gap-filled.
await this.redis.set(this.completeKey(vehicleId), "1", COMPLETE_TTL_S);
} else {
await this.markNoResult(vehicleId);
}
// Clean up Redis keys — data is in PostgreSQL now
await this.redis.del(`prefetch:scheduled:${vehicleId}`);
await this.redis.del(`prefetch:progress:${vehicleId}`);
} }
} }
/**
* Settle a vehicle whose prefetch chain is done: mark it complete (with parts)
* or count it as residue (still zero parts), then clear the run's Redis state.
* Called both when the last sub-job finishes AND when processInit finds there
* is nothing left to queue — otherwise an already-complete tree would never be
* settled and the scan would re-pick it forever.
*/
private async finalizeVehicle(vehicleId: string): Promise<void> {
// Genuine residue: the whole chain finished but the vehicle still has no
// parts (all leaves empty / no catalog data). Count it so Phase-1 stops
// re-picking it every wave.
const [hasPart] = await this.db
.select({ id: parts.id })
.from(parts)
.where(eq(parts.vehicleId, vehicleId))
.limit(1);
if (hasPart) {
// Fully fetched with parts → mark complete so the Phase-2 rescan skips it
// (re-validates after the TTL). A chain with any failed job never reaches
// isFinished, so partially-fetched vehicles are never marked — they keep
// getting gap-filled.
await this.redis.set(this.completeKey(vehicleId), "1", COMPLETE_TTL_S);
// Durable completeness flag (never expires) — the reliable "% fully
// fetched" measurement, independent of the ephemeral Redis marker.
// Re-set on every re-drill completion so fullyFetchedAt tracks last-verified.
await this.db
.update(vehicles)
.set({ fullyFetched: true, fullyFetchedAt: new Date() })
.where(eq(vehicles.id, vehicleId));
} else {
await this.markNoResult(vehicleId);
}
// Clean up Redis keys — data is in PostgreSQL now
await this.redis.del(this.scheduledKey(vehicleId));
await this.redis.del(`prefetch:progress:${vehicleId}`);
}
private async incrementErrors(vehicleId: string): Promise<void> { private async incrementErrors(vehicleId: string): Promise<void> {
const progress = await this.redis.getJson<{ errors: number }>(`prefetch:progress:${vehicleId}`); const progress = await this.redis.getJson<{ errors: number }>(`prefetch:progress:${vehicleId}`);
if (!progress) return; if (!progress) return;
@@ -842,6 +1028,62 @@ export class PrefetchWorkerService implements OnModuleInit, OnModuleDestroy {
return `prefetch:noresult:${vehicleId}`; return `prefetch:noresult:${vehicleId}`;
} }
/**
* Backfill's own in-flight guard — namespaced so it can't shadow the user
* decode path's `prefetch:scheduled:<id>` (vehicles.service.ts reads that key
* and skips the fresh-decode fast-lane init while it is set).
*/
private scheduledKey(vehicleId: string): string {
return `prefetch:scheduled:backfill:${vehicleId}`;
}
/**
* Queue depth across BOTH lanes, split into "pressure" (work the workers will
* pick up within PRESSURE_HORIZON_MS) and "total" (everything pending).
*
* BullMQ stores delayed jobs in a ZSET scored `dueMs * 0x1000 + seq` (12-bit
* collision counter — addDelayedJob / moveToDelayed lua), so "due within X ms"
* is a plain ZCOUNT with the bound encoded the same way. RedisService exposes
* no zcount, so we borrow each queue's OWN ioredis connection and its toKey()
* rather than hand-building `bull:<name>:delayed`.
*/
private async getQueueDepth(): Promise<{
pressure: number;
total: number;
imminent: number;
delayed: number;
}> {
// String bound so ioredis can't render it in exponent notation.
const maxScore = String((Date.now() + PRESSURE_HORIZON_MS + 1) * 0x1000 - 1);
let pressure = 0;
let total = 0;
let imminent = 0;
let delayed = 0;
for (const q of [this.queue, this.fastQueue]) {
const c = await q.getJobCounts("waiting", "active", "delayed", "prioritized");
const live = (c.waiting ?? 0) + (c.active ?? 0);
const d = c.delayed ?? 0;
// Fail CLOSED: if the ZCOUNT can't be taken, count every delayed job as
// pressure — fall back to the old over-conservative gate rather than
// silently unlocking Phase-2 with no visibility. A repeating warn here
// means Phase-2 is suspended again.
let due = d;
try {
const client = await q.client;
due = await client.zcount(q.toKey("delayed"), "-inf", maxScore);
} catch (err) {
this.logger.warn(
`[backfill] delayed zcount failed on ${q.name} (${(err as Error).message}) — counting all delayed as pressure`,
);
}
pressure += live + due;
total += live + d + (c.prioritized ?? 0);
imminent += due;
delayed += d;
}
return { pressure, total, imminent, delayed };
}
private completeKey(vehicleId: string): string { private completeKey(vehicleId: string): string {
return `prefetch:complete:${vehicleId}`; return `prefetch:complete:${vehicleId}`;
} }
@@ -857,7 +1099,7 @@ export class PrefetchWorkerService implements OnModuleInit, OnModuleDestroy {
* (which stay ~200 categories and DO yield parts) are never affected. */ * (which stay ~200 categories and DO yield parts) are never affected. */
private async markPoison(vehicleId: string): Promise<void> { private async markPoison(vehicleId: string): Promise<void> {
await this.redis.set(this.poisonKey(vehicleId), "1", POISON_TTL_S); await this.redis.set(this.poisonKey(vehicleId), "1", POISON_TTL_S);
await this.redis.del(`prefetch:scheduled:${vehicleId}`); await this.redis.del(this.scheduledKey(vehicleId));
await this.redis.del(`prefetch:progress:${vehicleId}`); await this.redis.del(`prefetch:progress:${vehicleId}`);
} }
@@ -886,6 +1128,59 @@ export class PrefetchWorkerService implements OnModuleInit, OnModuleDestroy {
} }
} }
/**
* Per-source rolling-day budget (storm guard). UTC-day fixed window in Redis;
* when the source's daily job count exceeds its ceiling, defer the job until
* the window rolls so a long run can't drain the proxy budget. 0 = unlimited.
*/
private async checkSourceDailyBudget(
source: string,
lane: "main" | "fast" = "main",
): Promise<void> {
const max = SOURCE_DAILY_MAX[source] ?? 0;
if (max <= 0) return;
const limit = lane === "fast" ? max : this.dailyMainLimit(source);
const dayMs = 86_400_000;
const now = Date.now();
const key = this.dailyKey(source, now);
// READ-then-INCR (was INCR-then-check). A REJECTED attempt must not count:
// the old order inflated the counter with every defer (observed 48531 against
// a 30000 budget), which (a) made the number useless for capacity decisions
// and (b) — now that the scan reads the same counter to stop feeding a spent
// source — would let pure defer churn lock the source out. Worst-case
// overshoot under the read/incr race is WORKER_CONCURRENCY jobs: acceptable.
const n = Number((await this.redis.get(key)) ?? 0);
if (n >= limit) {
// Defer to the next UTC day, plus up to 45min of JITTER. Without jitter every
// deferred job wakes in the SAME millisecond (observed: 11495 jobs all at
// 00:00:01 UTC) — the promotion lands as one burst and the pressure signal
// flaps. Other sources keep flowing (per-job defer, not a worker pause).
const msLeft = dayMs - (now % dayMs) + 1000 + Math.floor(Math.random() * 45 * 60_000);
if (n === limit) {
this.logger.warn(
`[prefetch] ${source} daily budget hit (lane=${lane}, ${n}/${limit} of ${max}) — ` +
`deferring ~${Math.round(msLeft / 3_600_000)}h until the window rolls`,
);
}
throw new RateLimitError(msLeft, "source-rate");
}
const after = await this.redis.incr(key);
if (after === 1) await this.redis.expire(key, 90_000); // ~25h, outlives the window
}
/** Redis key for a source's UTC-day budget counter (shared by both lanes). */
private dailyKey(source: string, now = Date.now()): string {
return `prefetch:daily:${source}:${Math.floor(now / 86_400_000)}`;
}
/** Main (backfill) lane threshold — the fast lane's reserve is never available
* to backfill, so a sweep can't park the user's fresh-decode chain. */
private dailyMainLimit(source: string): number {
const max = SOURCE_DAILY_MAX[source] ?? 0;
return max <= 0 ? 0 : Math.floor(max * (1 - DAILY_FAST_RESERVE));
}
/** Record that a backfill attempt finished with the vehicle still at zero parts. */ /** Record that a backfill attempt finished with the vehicle still at zero parts. */
private async markNoResult(vehicleId: string): Promise<void> { private async markNoResult(vehicleId: string): Promise<void> {
const key = this.noResultKey(vehicleId); const key = this.noResultKey(vehicleId);

View File

@@ -7,6 +7,8 @@ import {
computeStats, computeStats,
filterOffersForBrand, filterOffersForBrand,
istanbulToday, istanbulToday,
partPriceCurrentCacheKey,
partPriceSeriesCacheKey,
} from "../../part-prices/part-prices.logic"; } from "../../part-prices/part-prices.logic";
import { createSupplierPriceSource } from "../../part-prices/supplier-price-source"; import { createSupplierPriceSource } from "../../part-prices/supplier-price-source";
@@ -114,8 +116,8 @@ export async function processPartPriceRefresh(
// Cache düşür — bir sonraki sayfa görüntülemesi taze pg satırını okur. // Cache düşür — bir sonraki sayfa görüntülemesi taze pg satırını okur.
const keys = chunk.flatMap((t) => [ const keys = chunk.flatMap((t) => [
`partprice:series:v2:${t.codeNorm}::${t.brandNorm}`, partPriceSeriesCacheKey(t.codeNorm, t.brandNorm),
`partprice:cur:v2:${t.codeNorm}::${t.brandNorm}`, partPriceCurrentCacheKey(t.codeNorm, t.brandNorm),
]); ]);
if (keys.length > 0) await redis.del(...keys); if (keys.length > 0) await redis.del(...keys);

View File

@@ -2,7 +2,7 @@ import { Job } from "bullmq";
import { and, eq, sql } from "drizzle-orm"; import { and, eq, sql } from "drizzle-orm";
import { PostgresJsDatabase } from "drizzle-orm/postgres-js"; import { PostgresJsDatabase } from "drizzle-orm/postgres-js";
import { catalogVehicles, vinpinDecodes } from "../../database/schema/core"; import { catalogVehicles, vinpinDecodes } from "../../database/schema/core";
import { getVinpinDriver } from "../../integrations/vinpin/vinpin-driver.service"; import { getVinpinDaemon } from "../../integrations/vinpin/vinpin-daemon.service";
import { import {
type CatalogCandidate, type CatalogCandidate,
pickBestCatalogMatch, pickBestCatalogMatch,
@@ -42,7 +42,11 @@ export async function processVinpinDecode(
.where(eq(vinpinDecodes.vin, vin)); .where(eq(vinpinDecodes.vin, vin));
try { try {
const decoded = await getVinpinDriver().decode(vin); // Route through the warm-session daemon: inside business hours it decodes on
// the persistent warm seat (taskbar-raise + in-catalog decode); off-hours (or
// when warm can't be established) it transparently uses the cold per-decode
// path. Never throws — returns null on any failure.
const decoded = await getVinpinDaemon().decode(vin);
if (!decoded) { if (!decoded) {
await db await db
@@ -53,7 +57,9 @@ export async function processVinpinDecode(
return { status: "not_found", catalogVehicleId: null }; return { status: "not_found", catalogVehicleId: null };
} }
// Match the decoded model to an existing PL24 Fiat catalog_vehicle. // Match the decoded model to an existing PL24 catalog_vehicle of the SAME
// brand. Fiat → 'fiat'; Renault/Dacia → the decoded brand (RENAULT/DACIA).
const brandName = decoded.brand ?? "Fiat";
const rows = await db const rows = await db
.select({ .select({
id: catalogVehicles.id, id: catalogVehicles.id,
@@ -62,7 +68,10 @@ export async function processVinpinDecode(
}) })
.from(catalogVehicles) .from(catalogVehicles)
.where( .where(
and(sql`lower(${catalogVehicles.brandName}) = 'fiat'`, eq(catalogVehicles.source, "pl24")), and(
sql`lower(${catalogVehicles.brandName}) = ${brandName.toLowerCase()}`,
eq(catalogVehicles.source, "pl24"),
),
); );
const catalogVehicleId = pickBestCatalogMatch( const catalogVehicleId = pickBestCatalogMatch(
@@ -74,7 +83,7 @@ export async function processVinpinDecode(
.update(vinpinDecodes) .update(vinpinDecodes)
.set({ .set({
status: "decoded", status: "decoded",
brandName: "Fiat", brandName,
model: decoded.model, model: decoded.model,
sincom: decoded.sincom, sincom: decoded.sincom,
trim: decoded.trim, trim: decoded.trim,

View File

@@ -0,0 +1,23 @@
import { describe, expect, it } from "vitest";
import { VINPIN_DECODE_JOB_OPTIONS } from "./vinpin-decode.queue";
/**
* The single Vinpin seat is shared by every decode and the driver runs its own
* bounded internal retries + a hard wall-clock budget. A BullMQ-level auto-retry
* on top is what compounded the prod seat livelock (a failed decode auto-re-ran
* straight back into the stuck seat). So the queue must NOT auto-retry.
*/
describe("vinpin-decode queue job options", () => {
it("uses attempts:1 — no BullMQ auto-retry", () => {
expect(VINPIN_DECODE_JOB_OPTIONS.attempts).toBe(1);
});
it("does not configure a retry backoff", () => {
expect(VINPIN_DECODE_JOB_OPTIONS.backoff).toBeUndefined();
});
it("still bounds retained job history", () => {
expect(VINPIN_DECODE_JOB_OPTIONS.removeOnComplete).toEqual({ count: 50 });
expect(VINPIN_DECODE_JOB_OPTIONS.removeOnFail).toEqual({ count: 100 });
});
});

View File

@@ -1,9 +1,28 @@
import { Provider } from "@nestjs/common"; import { Provider } from "@nestjs/common";
import { Queue } from "bullmq"; import { type JobsOptions, Queue } from "bullmq";
import { QUEUE_NAMES, getBullConnection, getBullTelemetry } from "../bull.config"; import { QUEUE_NAMES, getBullConnection, getBullTelemetry } from "../bull.config";
export const VINPIN_DECODE_QUEUE = "VINPIN_DECODE_QUEUE"; export const VINPIN_DECODE_QUEUE = "VINPIN_DECODE_QUEUE";
/**
* Default job options for the Vinpin decode queue.
*
* `attempts: 1` — NO BullMQ-level auto-retry. The single Vinpin seat is shared by
* every decode, and the driver ALREADY runs its own bounded internal retries
* (VINPIN_DECODE_MAX_ATTEMPTS) plus a hard wall-clock budget before it reports
* not_found. Stacking a BullMQ retry (the old attempts:2 + 30s exponential
* backoff) on top is exactly what compounded the seat livelock in prod: one bad
* VIN would fail, auto-re-run 30s later straight back into the stuck seat, and
* starve real decodes for minutes. A failed decode now persists as not_found (a
* clean "not decodable") or failed (a hard infra error, user-retriable) instead of
* being auto-re-fed into the seat.
*/
export const VINPIN_DECODE_JOB_OPTIONS: JobsOptions = {
attempts: 1,
removeOnComplete: { count: 50 },
removeOnFail: { count: 100 },
};
/** Vinpin ePER decode-oracle queue. Single Vinpin seat → the worker consumes /** Vinpin ePER decode-oracle queue. Single Vinpin seat → the worker consumes
* this with concurrency 1. Jobs carry just `{ vin }`. */ * this with concurrency 1. Jobs carry just `{ vin }`. */
export const VinpinDecodeQueueProvider: Provider = { export const VinpinDecodeQueueProvider: Provider = {
@@ -13,14 +32,7 @@ export const VinpinDecodeQueueProvider: Provider = {
return new Queue(QUEUE_NAMES.VINPIN_DECODE, { return new Queue(QUEUE_NAMES.VINPIN_DECODE, {
connection: getBullConnection(), connection: getBullConnection(),
...(telemetry ? { telemetry } : {}), ...(telemetry ? { telemetry } : {}),
defaultJobOptions: { defaultJobOptions: VINPIN_DECODE_JOB_OPTIONS,
// The driver itself retries (VINPIN_DECODE_MAX_ATTEMPTS) before reporting
// not_found, so the queue keeps a small attempt budget for hard crashes.
attempts: 2,
backoff: { type: "exponential", delay: 30_000 },
removeOnComplete: { count: 50 },
removeOnFail: { count: 100 },
},
}); });
}, },
}; };

View File

@@ -58,6 +58,10 @@ async function bootstrap() {
"https://connect.facebook.net", "https://connect.facebook.net",
"https://challenges.cloudflare.com", "https://challenges.cloudflare.com",
"https://destek.sase.tr", "https://destek.sase.tr",
// Google Ads gtag.js (conversion tracking). Its absence here silently
// blocked the whole tag from loading → gtag config/conversion never ran
// → 0 conversions for weeks despite correct AW id + labels.
"https://www.googletagmanager.com",
"'sha256-T5FzBQBMINFjZ4WLy58SeZ+J7xXzjnQEGlg618CQnhA='", "'sha256-T5FzBQBMINFjZ4WLy58SeZ+J7xXzjnQEGlg618CQnhA='",
], ],
styleSrc: ["'self'", "https:", "'unsafe-inline'"], styleSrc: ["'self'", "https:", "'unsafe-inline'"],
@@ -67,6 +71,12 @@ async function bootstrap() {
"https://storage.sase.tr", "https://storage.sase.tr",
"https://www.facebook.com", "https://www.facebook.com",
"https://destek.sase.tr", "https://destek.sase.tr",
// Google Ads conversion + remarketing pixel pings (fire as images).
"https://www.google.com",
"https://www.google.com.tr",
"https://www.googleadservices.com",
"https://googleads.g.doubleclick.net",
"https://ad.doubleclick.net",
], ],
fontSrc: ["'self'", "https:", "data:"], fontSrc: ["'self'", "https:", "data:"],
mediaSrc: ["'self'", "data:", "https://destek.sase.tr"], mediaSrc: ["'self'", "data:", "https://destek.sase.tr"],
@@ -79,6 +89,14 @@ async function bootstrap() {
"https://challenges.cloudflare.com", "https://challenges.cloudflare.com",
"https://destek.sase.tr", "https://destek.sase.tr",
"wss://destek.sase.tr", "wss://destek.sase.tr",
// Google Ads gtag config fetch + conversion pings (googleadservices /
// google.com 1p-conversion & ccm/collect enhanced-conversion beacons).
"https://www.googletagmanager.com",
"https://www.google.com",
"https://www.google.com.tr",
"https://www.googleadservices.com",
"https://googleads.g.doubleclick.net",
"https://ad.doubleclick.net",
// Sentry browser SDK envelope POSTs (otolog org, de region). // Sentry browser SDK envelope POSTs (otolog org, de region).
// Without this CSP silently blocks every error/replay upload. // Without this CSP silently blocks every error/replay upload.
"https://*.ingest.de.sentry.io", "https://*.ingest.de.sentry.io",

View File

@@ -21,6 +21,9 @@ export const OPTIONAL_WORKFLOWS = new Set<string>([
"referral", "referral",
"referral-qualified", "referral-qualified",
"referral-reward", "referral-reward",
// Manual campaign sends (host-side sase-conversion-campaign.sh) — marketing,
// so it must honour opt-out and its unsubscribe tokens must validate here.
"conversion",
"mobile_push", "mobile_push",
]); ]);
@@ -50,6 +53,7 @@ export const NOTIFICATION_CATEGORIES = [
"referral", "referral",
"referral-qualified", "referral-qualified",
"referral-reward", "referral-reward",
"conversion",
] as const, ] as const,
}, },
{ {

View File

@@ -62,24 +62,34 @@ const NO_UNSUBSCRIBE_WORKFLOWS = new Set<string>([
"payment-failed", "payment-failed",
]); ]);
/**
* Signed HTTPS unsubscribe link for a (workflow, user) pair — the same URL the
* List-Unsubscribe header carries. GET renders a confirmation page, POST is
* the RFC 8058 one-click. Null for transactional flows or when the secret is
* unset (dev), so callers can skip the payload/header entirely.
*/
export function buildUnsubscribeUrl(workflow: string, subscriberId: string): string | null {
if (NO_UNSUBSCRIBE_WORKFLOWS.has(workflow)) return null;
if (!UNSUBSCRIBE_URL_BASE || !UNSUBSCRIBE_SECRET) return null;
const token = createHmac("sha256", UNSUBSCRIBE_SECRET)
.update(`${subscriberId}|${workflow}`)
.digest("hex");
const q = new URLSearchParams({ u: subscriberId, w: workflow, t: token });
return `${UNSUBSCRIBE_URL_BASE}?${q.toString()}`;
}
function buildUnsubscribeHeaders(workflow: string, subscriberId: string): Record<string, string> { function buildUnsubscribeHeaders(workflow: string, subscriberId: string): Record<string, string> {
if (NO_UNSUBSCRIBE_WORKFLOWS.has(workflow)) return {}; if (NO_UNSUBSCRIBE_WORKFLOWS.has(workflow)) return {};
const targets: string[] = []; const targets: string[] = [];
if (UNSUBSCRIBE_URL_BASE && UNSUBSCRIBE_SECRET) { const httpsUrl = buildUnsubscribeUrl(workflow, subscriberId);
const token = createHmac("sha256", UNSUBSCRIBE_SECRET) if (httpsUrl) targets.push(`<${httpsUrl}>`);
.update(`${subscriberId}|${workflow}`)
.digest("hex");
const q = new URLSearchParams({ u: subscriberId, w: workflow, t: token });
targets.push(`<${UNSUBSCRIBE_URL_BASE}?${q.toString()}>`);
}
targets.push( targets.push(
`<mailto:${UNSUBSCRIBE_EMAIL}?subject=unsubscribe%3A${encodeURIComponent(workflow)}>`, `<mailto:${UNSUBSCRIBE_EMAIL}?subject=unsubscribe%3A${encodeURIComponent(workflow)}>`,
); );
const headers: Record<string, string> = { "List-Unsubscribe": targets.join(", ") }; const headers: Record<string, string> = { "List-Unsubscribe": targets.join(", ") };
// RFC 8058 one-click — only assert when an HTTPS endpoint is wired; Gmail // RFC 8058 one-click — only assert when an HTTPS endpoint is wired; Gmail
// will probe the HTTPS target with POST when this header is present, so // will probe the HTTPS target with POST when this header is present.
// gate it behind both env vars being set. if (httpsUrl) {
if (UNSUBSCRIBE_URL_BASE && UNSUBSCRIBE_SECRET) {
headers["List-Unsubscribe-Post"] = "List-Unsubscribe=One-Click"; headers["List-Unsubscribe-Post"] = "List-Unsubscribe=One-Click";
} }
return headers; return headers;
@@ -176,7 +186,14 @@ export async function triggerNovu(
// Postal only AFTER the host-side Novu NodemailerProvider patch is applied — // Postal only AFTER the host-side Novu NodemailerProvider patch is applied —
// see postal/novu-patches/apply-headers-patch.sh. // see postal/novu-patches/apply-headers-patch.sh.
const unsubHeaders = buildUnsubscribeHeaders(name, to.subscriberId); const unsubHeaders = buildUnsubscribeHeaders(name, to.subscriberId);
const body: Record<string, unknown> = { name, to, payload }; // Visible body-footer variant of the same link — templates render it via
// `{{#if unsubscribeUrl}}` so mails stay valid when the secret is unset.
const unsubscribeUrl = buildUnsubscribeUrl(name, to.subscriberId);
const fullPayload =
unsubscribeUrl && payload.unsubscribeUrl === undefined
? { ...payload, unsubscribeUrl }
: payload;
const body: Record<string, unknown> = { name, to, payload: fullPayload };
if (Object.keys(unsubHeaders).length > 0) { if (Object.keys(unsubHeaders).length > 0) {
body.overrides = { email: { headers: unsubHeaders } }; body.overrides = { email: { headers: unsubHeaders } };
} }

View File

@@ -113,6 +113,7 @@ const WORKFLOW_LABELS: Record<string, string> = {
referral: "Davet hatırlatması", referral: "Davet hatırlatması",
"referral-qualified": "Davet bildirimleri", "referral-qualified": "Davet bildirimleri",
"referral-reward": "Ödül bildirimleri", "referral-reward": "Ödül bildirimleri",
conversion: "Kampanya mailleri",
}; };
/** /**
@@ -141,7 +142,7 @@ function renderPage(ok: boolean, workflow: string): string {
<h1 style="font-size:20px;margin:22px 0 14px;">Abonelikten çıkıldı</h1> <h1 style="font-size:20px;margin:22px 0 14px;">Abonelikten çıkıldı</h1>
<p style="color:#4a4a4a;line-height:1.6;">Artık <strong>${escapeHtml(label)}</strong> almayacaksın. Hesabınla ilgili önemli bilgilendirme mailleri (e-posta doğrulama, ödeme bildirimleri) gelmeye devam eder.</p> <p style="color:#4a4a4a;line-height:1.6;">Artık <strong>${escapeHtml(label)}</strong> almayacaksın. Hesabınla ilgili önemli bilgilendirme mailleri (e-posta doğrulama, ödeme bildirimleri) gelmeye devam eder.</p>
<p style="color:#777;font-size:14px;margin-top:24px;">Fikrini değiştirirsen ayarlar &gt; bildirimler sayfasından geri açabilirsin.</p> <p style="color:#777;font-size:14px;margin-top:24px;">Fikrini değiştirirsen ayarlar &gt; bildirimler sayfasından geri açabilirsin.</p>
<p style="margin-top:22px;"><a href="https://sase.tr/dashboard/settings/notifications" style="display:inline-block;background:#111;color:#fff;text-decoration:none;padding:12px 26px;border-radius:8px;font-weight:600;">Ayarları aç</a></p> <p style="margin-top:22px;"><a href="https://sase.tr/dashboard/settings?tab=notifications" style="display:inline-block;background:#111;color:#fff;text-decoration:none;padding:12px 26px;border-radius:8px;font-weight:600;">Ayarları aç</a></p>
</main></body>`; </main></body>`;
} }

View File

@@ -6,10 +6,13 @@ import {
brandCompatible, brandCompatible,
computeStats, computeStats,
filterOffersForBrand, filterOffersForBrand,
isOeSupplyLabel,
istanbulToday, istanbulToday,
normPartCode, normPartCode,
oeFamilyOf,
percentile, percentile,
reconstructDailySeries, reconstructDailySeries,
selectOeOffers,
} from "./part-prices.logic"; } from "./part-prices.logic";
describe("normPartCode", () => { describe("normPartCode", () => {
@@ -174,17 +177,139 @@ describe("filterOffersForBrand", () => {
expect(filterOffersForBrand(offers, "", "27155")).toEqual([]); expect(filterOffersForBrand(offers, "", "27155")).toEqual([]);
}); });
it("uzun kodda markasız istek tüm teklifleri kullanır (OE vakası)", () => { it("uzun kodda markasız istek YALNIZ orijinal teklifleri kullanır", () => {
const oe = [ // 2026-07-14 vakası: orijinal+yan sanayi tek havuzda "hayalet medyan"
{ brandNorm: "MAIS", price: 195 }, // üretiyordu (9827622780 → 4.495₺, hiçbir satıcının fiyatı değil).
{ brandNorm: "RENAULT", price: 247 }, // kokpit tur'una göre MAIS+OPAR orijinal; SAGEMFRANS/FEBI değil.
const mixed = [
{ brandNorm: "MAIS", price: 245 },
{ brandNorm: "OPAR", price: 247 },
{ brandNorm: "SAGEMFRANS", price: 210 },
{ brandNorm: "FEBI", price: 160 },
]; ];
expect(filterOffersForBrand(oe, "", "8200768913")).toHaveLength(2); const out = filterOffersForBrand(mixed, "", "8200768913");
expect(out.map((o) => o.brandNorm).sort()).toEqual(["MAIS", "OPAR"]);
}); });
it("uzun kod + uyumsuz marka etiketi → dağıtıcı fallback'i (tümü)", () => { it("markasız istekte hiç orijinal teklif yoksa boş (yan sanayi OE gibi gösterilmez)", () => {
const oe = [{ brandNorm: "MAIS", price: 195 }]; const amOnly = [{ brandNorm: "BRUCKE", price: 890 }];
expect(filterOffersForBrand(oe, "RENAULT", "8200768913")).toHaveLength(1); expect(filterOffersForBrand(amOnly, "", "46456072")).toEqual([]);
});
it("araç markası → SADECE o markanın OE ailesi (PSA vs OPAR ayrışır)", () => {
// 9827622780 vakası: aynı koda PSA (Peugeot ailesi) ve OPAR (Fiat ailesi)
// düşüyor. Peugeot kodu istenince yalnız PSA gelir, OPAR elenir → medyan
// artık iki dağıtıcının ortası (hayalet) değil.
const mixed = [
{ brandNorm: "PSA", price: 5531 },
{ brandNorm: "OPAR", price: 3459 },
{ brandNorm: "FEBI", price: 900 },
];
expect(filterOffersForBrand(mixed, "PEUGEOT", "9827622780")).toEqual([
{ brandNorm: "PSA", price: 5531 },
]);
// Aynı kod Fiat aracından istenirse OPAR gelir.
expect(filterOffersForBrand(mixed, "FIAT", "9827622780")).toEqual([
{ brandNorm: "OPAR", price: 3459 },
]);
});
it("araç markası dağıtıcı etiketine eşlenir (RENAULT → MAIS), yan sanayi elenir", () => {
const oe = [
{ brandNorm: "MAIS", price: 195 },
{ brandNorm: "FEBI", price: 90 },
{ brandNorm: "OPAR", price: 210 }, // farklı aile → elenir
];
expect(filterOffersForBrand(oe, "RENAULT", "8200768913")).toEqual([
{ brandNorm: "MAIS", price: 195 },
]);
});
it("araç markası + jenerik ORJINAL → elenir (aile belirsiz)", () => {
const oe = [
{ brandNorm: "PSA", price: 5531 },
{ brandNorm: "ORJINAL", price: 111 },
];
expect(filterOffersForBrand(oe, "CITROEN", "9827622780")).toEqual([
{ brandNorm: "PSA", price: 5531 },
]);
});
it("yan sanayi markası çipi → yalnız etiketi uyumlular, OE'ye düşmez", () => {
const oe = [
{ brandNorm: "MAIS", price: 195 },
{ brandNorm: "FEBI", price: 160 },
];
// FEBI çipi FEBI'yi alır; MAIS (orijinal) gösterilmez.
expect(filterOffersForBrand(oe, "FEBIBILSTEIN", "8200768913")).toEqual([
{ brandNorm: "FEBI", price: 160 },
]);
});
});
describe("isOeSupplyLabel / selectOeOffers (OE aileleri + jenerik ORJINAL)", () => {
it("dağıtıcı ve orijinal etiketleri tanır", () => {
expect(isOeSupplyLabel("MAIS")).toBe(true); // Renault dağıtıcısı
expect(isOeSupplyLabel("OPAR")).toBe(true); // Fiat/Tofaş
expect(isOeSupplyLabel("PSA")).toBe(true);
expect(isOeSupplyLabel("ORJINAL")).toBe(true); // jenerik orijinal
expect(isOeSupplyLabel("VECO")).toBe(true); // Iveco OE alias'ı
});
it("ham araç-marka etiketleri de ORİJİNALDİR (kokpit'in yansanayi demesi yanlış)", () => {
// 2026-07-14 kullanıcı düzeltmesi: FORD/GM/BMW/Mercedes/VW OE etiketidir.
expect(isOeSupplyLabel("FORD")).toBe(true);
expect(isOeSupplyLabel("GM")).toBe(true); // Opel OE'si
expect(isOeSupplyLabel("BMW")).toBe(true);
expect(isOeSupplyLabel("MERCEDES")).toBe(true);
expect(isOeSupplyLabel("VOLKSWAGEN")).toBe(true);
expect(isOeSupplyLabel("RENAULT")).toBe(true);
});
it("gerçek yan sanayi PARÇA markaları orijinal DEĞİL", () => {
expect(isOeSupplyLabel("BOSCH")).toBe(false);
expect(isOeSupplyLabel("FEBI")).toBe(false);
expect(isOeSupplyLabel("VALEO")).toBe(false);
expect(isOeSupplyLabel("TRW")).toBe(false);
expect(isOeSupplyLabel("")).toBe(false);
});
it("GM Opel ailesine, FORD kendi ailesine eşlenir", () => {
expect(oeFamilyOf("GM")).toBe("OPEL");
expect(oeFamilyOf("FORD")).toBe("FORD");
expect(oeFamilyOf("MERCEDES")).toBe("MERCEDES");
});
it("selectOeOffers karma havuzdan orijinalleri (araç markaları dahil) seçer", () => {
const out = selectOeOffers([
{ brandNorm: "OPAR", price: 767 },
{ brandNorm: "FORD", price: 480 }, // artık orijinal
{ brandNorm: "IBR", price: 909 }, // İbraş = yan sanayi
]);
expect(out.map((o) => o.brandNorm).sort()).toEqual(["FORD", "OPAR"]);
});
it("Ford kodu araç markası FORD → FORD teklifi gelir", () => {
const offers = [
{ brandNorm: "FORD", price: 480 },
{ brandNorm: "BOSCH", price: 300 },
];
expect(filterOffersForBrand(offers, "FORD", "1234567890")).toEqual([
{ brandNorm: "FORD", price: 480 },
]);
});
it("Opel kodu → OPEL + GM aynı aile, ikisi de gelir; PSA farklı aile elenir", () => {
const offers = [
{ brandNorm: "GM", price: 500 },
{ brandNorm: "OPEL", price: 520 },
{ brandNorm: "PSA", price: 610 },
];
expect(
filterOffersForBrand(offers, "OPEL", "9827622780")
.map((o) => o.brandNorm)
.sort(),
).toEqual(["GM", "OPEL"]);
}); });
}); });

View File

@@ -31,6 +31,104 @@ export function normPartCode(code: string): string {
// süzülür. Tedarikçiler markayı kısaltarak yazar (BCH/B→Bosch, BLP→Blue // süzülür. Tedarikçiler markayı kısaltarak yazar (BCH/B→Bosch, BLP→Blue
// Print, IBR→İbraş) — eşleşme önek VEYA sıralı-altdizi ile yapılır. // Print, IBR→İbraş) — eşleşme önek VEYA sıralı-altdizi ile yapılır.
// ─── Orijinal (OE) etiketleri ve marka aileleri ────────────────────────────
// Markasız/araç-markalı bağlam (OEM detay kartı) yalnız ORİJİNAL teklifleri
// gösterir: orijinal + yan sanayi tek havuzda medyanlanınca hiçbir gerçek
// ürünün fiyatı olmayan "hayalet fiyat" çıkar (2026-07-14: 9827622780 →
// 4.495₺ = PSA 5.531 ile OPAR 3.459'un ortası).
//
// Bir OEM kodu tek bir araç markasına aittir → teklifleri o markanın OE
// ailesine süzeriz (aynı koda düşen PSA vs OPAR karışmaz). `family → üyeler`;
// üyeler hem araç markası adları (istek/sase brands) hem dağıtıcı etiketleridir
// (teklif/takip: MAIS=Renault, OPAR=Fiat, PSA, VECO=Iveco, GM=Opel).
//
// ORİJİNAL TESPİTİ: bir teklif etiketi orijinal sayılır ancak bir OE ailesinin
// üyesiyse ya da jenerik "ORJINAL" ise. Kaynak = sase araç markaları + Türkiye
// OE-dağıtıcı etiketleri. NOT (2026-07-14 kullanıcı düzeltmesi): ham araç-marka
// etiketleri (FORD, GM, BMW, MERCEDES, VOLKSWAGEN, RENAULT, FIAT…) ORİJİNALDİR
// — kokpit `tur` bunları 'yansanayi' sayıyordu, bu YANLIŞ; burada aileleriyle
// birlikte orijinal kabul edilir. Gerçek yan sanayi PARÇA markaları (Bosch/
// Febi/Valeo/TRW…) hiçbir ailede değildir → orijinal sayılmaz.
const OE_FAMILIES: Readonly<Record<string, readonly string[]>> = {
RENAULT: ["RENAULT", "DACIA", "ALPINE", "MAIS"],
FIAT: ["FIAT", "ALFAROMEO", "LANCIA", "ABARTH", "OPAR", "TOFAS"],
PSA: ["PEUGEOT", "CITROEN", "DS", "PSA"],
OPEL: ["OPEL", "VAUXHALL", "GM"], // GM = General Motors, TR'de Opel OE'si
VAG: ["VOLKSWAGEN", "VW", "AUDI", "SEAT", "SKODA", "CUPRA", "BENTLEY"],
FORD: ["FORD"],
BMW: ["BMW", "MINI"],
MERCEDES: ["MERCEDESBENZ", "MERCEDES", "SMART"],
TOYOTA: ["TOYOTA", "TOYOTAORJINAL", "LEXUS"],
HONDA: ["HONDA"],
NISSAN: ["NISSAN", "INFINITI"],
HYUNDAI: ["HYUNDAI"],
KIA: ["KIA"],
MAZDA: ["MAZDA"],
VOLVO: ["VOLVO", "POLESTAR"],
PORSCHE: ["PORSCHE"],
JLR: ["JAGUAR", "LANDROVER"],
MAN: ["MAN"],
MITSUBISHI: ["MITSUBISHI"],
SUBARU: ["SUBARU"],
SUZUKI: ["SUZUKI"],
IVECO: ["IVECO", "VECO", "OEVECO"],
// sase araç listesinde olmayan ama teklif/istek olarak gelebilecek markalar.
CHRYSLER: ["CHRYSLER", "DODGE", "JEEP", "MOPAR", "LINCOLN", "BUICK"],
CHEVROLET: ["CHEVROLET"],
DAEWOO: ["DAEWOO"],
DAIHATSU: ["DAIHATSU"],
DFM: ["DFM"],
LADA: ["LADA"],
PROTON: ["PROTON"],
ROVER: ["ROVER", "RANGE"],
SAAB: ["SAAB"],
SSANGYONG: ["SSANGYONG"],
TATA: ["TATA"],
TESLA: ["TESLA"],
TOGG: ["TOGG"],
};
const OE_FAMILY_OF: ReadonlyMap<string, string> = new Map(
Object.entries(OE_FAMILIES).flatMap(([family, members]) =>
members.map((m) => [m, family] as [string, string]),
),
);
/** Markanın (araç ya da dağıtıcı etiketi) OE ailesi; bilinmiyorsa null.
* Jenerik "ORJINAL" hiçbir aileye ait değildir (markası belirsiz) → null. */
export function oeFamilyOf(brandNorm: string): string | null {
return OE_FAMILY_OF.get(brandNorm) ?? null;
}
// Orijinal etiket seti = tüm OE aile üyeleri + jenerik "ORJINAL" (orijinal ama
// aile-belirsiz: markasız/taban görünümde sayılır, aile filtresinde elenir).
// Aileden TÜRETİLİR → OE-tespiti ile aile-filtresi asla drift etmez; yeni bir
// marka eklemek için tek yer OE_FAMILIES.
const OE_SUPPLY_LABELS: ReadonlySet<string> = new Set([
...Object.values(OE_FAMILIES).flat(),
"ORJINAL",
]);
/** Teklifin etiketi orijinal mi (bir OE ailesinin üyesi ya da jenerik ORJINAL). */
export function isOeSupplyLabel(brandNorm: string): boolean {
return OE_SUPPLY_LABELS.has(brandNorm);
}
/** Yalnız orijinal (OE) etiketli teklifler. */
export function selectOeOffers<T extends { brandNorm: string }>(offers: T[]): T[] {
return offers.filter((o) => isOeSupplyLabel(o.brandNorm));
}
// ─── Redis cache anahtarları ───────────────────────────────────────────────
// Service ve worker processor'ı AYNI üreticileri kullanır (literal kopya
// drift'i olmasın). v4 = OE seti araç-marka etiketlerini (FORD/GM/BMW/MERCEDES/
// VW…) de kapsayacak şekilde genişledi → v3'teki "miss" değerleri bayat.
export const PART_PRICE_CACHE_VERSION = "v4";
export const partPriceSeriesCacheKey = (codeNorm: string, brandNorm: string) =>
`partprice:series:${PART_PRICE_CACHE_VERSION}:${codeNorm}::${brandNorm}`;
export const partPriceCurrentCacheKey = (codeNorm: string, brandNorm: string) =>
`partprice:cur:${PART_PRICE_CACHE_VERSION}:${codeNorm}::${brandNorm}`;
/** a'nın tüm karakterleri b içinde aynı sırayla geçiyor mu (BCH ⊂ BOSCH). */ /** a'nın tüm karakterleri b içinde aynı sırayla geçiyor mu (BCH ⊂ BOSCH). */
export function inOrderSubsequence(a: string, b: string): boolean { export function inOrderSubsequence(a: string, b: string): boolean {
let i = 0; let i = 0;
@@ -61,10 +159,17 @@ export function allowBrandless(codeNorm: string): boolean {
/** /**
* Teklifleri istenen markaya süz: * Teklifleri istenen markaya süz:
* - marka istendi → uyumlular; hiçbiri uymuyorsa ve kod markasız-güvenliyse * - istenen marka bir ARAÇ/OE markasıysa (OEM kartına o kodun araç markası
* hepsi (OE/dağıtıcı etiketi vakası: RENAULT istenir, teklifler MAIS taşır); * geçer, ör. PEUGEOT) → yalnız o markanın OE ailesinden orijinal teklifler
* kısa kodda boş (yanlış veri göstermekten iyidir), * (PEUGEOT → PSA ailesi; OPAR/MAIS gibi başka aile dağıtıcıları elenir).
* - marka istenmedi → kod markasız-güvenliyse hepsi, değilse boş. * Böylece aynı koda düşen PSA vs OPAR karışıp medyanı bozmaz. Jenerik
* "ORJINAL" (aile belirsiz) bu süzgeçte elenir,
* - istenen marka bir YAN SANAYİ markasıysa (FEBI çipi) → etiketi uyumlu
* teklifler (kısaltma/önek eşleşmesi); OE'ye düşme YOK,
* - marka istenmedi (kodun markası bilinmiyor) → yalnız orijinal (tüm OE
* aileleri) — güvenli taban; yan sanayi karışımı hayalet medyan üretirdi,
* - kısa/çakışmaya açık kodlarda (allowBrandless=false) araç-markası ve
* markasız yolları kapalıdır (yanlış veri göstermekten iyidir).
*/ */
export function filterOffersForBrand<T extends { brandNorm: string }>( export function filterOffersForBrand<T extends { brandNorm: string }>(
offers: T[], offers: T[],
@@ -72,11 +177,17 @@ export function filterOffersForBrand<T extends { brandNorm: string }>(
codeNorm: string, codeNorm: string,
): T[] { ): T[] {
if (requestedBrandNorm) { if (requestedBrandNorm) {
const compat = offers.filter((o) => brandCompatible(o.brandNorm, requestedBrandNorm)); const family = oeFamilyOf(requestedBrandNorm);
if (compat.length > 0) return compat; if (family) {
return allowBrandless(codeNorm) ? offers : []; if (!allowBrandless(codeNorm)) return [];
return offers.filter(
(o) => isOeSupplyLabel(o.brandNorm) && oeFamilyOf(o.brandNorm) === family,
);
}
// Aile eşlemesi yok → yan sanayi markası: etiket uyumuna göre süz.
return offers.filter((o) => brandCompatible(o.brandNorm, requestedBrandNorm));
} }
return allowBrandless(codeNorm) ? offers : []; return allowBrandless(codeNorm) ? selectOeOffers(offers) : [];
} }
export interface SupplierOffer { export interface SupplierOffer {

View File

@@ -17,6 +17,8 @@ import {
filterOffersForBrand, filterOffersForBrand,
istanbulToday, istanbulToday,
normPartCode, normPartCode,
partPriceCurrentCacheKey,
partPriceSeriesCacheKey,
reconstructDailySeries, reconstructDailySeries,
} from "./part-prices.logic"; } from "./part-prices.logic";
import { type SupplierPriceSource, createSupplierPriceSource } from "./supplier-price-source"; import { type SupplierPriceSource, createSupplierPriceSource } from "./supplier-price-source";
@@ -54,10 +56,8 @@ const BATCH_CACHE_TTL = 1800;
const MAX_BATCH_PARTS = 400; const MAX_BATCH_PARTS = 400;
export const partPriceKey = (codeNorm: string, brandNorm: string) => `${codeNorm}::${brandNorm}`; export const partPriceKey = (codeNorm: string, brandNorm: string) => `${codeNorm}::${brandNorm}`;
const seriesKey = (codeNorm: string, brandNorm: string) => const seriesKey = partPriceSeriesCacheKey;
`partprice:series:v2:${codeNorm}::${brandNorm}`; const currentKey = partPriceCurrentCacheKey;
const currentKey = (codeNorm: string, brandNorm: string) =>
`partprice:cur:v2:${codeNorm}::${brandNorm}`;
/** /**
* Parça (kod + marka) bazlı tedarikçi fiyat görünümleri. P-servisi sözleşmesi: * Parça (kod + marka) bazlı tedarikçi fiyat görünümleri. P-servisi sözleşmesi:
@@ -67,7 +67,8 @@ const currentKey = (codeNorm: string, brandNorm: string) =>
* Kimlik (kod, marka): kısa sayısal kodlar markalar arası çakışır (FEBI 27155 * Kimlik (kod, marka): kısa sayısal kodlar markalar arası çakışır (FEBI 27155
* ≠ GROS 27155 ≠ İBRAŞ 27155 — farklı fiziksel parçalar). Teklifler sku_map'in * ≠ GROS 27155 ≠ İBRAŞ 27155 — farklı fiziksel parçalar). Teklifler sku_map'in
* marka etiketiyle istenen markaya süzülür (filterOffersForBrand); markasız * marka etiketiyle istenen markaya süzülür (filterOffersForBrand); markasız
* sorgu yalnızca uzun/benzersiz kodlarda tüm teklifleri kullanır. * sorgu (OEM detay ana kartı) yalnızca ORİJİNAL (OE/dağıtıcı) teklifleri
* kullanır — orijinal+yan-sanayi havuzu hayalet medyan üretir (2026-07-14).
* *
* - Seri: parça ilk kez istendiğinde takip history'sinden lazy-backfill edilir * - Seri: parça ilk kez istendiğinde takip history'sinden lazy-backfill edilir
* ve pg'ye (part_price_tracks + part_price_daily) kalıcı yazılır; sonraki * ve pg'ye (part_price_tracks + part_price_daily) kalıcı yazılır; sonraki

View File

@@ -147,13 +147,15 @@ export class PartsService {
* Reverse catalog: the user's own decoded vehicles whose parts list contains * Reverse catalog: the user's own decoded vehicles whose parts list contains
* this exact OEM code. Powers the "bu kod kataloğunuzda şu araçlarda var" * this exact OEM code. Powers the "bu kod kataloğunuzda şu araçlarda var"
* section of the OEM detail page — pure sase data, no TecDoc/vehicle-structure * section of the OEM detail page — pure sase data, no TecDoc/vehicle-structure
* dependency. Exact match on the indexed `oem_code` (the code came from a real * dependency. NORMALIZE-eşleşme: URL kodu boşluksuz ("9827622780") gelirken
* part row, so the spelling matches). One representative `categoryId` per * katalog aynı kodu boşluklu saklayabilir ("9827 622 780" — özellikle PSA);
* vehicle lets the UI deep-link straight to a schema page showing the part. * exact match bunları kaçırıyordu (fiyat kartı marka çözümü de buna dayanır).
* `parts_oem_code_norm_idx` functional index'iyle aynı ifade → index kullanır.
* Vitrin `categoryId`'si UI'ı doğrudan şema sayfasına götürür.
*/ */
async vehiclesByOem(oemCode: string) { async vehiclesByOem(oemCode: string) {
const code = (oemCode ?? "").trim(); const norm = (oemCode ?? "").toUpperCase().replace(/[^A-Z0-9]/g, "");
if (!code) return []; if (!norm) return [];
return this.db return this.db
.select({ .select({
vehicleId: vehicles.id, vehicleId: vehicles.id,
@@ -165,7 +167,7 @@ export class PartsService {
}) })
.from(parts) .from(parts)
.innerJoin(vehicles, eq(parts.vehicleId, vehicles.id)) .innerJoin(vehicles, eq(parts.vehicleId, vehicles.id))
.where(eq(parts.oemCode, code)) .where(sql`regexp_replace(upper(${parts.oemCode}), '[^A-Z0-9]', '', 'g') = ${norm}`)
.groupBy(vehicles.id, vehicles.brandName, vehicles.model, vehicles.year) .groupBy(vehicles.id, vehicles.brandName, vehicles.model, vehicles.year)
.orderBy(vehicles.brandName, vehicles.model) .orderBy(vehicles.brandName, vehicles.model)
.limit(50); .limit(50);

View File

@@ -7,6 +7,7 @@ import { drizzle } from "drizzle-orm/postgres-js";
import Redis from "ioredis"; import Redis from "ioredis";
import OpenAI from "openai"; import OpenAI from "openai";
import postgres from "postgres"; import postgres from "postgres";
import { getVinpinDaemon } from "./integrations/vinpin/vinpin-daemon.service";
import { QUEUE_NAMES, getBullConnection, getBullTelemetry } from "./jobs/bull.config"; import { QUEUE_NAMES, getBullConnection, getBullTelemetry } from "./jobs/bull.config";
import { processCanonicalBackfill } from "./jobs/processors/canonical-backfill.processor"; import { processCanonicalBackfill } from "./jobs/processors/canonical-backfill.processor";
import { processEmexScrape } from "./jobs/processors/emex-scrape.processor"; import { processEmexScrape } from "./jobs/processors/emex-scrape.processor";
@@ -243,6 +244,15 @@ vinpinDecodeWorker.on("failed", (job, err) => {
workers.push(vinpinDecodeWorker); workers.push(vinpinDecodeWorker);
// Vinpin warm-session daemon: holds the single Vinpin seat warm (browser + login
// + Fiat ePER / Renault Rpartstore / Dialogys windows open) during business hours
// (08:00–21:00 Europe/Istanbul), keepalive-nudged every ~75s, so decodes run on
// the warm seat instead of paying the per-decode launch/login/open cold-start.
// Inert unless VINPIN_ENABLED=true (and not VINPIN_WARM_DAEMON=false). The
// processor calls this daemon; off-hours it transparently uses the cold path.
const vinpinDaemon = getVinpinDaemon();
vinpinDaemon.start();
// Canonical Backfill Worker (maps raw OEM category names → unified taxonomy). // Canonical Backfill Worker (maps raw OEM category names → unified taxonomy).
// On-demand only (no cron); a single pass is a big sweep so concurrency 1. // On-demand only (no cron); a single pass is a big sweep so concurrency 1.
const canonicalBackfillWorker = new Worker( const canonicalBackfillWorker = new Worker(
@@ -341,6 +351,10 @@ async function shutdown(signal: string) {
await Promise.all(workers.map((w) => w.close())); await Promise.all(workers.map((w) => w.close()));
console.log("[worker] All workers closed"); console.log("[worker] All workers closed");
// 2b. Stop the Vinpin warm daemon and release the seat.
await vinpinDaemon.stop();
console.log("[worker] Vinpin warm daemon stopped");
// 3. Close database connection // 3. Close database connection
await sql.end(); await sql.end();
console.log("[worker] Database connection closed"); console.log("[worker] Database connection closed");

View File

@@ -0,0 +1,145 @@
import { SegmentQualifier } from "@/components/auth/segment-qualifier";
import { useAuth } from "@/hooks/use-auth";
import { capture, setPeopleProperties } from "@/lib/posthog";
import { Button } from "@sase/ui";
import { useLocation } from "@tanstack/react-router";
import { useEffect, useState } from "react";
/**
* Universal post-auth segment gate.
*
* The register page gates segment selection behind the form, but that only
* covers email + register-page-OAuth signups. A user who starts Google OAuth
* from the LOGIN page (login.tsx) gets an account created server-side and lands
* on the dashboard with no segment ever chosen — this is the bulk of the ~41%
* of signups with a null segment. Segment isn't persisted server-side (only
* localStorage + a PostHog person property), so we enforce it here at the one
* chokepoint every authenticated user passes through: the dashboard.
*
* Behaviour (product decision 2026-07-27):
* - New users (account created in the last few minutes → the login-OAuth gap):
* MANDATORY, non-dismissible modal.
* - Existing segment-less users (the ~538 backfill): SOFT, dismissible with a
* cooldown so we re-ask later without nagging or blocking active/paying users.
*
* This is a baseline fix shipped to everyone — NOT the `funnel-bucket` A/B
* experiment (that gates the tailored value/upgrade experience separately).
*/
const SEGMENT_KEY = "sase-b2b-segment";
const DISMISS_UNTIL_KEY = "sase-b2b-segment-prompt-until";
// Account younger than this ⇒ treat as a fresh signup (mandatory). Generous so
// the signup → first dashboard load always counts, even with a slow OAuth hop.
const NEW_USER_WINDOW_MS = 15 * 60 * 1000;
// How long a "Daha sonra" dismissal silences the soft prompt for existing users.
const DISMISS_COOLDOWN_MS = 7 * 24 * 60 * 60 * 1000;
function readSegment(): string | null {
try {
return localStorage.getItem(SEGMENT_KEY);
} catch {
return null;
}
}
export function SegmentGate() {
const { user, isLoading } = useAuth();
const location = useLocation();
const [open, setOpen] = useState(false);
const [mandatory, setMandatory] = useState(false);
useEffect(() => {
// Only inside the app, only once the session has resolved to a real user.
if (isLoading || !user) {
setOpen(false);
return;
}
if (!location.pathname.startsWith("/dashboard")) {
setOpen(false);
return;
}
// Already segmented — nothing to do. (Register writes this pre-redirect, so
// email + register-OAuth signups never see the gate.)
if (readSegment()) {
setOpen(false);
return;
}
const createdAt = user.createdAt ? new Date(user.createdAt).getTime() : 0;
const isNew = createdAt > 0 && Date.now() - createdAt < NEW_USER_WINDOW_MS;
if (isNew) {
setMandatory(true);
setOpen(true);
return;
}
// Existing segment-less user: honour the soft-dismiss cooldown.
let dismissedUntil = 0;
try {
dismissedUntil = Number(localStorage.getItem(DISMISS_UNTIL_KEY)) || 0;
} catch {
dismissedUntil = 0;
}
if (Date.now() < dismissedUntil) {
setOpen(false);
return;
}
setMandatory(false);
setOpen(true);
}, [user, isLoading, location.pathname]);
if (!open) return null;
function handleSelect(seg: string) {
try {
localStorage.setItem(SEGMENT_KEY, seg);
} catch {
// localStorage unavailable — still fire analytics below.
}
// `source` distinguishes the login-OAuth gap fill from the backfill so we can
// measure each in PostHog; mirrors register.tsx's signup_segment_selected.
capture("signup_segment_selected", {
segment: seg,
source: mandatory ? "post_signup_gate" : "backfill_gate",
});
setPeopleProperties({ b2b_segment: seg });
setOpen(false);
}
function handleDismiss() {
try {
localStorage.setItem(DISMISS_UNTIL_KEY, String(Date.now() + DISMISS_COOLDOWN_MS));
} catch {
// best-effort
}
capture("signup_segment_prompt_dismissed");
setOpen(false);
}
return (
<div
className="fixed inset-0 z-[60] flex items-center justify-center overflow-y-auto bg-background/80 p-4 backdrop-blur-sm"
// biome-ignore lint/a11y/useSemanticElements: overlay modal — role="dialog"+aria-modal is the correct ARIA here; a native <dialog> would need imperative showModal() plumbing this SPA overlay doesn't use
role="dialog"
aria-modal="true"
aria-label="İşletme türü seçimi"
>
<div className="my-auto w-full max-w-md rounded-2xl border border-border bg-card p-6 shadow-xl">
<div>
<h2 className="text-xl font-bold tracking-tight">Bu platform kimler için?</h2>
<p className="mt-2 text-sm text-muted-foreground">
İşletmeni seç — sana uygun sınırsız şase sorgulama erişimini açalım.
</p>
</div>
<div className="mt-5">
<SegmentQualifier onSelect={handleSelect} />
</div>
{!mandatory && (
<Button variant="ghost" className="mt-3 w-full" onClick={handleDismiss}>
Daha sonra
</Button>
)}
</div>
</div>
);
}

View File

@@ -66,8 +66,9 @@ function DeltaBadge({ pct }: { pct: number }) {
interface PartPriceSectionProps { interface PartPriceSectionProps {
code: string; code: string;
/** Parça markası — kısa kodlarda teklifleri doğru markaya süzer; OEM /** Kartta = kodun araç markası (teklifleri o markanın OE ailesine süzer,
* detayın ana kodu gibi markasız bağlamlarda boş bırakılır. */ * PSA vs OPAR karışmaz); çipte = satırın markası. Bilinmiyorsa boş → tüm
* OE aileleri (güvenli taban). */
brand?: string; brand?: string;
/** Ana sayfa yerleşiminde kart çerçevesi; dialog içinde çıplak. */ /** Ana sayfa yerleşiminde kart çerçevesi; dialog içinde çıplak. */
variant?: "card" | "plain"; variant?: "card" | "plain";
@@ -133,9 +134,13 @@ export function PartPriceSection({
<div className="flex flex-wrap items-start justify-between gap-3"> <div className="flex flex-wrap items-start justify-between gap-3">
{variant === "card" ? ( {variant === "card" ? (
<div> <div>
<h2 className="text-sm font-semibold">Tedarikçi fiyat analizi</h2> <h2 className="text-sm font-semibold">
Orijinal (OE) fiyat analizi{brand ? ` · ${brand}` : ""}
</h2>
<p className="mt-0.5 text-xs text-muted-foreground"> <p className="mt-0.5 text-xs text-muted-foreground">
Stoktaki tekliflerin dağılımı — P50 medyan · P95 · P99 {brand
? `Stoktaki ${brand} orijinal/dağıtıcı tekliflerinin dağılımı — P50 medyan · P95 · P99`
: "Stoktaki orijinal/dağıtıcı tekliflerin dağılımı — P50 medyan · P95 · P99"}
</p> </p>
</div> </div>
) : ( ) : (
@@ -211,8 +216,10 @@ export function PartPriceSection({
</div> </div>
<p className="mt-2 text-[11px] leading-relaxed text-muted-foreground"> <p className="mt-2 text-[11px] leading-relaxed text-muted-foreground">
Fiyatlar stoktaki tedarikçi tekliflerinin istatistiksel dağılımıdır; tedarikçi bilgisi {variant === "card"
paylaşılmaz. Son fiyat değişimi: {formatDateLong(data.series[data.series.length - 1].date)} ? "Fiyatlar yalnızca orijinal (OE/dağıtıcı) tekliflerin dağılımıdır — yan sanayi teklifleri dahil edilmez; tedarikçi bilgisi paylaşılmaz."
: "Fiyatlar stoktaki tedarikçi tekliflerinin istatistiksel dağılımıdır; tedarikçi bilgisi paylaşılmaz."}{" "}
Son fiyat değişimi: {formatDateLong(data.series[data.series.length - 1].date)}
</p> </p>
</section> </section>
); );

View File

@@ -0,0 +1,59 @@
import { useAuth } from "@/hooks/use-auth";
import { trackGoogleAdsConversion } from "@/lib/google-ads";
import { useEffect, useRef } from "react";
/**
* Universal post-auth Google Ads sign-up conversion.
*
* The register page fires the sign-up conversion only on the EMAIL path
* (register.tsx). Google OAuth signups — both the register-page Google button
* and the login-page Google button — complete server-side after a redirect and
* never fire it, so Google Ads saw ~0 of them (measured: ~79% of paid-driven
* signups were OAuth → invisible to Google Ads, starving Max Conversions of its
* signal). This mounts at the root and fires for any brand-new authenticated
* user, covering every signup path.
*
* Double-count safety: the conversion carries transaction_id `signup_<userId>`,
* which Google dedupes on — so an email signup that already fired on the
* register page counts once even though this fires again. The localStorage guard
* additionally stops repeat fires across the new user's first-session pageviews;
* register.tsx sets the same guard so email signups skip the redundant fire.
*
* Attribution: gtag's own `_gcl_aw` cookie (set from gclid on the ad landing)
* survives the same-domain OAuth round-trip, so firing here still attributes to
* the original click. Organic (non-ad) new users fire too, but Google only
* counts conversions it can tie to an ad click — the rest are ignored.
*/
const NEW_USER_WINDOW_MS = 30 * 60 * 1000;
function guardKey(userId: string): string {
return `sase-ga-signup-conv-${userId}`;
}
export function GoogleAdsSignupConversion() {
const { user, isLoading } = useAuth();
const firedRef = useRef(false);
useEffect(() => {
if (isLoading || !user || firedRef.current) return;
const createdAt = user.createdAt ? new Date(user.createdAt).getTime() : 0;
// Only genuinely fresh accounts — this is a signup conversion, not a login.
if (!createdAt || Date.now() - createdAt > NEW_USER_WINDOW_MS) return;
const key = guardKey(user.id);
try {
if (localStorage.getItem(key)) return;
localStorage.setItem(key, "1");
} catch {
// localStorage unavailable — firedRef still prevents in-session repeats.
}
firedRef.current = true;
trackGoogleAdsConversion(import.meta.env.VITE_GOOGLE_ADS_SIGNUP_LABEL, {
transactionId: `signup_${user.id}`,
email: user.email,
});
}, [user, isLoading]);
return null;
}

View File

@@ -1,7 +1,7 @@
import { api } from "@/lib/api-client"; import { api } from "@/lib/api-client";
import { useSession } from "@/lib/auth-client"; import { useSession } from "@/lib/auth-client";
import { useTranslation } from "@/lib/i18n"; import { useTranslation } from "@/lib/i18n";
import { capture } from "@/lib/posthog"; import { capture, subscribeFeatureFlag } from "@/lib/posthog";
import { Button } from "@sase/ui"; import { Button } from "@sase/ui";
import { useQuery } from "@tanstack/react-query"; import { useQuery } from "@tanstack/react-query";
import { Link } from "@tanstack/react-router"; import { Link } from "@tanstack/react-router";
@@ -25,6 +25,31 @@ const VALUE_THRESHOLD = 3;
// Urgency banner owns days <= 3; this one owns days > 3 (no overlap). // Urgency banner owns days <= 3; this one owns days > 3 (no overlap).
const URGENCY_WINDOW_DAYS = 3; const URGENCY_WINDOW_DAYS = 3;
// Kova B of the `funnel-bucket` A/B experiment: segment-tailored, Meta-proven
// value copy for the b2b_qualified variant. These hooks are the ones that won on
// Meta (iade / yanlış-parça / sınırsız-şase framing). Only real B2B segments get
// the pitch; vehicle_owner / unknown fall back to the neutral control copy
// (product decision 2026-07-27 — don't push a subscription on consumers).
const SEGMENT_KEY = "sase-b2b-segment";
const B2B_COPY: Record<string, { title: string; desc: string }> = {
parts_dealer: {
title: "Yanlış parça siparişine son",
desc: "Dükkânına gelen her araçta şaseden doğru OEM parça — iade ve stok derdi yok.",
},
wholesaler: {
title: "Her siparişte birebir OEM",
desc: "Toptan siparişlerde şaseden doğru OEM eşleşmesi — yanlış kalem, iade yok.",
},
ecommerce: {
title: "Listelemende doğru parça",
desc: "Şaseden doğru OEM ile hatalı satışı ve iade oranını düşür.",
},
service_fleet: {
title: "Serviste doğru parça, ilk seferde",
desc: "Her araçta şaseden doğru OEM — bekleme yok, yanlış sipariş yok.",
},
};
function dismissStorageKey(userId: string | null | undefined, endDate: string): string { function dismissStorageKey(userId: string | null | undefined, endDate: string): string {
return `trialValueUpsellDismissed-${userId ?? "anon"}-${endDate}`; return `trialValueUpsellDismissed-${userId ?? "anon"}-${endDate}`;
} }
@@ -80,6 +105,26 @@ export function TrialValueUpsell() {
const visible = inWindow && hasProvenValue && !dismissed; const visible = inWindow && hasProvenValue && !dismissed;
// Read the experiment flag ONLY once the nudge is visible, so the PostHog
// exposure ($feature_flag_called) population = activated trial users who
// actually see it — not every dashboard mount. Keeps the thin signal undiluted.
const [bucket, setBucket] = useState<string | boolean | undefined>(undefined);
useEffect(() => {
if (!visible) return;
return subscribeFeatureFlag("funnel-bucket", setBucket);
}, [visible]);
const [segment] = useState<string | null>(() => {
try {
return localStorage.getItem(SEGMENT_KEY);
} catch {
return null;
}
});
const tailored =
bucket === "b2b_qualified" && segment && segment !== "vehicle_owner"
? B2B_COPY[segment]
: undefined;
useEffect(() => { useEffect(() => {
if (!visible || viewedRef.current || days === null) return; if (!visible || viewedRef.current || days === null) return;
viewedRef.current = true; viewedRef.current = true;
@@ -120,16 +165,16 @@ export function TrialValueUpsell() {
<div className="flex flex-1 flex-col gap-1 sm:flex-row sm:items-center sm:gap-4"> <div className="flex flex-1 flex-col gap-1 sm:flex-row sm:items-center sm:gap-4">
<div> <div>
<p className="text-sm font-semibold text-foreground"> <p className="text-sm font-semibold text-foreground">
{t("subscription.valueUpsell.title")} {tailored ? tailored.title : t("subscription.valueUpsell.title")}
</p> </p>
<p className="text-xs text-muted-foreground"> <p className="text-xs text-muted-foreground">
{t("subscription.valueUpsell.description")} {tailored ? tailored.desc : t("subscription.valueUpsell.description")}
</p> </p>
</div> </div>
<Link to="/dashboard/subscription" className="shrink-0" onClick={handleCTAClick}> <Link to="/dashboard/subscription" className="shrink-0" onClick={handleCTAClick}>
<Button size="sm" className="bg-brand text-white hover:bg-brand/90"> <Button size="sm" className="bg-brand text-white hover:bg-brand/90">
{t("subscription.valueUpsell.cta")} {tailored ? "Sınırsız erişime geç" : t("subscription.valueUpsell.cta")}
</Button> </Button>
</Link> </Link>
</div> </div>

View File

@@ -39,9 +39,15 @@ export function initGoogleAds(): void {
_adsId = id; _adsId = id;
window.dataLayer = window.dataLayer || []; window.dataLayer = window.dataLayer || [];
const gtag: (...args: GtagArgs) => void = (...args) => { // gtag.js executes only queue entries that are the `arguments` object; pushing a
window.dataLayer?.push(args); // plain array (rest params → `args`) is stored as inert dataLayer data and the
}; // command (config/event) NEVER runs. That silently disabled ALL conversion
// tracking — no _gcl_aw linker cookie, no conversion pings, 0 conversions in the
// panel. Use Google's canonical snippet form that pushes `arguments`.
function gtag() {
// biome-ignore lint/style/noArguments: gtag.js only processes the raw arguments object
window.dataLayer?.push(arguments as unknown as GtagArgs);
}
if (!window.gtag) window.gtag = gtag; if (!window.gtag) window.gtag = gtag;
const script = document.createElement("script"); const script = document.createElement("script");

View File

@@ -719,7 +719,10 @@
"previewHint": "Click Decode VIN to access the full parts catalog.", "previewHint": "Click Decode VIN to access the full parts catalog.",
"noCatalogTitle": "We recognized this vehicle", "noCatalogTitle": "We recognized this vehicle",
"noCatalogHint": "There's no ready catalog for this VIN yet. Browse {brand} models in the catalog to find the customer vehicle's parts.", "noCatalogHint": "There's no ready catalog for this VIN yet. Browse {brand} models in the catalog to find the customer vehicle's parts.",
"noCatalogHintNeutral": "There's no ready catalog for this VIN yet. Browse models in the catalog to find the customer vehicle's parts.",
"browseCatalogCta": "Browse the {brand} catalog by model", "browseCatalogCta": "Browse the {brand} catalog by model",
"browseCatalogCtaNeutral": "Browse the catalog by model",
"decodePendingHint": "The vehicle is being identified and will be ready in a few minutes. You can search again shortly.",
"recent": "Recent searches", "recent": "Recent searches",
"seeAll": "See all →", "seeAll": "See all →",
"historyAria": "{brand} {model} — VIN {vin}, open from history", "historyAria": "{brand} {model} — VIN {vin}, open from history",

View File

@@ -719,7 +719,10 @@
"previewHint": "Şase Çöz butonuna tıklayarak tam parça kataloğuna erişin.", "previewHint": "Şase Çöz butonuna tıklayarak tam parça kataloğuna erişin.",
"noCatalogTitle": "Bu aracı tanıdık", "noCatalogTitle": "Bu aracı tanıdık",
"noCatalogHint": "Bu şase için hazır katalog henüz yok. {brand} modellerini katalogdan seçerek müşteri aracının parçalarına ulaşabilirsiniz.", "noCatalogHint": "Bu şase için hazır katalog henüz yok. {brand} modellerini katalogdan seçerek müşteri aracının parçalarına ulaşabilirsiniz.",
"noCatalogHintNeutral": "Bu şase için hazır katalog henüz yok. Modelleri katalogdan seçerek müşteri aracının parçalarına ulaşabilirsiniz.",
"browseCatalogCta": "{brand} kataloğunu modelden incele", "browseCatalogCta": "{brand} kataloğunu modelden incele",
"browseCatalogCtaNeutral": "Kataloğu modelden incele",
"decodePendingHint": "Araç tanımlanıyor, birkaç dakika içinde hazır olacak. Birazdan tekrar sorgulayabilirsiniz.",
"recent": "Son Aramalar", "recent": "Son Aramalar",
"seeAll": "Tümünü Gör →", "seeAll": "Tümünü Gör →",
"historyAria": "{brand} {model} — şase {vin}, geçmişten aç", "historyAria": "{brand} {model} — şase {vin}, geçmişten aç",

View File

@@ -39,6 +39,7 @@ import { Route as DashboardSubscriptionIndexRouteImport } from './routes/dashboa
import { Route as DashboardCatalogIndexRouteImport } from './routes/dashboard/catalog/index' import { Route as DashboardCatalogIndexRouteImport } from './routes/dashboard/catalog/index'
import { Route as DashboardAdminIndexRouteImport } from './routes/dashboard/admin/index' import { Route as DashboardAdminIndexRouteImport } from './routes/dashboard/admin/index'
import { Route as DemoCategoriesCategoryIdRouteImport } from './routes/demo_/categories_/$categoryId' import { Route as DemoCategoriesCategoryIdRouteImport } from './routes/demo_/categories_/$categoryId'
import { Route as DashboardSettingsTabRouteImport } from './routes/dashboard/settings_/$tab'
import { Route as DashboardOemCodeRouteImport } from './routes/dashboard/oem.$code' import { Route as DashboardOemCodeRouteImport } from './routes/dashboard/oem.$code'
import { Route as DashboardBlogSlugRouteImport } from './routes/dashboard/blog_/$slug' import { Route as DashboardBlogSlugRouteImport } from './routes/dashboard/blog_/$slug'
import { Route as DashboardAdminUsersRouteImport } from './routes/dashboard/admin/users' import { Route as DashboardAdminUsersRouteImport } from './routes/dashboard/admin/users'
@@ -210,6 +211,11 @@ const DemoCategoriesCategoryIdRoute =
path: '/demo/categories/$categoryId', path: '/demo/categories/$categoryId',
getParentRoute: () => rootRouteImport, getParentRoute: () => rootRouteImport,
} as any) } as any)
const DashboardSettingsTabRoute = DashboardSettingsTabRouteImport.update({
id: '/settings_/$tab',
path: '/settings/$tab',
getParentRoute: () => DashboardRoute,
} as any)
const DashboardOemCodeRoute = DashboardOemCodeRouteImport.update({ const DashboardOemCodeRoute = DashboardOemCodeRouteImport.update({
id: '/oem/$code', id: '/oem/$code',
path: '/oem/$code', path: '/oem/$code',
@@ -352,6 +358,7 @@ export interface FileRoutesByFullPath {
'/dashboard/admin/users': typeof DashboardAdminUsersRoute '/dashboard/admin/users': typeof DashboardAdminUsersRoute
'/dashboard/blog/$slug': typeof DashboardBlogSlugRoute '/dashboard/blog/$slug': typeof DashboardBlogSlugRoute
'/dashboard/oem/$code': typeof DashboardOemCodeRoute '/dashboard/oem/$code': typeof DashboardOemCodeRoute
'/dashboard/settings/$tab': typeof DashboardSettingsTabRoute
'/demo/categories/$categoryId': typeof DemoCategoriesCategoryIdRoute '/demo/categories/$categoryId': typeof DemoCategoriesCategoryIdRoute
'/dashboard/admin/': typeof DashboardAdminIndexRoute '/dashboard/admin/': typeof DashboardAdminIndexRoute
'/dashboard/catalog/': typeof DashboardCatalogIndexRoute '/dashboard/catalog/': typeof DashboardCatalogIndexRoute
@@ -401,6 +408,7 @@ export interface FileRoutesByTo {
'/dashboard/admin/users': typeof DashboardAdminUsersRoute '/dashboard/admin/users': typeof DashboardAdminUsersRoute
'/dashboard/blog/$slug': typeof DashboardBlogSlugRoute '/dashboard/blog/$slug': typeof DashboardBlogSlugRoute
'/dashboard/oem/$code': typeof DashboardOemCodeRoute '/dashboard/oem/$code': typeof DashboardOemCodeRoute
'/dashboard/settings/$tab': typeof DashboardSettingsTabRoute
'/demo/categories/$categoryId': typeof DemoCategoriesCategoryIdRoute '/demo/categories/$categoryId': typeof DemoCategoriesCategoryIdRoute
'/dashboard/admin': typeof DashboardAdminIndexRoute '/dashboard/admin': typeof DashboardAdminIndexRoute
'/dashboard/catalog': typeof DashboardCatalogIndexRoute '/dashboard/catalog': typeof DashboardCatalogIndexRoute
@@ -453,6 +461,7 @@ export interface FileRoutesById {
'/dashboard/admin/users': typeof DashboardAdminUsersRoute '/dashboard/admin/users': typeof DashboardAdminUsersRoute
'/dashboard/blog_/$slug': typeof DashboardBlogSlugRoute '/dashboard/blog_/$slug': typeof DashboardBlogSlugRoute
'/dashboard/oem/$code': typeof DashboardOemCodeRoute '/dashboard/oem/$code': typeof DashboardOemCodeRoute
'/dashboard/settings_/$tab': typeof DashboardSettingsTabRoute
'/demo_/categories_/$categoryId': typeof DemoCategoriesCategoryIdRoute '/demo_/categories_/$categoryId': typeof DemoCategoriesCategoryIdRoute
'/dashboard/admin/': typeof DashboardAdminIndexRoute '/dashboard/admin/': typeof DashboardAdminIndexRoute
'/dashboard/catalog/': typeof DashboardCatalogIndexRoute '/dashboard/catalog/': typeof DashboardCatalogIndexRoute
@@ -505,6 +514,7 @@ export interface FileRouteTypes {
| '/dashboard/admin/users' | '/dashboard/admin/users'
| '/dashboard/blog/$slug' | '/dashboard/blog/$slug'
| '/dashboard/oem/$code' | '/dashboard/oem/$code'
| '/dashboard/settings/$tab'
| '/demo/categories/$categoryId' | '/demo/categories/$categoryId'
| '/dashboard/admin/' | '/dashboard/admin/'
| '/dashboard/catalog/' | '/dashboard/catalog/'
@@ -554,6 +564,7 @@ export interface FileRouteTypes {
| '/dashboard/admin/users' | '/dashboard/admin/users'
| '/dashboard/blog/$slug' | '/dashboard/blog/$slug'
| '/dashboard/oem/$code' | '/dashboard/oem/$code'
| '/dashboard/settings/$tab'
| '/demo/categories/$categoryId' | '/demo/categories/$categoryId'
| '/dashboard/admin' | '/dashboard/admin'
| '/dashboard/catalog' | '/dashboard/catalog'
@@ -605,6 +616,7 @@ export interface FileRouteTypes {
| '/dashboard/admin/users' | '/dashboard/admin/users'
| '/dashboard/blog_/$slug' | '/dashboard/blog_/$slug'
| '/dashboard/oem/$code' | '/dashboard/oem/$code'
| '/dashboard/settings_/$tab'
| '/demo_/categories_/$categoryId' | '/demo_/categories_/$categoryId'
| '/dashboard/admin/' | '/dashboard/admin/'
| '/dashboard/catalog/' | '/dashboard/catalog/'
@@ -851,6 +863,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof DemoCategoriesCategoryIdRouteImport preLoaderRoute: typeof DemoCategoriesCategoryIdRouteImport
parentRoute: typeof rootRouteImport parentRoute: typeof rootRouteImport
} }
'/dashboard/settings_/$tab': {
id: '/dashboard/settings_/$tab'
path: '/settings/$tab'
fullPath: '/dashboard/settings/$tab'
preLoaderRoute: typeof DashboardSettingsTabRouteImport
parentRoute: typeof DashboardRoute
}
'/dashboard/oem/$code': { '/dashboard/oem/$code': {
id: '/dashboard/oem/$code' id: '/dashboard/oem/$code'
path: '/oem/$code' path: '/oem/$code'
@@ -1022,6 +1041,7 @@ interface DashboardRouteChildren {
DashboardAdminUsersRoute: typeof DashboardAdminUsersRoute DashboardAdminUsersRoute: typeof DashboardAdminUsersRoute
DashboardBlogSlugRoute: typeof DashboardBlogSlugRoute DashboardBlogSlugRoute: typeof DashboardBlogSlugRoute
DashboardOemCodeRoute: typeof DashboardOemCodeRoute DashboardOemCodeRoute: typeof DashboardOemCodeRoute
DashboardSettingsTabRoute: typeof DashboardSettingsTabRoute
DashboardAdminIndexRoute: typeof DashboardAdminIndexRoute DashboardAdminIndexRoute: typeof DashboardAdminIndexRoute
DashboardCatalogIndexRoute: typeof DashboardCatalogIndexRoute DashboardCatalogIndexRoute: typeof DashboardCatalogIndexRoute
DashboardSubscriptionIndexRoute: typeof DashboardSubscriptionIndexRoute DashboardSubscriptionIndexRoute: typeof DashboardSubscriptionIndexRoute
@@ -1056,6 +1076,7 @@ const DashboardRouteChildren: DashboardRouteChildren = {
DashboardAdminUsersRoute: DashboardAdminUsersRoute, DashboardAdminUsersRoute: DashboardAdminUsersRoute,
DashboardBlogSlugRoute: DashboardBlogSlugRoute, DashboardBlogSlugRoute: DashboardBlogSlugRoute,
DashboardOemCodeRoute: DashboardOemCodeRoute, DashboardOemCodeRoute: DashboardOemCodeRoute,
DashboardSettingsTabRoute: DashboardSettingsTabRoute,
DashboardAdminIndexRoute: DashboardAdminIndexRoute, DashboardAdminIndexRoute: DashboardAdminIndexRoute,
DashboardCatalogIndexRoute: DashboardCatalogIndexRoute, DashboardCatalogIndexRoute: DashboardCatalogIndexRoute,
DashboardSubscriptionIndexRoute: DashboardSubscriptionIndexRoute, DashboardSubscriptionIndexRoute: DashboardSubscriptionIndexRoute,

View File

@@ -1,3 +1,5 @@
import { SegmentGate } from "@/components/auth/segment-gate";
import { GoogleAdsSignupConversion } from "@/components/google-ads-signup-conversion";
import { InAppEscape } from "@/components/in-app-escape"; import { InAppEscape } from "@/components/in-app-escape";
import { SurveyPopover } from "@/components/survey-popover"; import { SurveyPopover } from "@/components/survey-popover";
import { useAuth } from "@/hooks/use-auth"; import { useAuth } from "@/hooks/use-auth";
@@ -157,6 +159,8 @@ function RootComponent() {
</a> </a>
<InAppEscape /> <InAppEscape />
<Outlet /> <Outlet />
<SegmentGate />
<GoogleAdsSignupConversion />
<SurveyPopover /> <SurveyPopover />
<Toaster position="top-center" /> <Toaster position="top-center" />
</> </>

View File

@@ -189,6 +189,13 @@ function RegisterPage() {
transactionId: data?.user ? `signup_${data.user.id}` : undefined, transactionId: data?.user ? `signup_${data.user.id}` : undefined,
email, email,
}); });
// Guard so the universal post-auth conversion (which covers OAuth signups)
// skips this email signup — Google would dedupe on transaction_id anyway.
try {
if (data?.user) localStorage.setItem(`sase-ga-signup-conv-${data.user.id}`, "1");
} catch {
// localStorage unavailable — the transaction_id dedupe still protects us.
}
if (plan) localStorage.setItem(PENDING_PLAN_KEY, plan); if (plan) localStorage.setItem(PENDING_PLAN_KEY, plan);
toast.success("Hesap oluşturuldu!"); toast.success("Hesap oluşturuldu!");
window.location.href = redirectUrl; window.location.href = redirectUrl;

View File

@@ -145,12 +145,36 @@ function OemDetailPage() {
}); });
// Reverse catalog: the user's own vehicles that use this OEM code (sase data). // Reverse catalog: the user's own vehicles that use this OEM code (sase data).
const { data: catalogVehicles } = useQuery({ const { data: catalogVehicles, isFetched: catalogVehiclesFetched } = useQuery({
queryKey: ["oem-vehicles", code], queryKey: ["oem-vehicles", code],
queryFn: () => queryFn: () =>
api.get<CatalogVehicle[]>(`/parts/oem-vehicles?code=${encodeURIComponent(code)}`), api.get<CatalogVehicle[]>(`/parts/oem-vehicles?code=${encodeURIComponent(code)}`),
}); });
// Bu OEM kodunun araç markası — kataloğumuzdaki araçlardan en çok geçen
// marka. Fiyat kartı bununla filtreleniyor: bir OEM kodu tek markaya aittir,
// teklifleri o markanın OE ailesine süzeriz (Peugeot kodu → PSA, OPAR
// karışmaz). Belirlenemezse (kod kataloğumuzda yok) boş → kart tüm OE
// ailelerini gösterir (güvenli taban). `v` search param'ı yalnızca serbest
// metin etiket olduğundan marka için güvenilmez; yapılandırılmış brandName
// esas alınır.
const codeBrand = useMemo(() => {
const counts = new Map<string, number>();
for (const cv of catalogVehicles ?? []) {
const b = cv.brandName?.trim();
if (b) counts.set(b, (counts.get(b) ?? 0) + Math.max(1, cv.occurrences));
}
let top: string | undefined;
let best = 0;
for (const [b, n] of counts) {
if (n > best) {
best = n;
top = b;
}
}
return top;
}, [catalogVehicles]);
// Sayfadaki tüm parçaların (kod + marka) güncel tedarikçi fiyatı (tek batch // Sayfadaki tüm parçaların (kod + marka) güncel tedarikçi fiyatı (tek batch
// isteği). Marka şart: kısa sayısal kodlar markalar arası çakışır (FEBI // isteği). Marka şart: kısa sayısal kodlar markalar arası çakışır (FEBI
// 27155 ≠ GROS 27155) — sunucu teklifleri markaya süzer. Eşleşmeyen parça // 27155 ≠ GROS 27155) — sunucu teklifleri markaya süzer. Eşleşmeyen parça
@@ -164,14 +188,14 @@ function OemDetailPage() {
seen.add(k); seen.add(k);
parts.push(b ? { code: c, brand: b } : { code: c }); parts.push(b ? { code: c, brand: b } : { code: c });
}; };
push(code); // sayfanın ana OEM kodu — markasız (uzun/benzersiz kodlar eşleşir) // Ana OEM kodunun fiyatını PartPriceSection serisi gösterir — batch'e girmez.
if (data?.matched) { if (data?.matched) {
for (const a of data.articles) push(a.articleNumber, a.brand); for (const a of data.articles) push(a.articleNumber, a.brand);
for (const p of data.aftermarketParts) push(p.articleNumber, p.brand); for (const p of data.aftermarketParts) push(p.articleNumber, p.brand);
for (const oe of data.oeCrossReferences) push(oe.code, oe.brand); for (const oe of data.oeCrossReferences) push(oe.code, oe.brand);
} }
return parts.slice(0, 400); return parts.slice(0, 400);
}, [data, code]); }, [data]);
const { data: priceBatch } = useQuery({ const { data: priceBatch } = useQuery({
queryKey: ["part-prices-batch", code, priceParts.length], queryKey: ["part-prices-batch", code, priceParts.length],
@@ -259,8 +283,10 @@ function OemDetailPage() {
</header> </header>
{/* ─── Tedarikçi fiyat geçmişi (sorgulanan kodun kendisi) ────────── {/* ─── Tedarikçi fiyat geçmişi (sorgulanan kodun kendisi) ──────────
Kendi verisi yoksa kendini gizler; P eşleşmesinden bağımsız. */} Kodun araç markasına (codeBrand) süzülür → yalnız o markanın OE
<PartPriceSection code={code} /> ailesi. Marka çözümü için oem-vehicles'ın dönmesini bekleriz (çift
istek + bayat markasız iz oluşmasın); kendi verisi yoksa gizlenir. */}
{catalogVehiclesFetched && <PartPriceSection code={code} brand={codeBrand} />}
{/* ─── Loading ────────────────────────────────────────────────────── */} {/* ─── Loading ────────────────────────────────────────────────────── */}
{isLoading && ( {isLoading && (

View File

@@ -22,7 +22,11 @@ const VIN_REGEX = /^[A-HJ-NPR-Z0-9]{17}$/;
const EXAMPLE_VIN = "WVWZZZ1JZ3W597935"; const EXAMPLE_VIN = "WVWZZZ1JZ3W597935";
// Vinpin ePER background-decode polling budget (the VINPIN_ENABLED fallback). // Vinpin ePER background-decode polling budget (the VINPIN_ENABLED fallback).
const VINPIN_MAX_POLLS = 6; // A cold decode drives the Vinpin VDI and can take ~60-100s (warm ~17s), so the
// window is sized for the cold worst case: 30 × 3000ms ≈ 90s. If it still hasn't
// resolved we show a reassuring "still working" state (the decode caches
// server-side, so a later re-submit returns instantly) — NOT a hard failure.
const VINPIN_MAX_POLLS = 30;
const VINPIN_POLL_INTERVAL_MS = 3000; const VINPIN_POLL_INTERVAL_MS = 3000;
interface VehicleHistoryItem { interface VehicleHistoryItem {
@@ -173,6 +177,11 @@ function SearchPage() {
const [decoding, setDecoding] = useState<{ vin: string; display: string } | null>(null); const [decoding, setDecoding] = useState<{ vin: string; display: string } | null>(null);
const decodePollRef = useRef<number | null>(null); const decodePollRef = useRef<number | null>(null);
// Cold Vinpin decode outran the ~90s poll window. Rather than dead-ending on
// the (brand-specific) no-catalog prompt, we reassure: the decode keeps running
// and caches server-side, so a later re-submit returns instantly.
const [decodePending, setDecodePending] = useState<{ display: string } | null>(null);
const { data: history } = useQuery({ const { data: history } = useQuery({
queryKey: ["vehicles", "history"], queryKey: ["vehicles", "history"],
queryFn: () => api.get<VehicleHistoryItem[]>("/vehicles/history?limit=6"), queryFn: () => api.get<VehicleHistoryItem[]>("/vehicles/history?limit=6"),
@@ -283,12 +292,19 @@ function SearchPage() {
// Re-hit the decode endpoint until the background Vinpin decode resolves to a // Re-hit the decode endpoint until the background Vinpin decode resolves to a
// catalog vehicle, gives up (noCatalog), or we exhaust the poll budget. // catalog vehicle, gives up (noCatalog), or we exhaust the poll budget.
function startVinpinPoll(cleanVin: string, pollCount: number) { function startVinpinPoll(cleanVin: string, pollCount: number, display: string) {
if (decodePollRef.current !== null) window.clearTimeout(decodePollRef.current); if (decodePollRef.current !== null) window.clearTimeout(decodePollRef.current);
if (pollCount >= VINPIN_MAX_POLLS) { if (pollCount >= VINPIN_MAX_POLLS) {
// Took too long — fall back to a friendly model-browse prompt. // Cold decode outran the ~90s window. Do NOT drop the user onto the
// (brand-specific) no-catalog dead-end — the decode is still running and
// caches server-side, so show a reassuring "come back shortly" state.
setDecoding(null); setDecoding(null);
setNoCatalog({ brandName: "Fiat", display: "" }); setDecodePending({ display });
capture("vin_decode_vinpin_still_pending", {
vin: cleanVin,
polls: pollCount,
query_source: querySourceRef.current,
});
return; return;
} }
decodePollRef.current = window.setTimeout(async () => { decodePollRef.current = window.setTimeout(async () => {
@@ -303,13 +319,13 @@ function SearchPage() {
setDecoding(null); setDecoding(null);
setNoCatalog({ brandName: data.noCatalog.brandName, display: data.noCatalog.display }); setNoCatalog({ brandName: data.noCatalog.brandName, display: data.noCatalog.display });
} else if (data.decoding) { } else if (data.decoding) {
startVinpinPoll(cleanVin, pollCount + 1); startVinpinPoll(cleanVin, pollCount + 1, data.decoding.display ?? display);
} else { } else {
setDecoding(null); setDecoding(null);
} }
} catch { } catch {
// Transient — keep polling until the budget is exhausted. // Transient — keep polling until the budget is exhausted.
startVinpinPoll(cleanVin, pollCount + 1); startVinpinPoll(cleanVin, pollCount + 1, display);
} }
}, VINPIN_POLL_INTERVAL_MS); }, VINPIN_POLL_INTERVAL_MS);
} }
@@ -319,6 +335,7 @@ function SearchPage() {
setError(null); setError(null);
setNoCatalog(null); setNoCatalog(null);
setDecoding(null); setDecoding(null);
setDecodePending(null);
if (decodePollRef.current !== null) window.clearTimeout(decodePollRef.current); if (decodePollRef.current !== null) window.clearTimeout(decodePollRef.current);
setLoading(true); setLoading(true);
const decodeStart = performance.now(); const decodeStart = performance.now();
@@ -379,7 +396,7 @@ function SearchPage() {
response_time_ms: responseTimeMs, response_time_ms: responseTimeMs,
query_source: querySourceRef.current, query_source: querySourceRef.current,
}); });
startVinpinPoll(cleanVin, 0); startVinpinPoll(cleanVin, 0, data.decoding.display ?? "");
return; return;
} }
@@ -428,6 +445,7 @@ function SearchPage() {
e.preventDefault(); e.preventDefault();
setError(null); setError(null);
setNoCatalog(null); setNoCatalog(null);
setDecodePending(null);
const cleanVin = vin.toUpperCase().trim(); const cleanVin = vin.toUpperCase().trim();
const querySource = querySourceRef.current; const querySource = querySourceRef.current;
@@ -547,6 +565,7 @@ function SearchPage() {
setError(null); setError(null);
setNoCatalog(null); setNoCatalog(null);
setDecoding(null); setDecoding(null);
setDecodePending(null);
setReportSent(false); setReportSent(false);
if (corrections.length > 0) { if (corrections.length > 0) {
for (const c of corrections) correctionsRef.current.add(c); for (const c of corrections) correctionsRef.current.add(c);
@@ -832,6 +851,28 @@ function SearchPage() {
</div> </div>
)} )}
{/* ─── Vinpin cold-decode outran the poll window: reassure, don't fail ─ */}
{decodePending && (
<div className="rounded-2xl border border-brand/30 bg-background p-5 sm:p-6">
<div className="flex items-start gap-4">
<div className="flex size-10 shrink-0 items-center justify-center rounded-xl bg-brand/10">
<Clock className="size-5 text-brand" />
</div>
<div className="min-w-0 flex-1">
<p className="font-[family-name:var(--font-display)] text-lg font-bold">
{t("search.decodingTitle")}
</p>
{decodePending.display && (
<p className="mt-0.5 text-sm font-medium text-foreground">
{decodePending.display}
</p>
)}
<p className="mt-1 text-sm text-muted-foreground">{t("search.decodePendingHint")}</p>
</div>
</div>
</div>
)}
{/* ─── No-catalog fallback: brand known, offer model-browse ───────── */} {/* ─── No-catalog fallback: brand known, offer model-browse ───────── */}
{noCatalog && ( {noCatalog && (
<div className="rounded-2xl border border-brand/30 bg-background p-5 sm:p-6"> <div className="rounded-2xl border border-brand/30 bg-background p-5 sm:p-6">
@@ -845,7 +886,9 @@ function SearchPage() {
</p> </p>
<p className="mt-0.5 text-sm font-medium text-foreground">{noCatalog.display}</p> <p className="mt-0.5 text-sm font-medium text-foreground">{noCatalog.display}</p>
<p className="mt-1 text-sm text-muted-foreground"> <p className="mt-1 text-sm text-muted-foreground">
{t("search.noCatalogHint", { brand: noCatalog.brandName })} {noCatalog.brandName
? t("search.noCatalogHint", { brand: noCatalog.brandName })
: t("search.noCatalogHintNeutral")}
</p> </p>
</div> </div>
</div> </div>
@@ -859,7 +902,9 @@ function SearchPage() {
capture("vin_no_catalog_browse_clicked", { brand_name: noCatalog.brandName }) capture("vin_no_catalog_browse_clicked", { brand_name: noCatalog.brandName })
} }
> >
{t("search.browseCatalogCta", { brand: noCatalog.brandName })} {noCatalog.brandName
? t("search.browseCatalogCta", { brand: noCatalog.brandName })
: t("search.browseCatalogCtaNeutral")}
</Link> </Link>
</Button> </Button>
</div> </div>

View File

@@ -0,0 +1,14 @@
import { createFileRoute, redirect } from "@tanstack/react-router";
import { SETTINGS_TABS, type SettingsTab } from "../settings";
// Path-style deep links (e.g. /dashboard/settings/notifications from e-mail
// unsubscribe confirmations) — the settings page keys tabs off `?tab=`, so
// redirect there. Unknown segments fall back to the default tab.
export const Route = createFileRoute("/dashboard/settings_/$tab")({
beforeLoad: ({ params }) => {
const tab = SETTINGS_TABS.includes(params.tab as SettingsTab)
? (params.tab as SettingsTab)
: undefined;
throw redirect({ to: "/dashboard/settings", search: tab ? { tab } : {} });
},
});

View File

@@ -15,9 +15,6 @@ services:
- VITE_SENTRY_DSN=${VITE_SENTRY_DSN:-} - VITE_SENTRY_DSN=${VITE_SENTRY_DSN:-}
- VITE_SENTRY_ENVIRONMENT=${VITE_SENTRY_ENVIRONMENT:-production} - VITE_SENTRY_ENVIRONMENT=${VITE_SENTRY_ENVIRONMENT:-production}
- VITE_SENTRY_RELEASE=${VITE_SENTRY_RELEASE:-} - VITE_SENTRY_RELEASE=${VITE_SENTRY_RELEASE:-}
# Per-commit cache-bust (see Dockerfile) — Coolify substitutes the SHA so
# every commit rebuilds the bundle instead of reusing a stale cached layer.
- SOURCE_COMMIT=${SOURCE_COMMIT:-unknown}
- VITE_GOOGLE_ADS_ID=${VITE_GOOGLE_ADS_ID:-} - VITE_GOOGLE_ADS_ID=${VITE_GOOGLE_ADS_ID:-}
- VITE_GOOGLE_ADS_SIGNUP_LABEL=${VITE_GOOGLE_ADS_SIGNUP_LABEL:-} - VITE_GOOGLE_ADS_SIGNUP_LABEL=${VITE_GOOGLE_ADS_SIGNUP_LABEL:-}
environment: environment:
@@ -66,6 +63,11 @@ services:
- VINPIN_URL=${VINPIN_URL:-https://login.tr.vinpin.online} - VINPIN_URL=${VINPIN_URL:-https://login.tr.vinpin.online}
- VINPIN_USER=${VINPIN_USER:-} - VINPIN_USER=${VINPIN_USER:-}
- VINPIN_PASS=${VINPIN_PASS:-} - VINPIN_PASS=${VINPIN_PASS:-}
- VINPIN_WARM_DAEMON=${VINPIN_WARM_DAEMON:-false}
# Set to "false" to skip opening Rpartstore entirely during a known upstream
# Rpartstore outage → Renault decodes go straight to Dialogys (drops the
# per-decode launch-error probe + "Loading application..." stray + budget burn).
- VINPIN_RPARTSTORE_ENABLED=${VINPIN_RPARTSTORE_ENABLED:-true}
- POSTAL_API_URL=${POSTAL_API_URL:-} - POSTAL_API_URL=${POSTAL_API_URL:-}
- POSTAL_API_KEY=${POSTAL_API_KEY:-} - POSTAL_API_KEY=${POSTAL_API_KEY:-}
- POSTAL_FROM_ADDRESS=${POSTAL_FROM_ADDRESS:-noreply@sase.tr} - POSTAL_FROM_ADDRESS=${POSTAL_FROM_ADDRESS:-noreply@sase.tr}
@@ -75,6 +77,10 @@ services:
- NOVU_API_KEY=${NOVU_API_KEY:-} - NOVU_API_KEY=${NOVU_API_KEY:-}
- APP_PUBLIC_URL=${APP_PUBLIC_URL:-https://sase.tr} - APP_PUBLIC_URL=${APP_PUBLIC_URL:-https://sase.tr}
- MAILTRACK_SECRET=${MAILTRACK_SECRET:-} - MAILTRACK_SECRET=${MAILTRACK_SECRET:-}
# Unsubscribe links (List-Unsubscribe header + mail footer); empty secret = mailto-only
- UNSUBSCRIBE_SECRET=${UNSUBSCRIBE_SECRET:-}
- UNSUBSCRIBE_URL_BASE=${UNSUBSCRIBE_URL_BASE:-}
- UNSUBSCRIBE_EMAIL=${UNSUBSCRIBE_EMAIL:-}
# PostHog server-side analytics (payments, subscription lifecycle, $revenue). # PostHog server-side analytics (payments, subscription lifecycle, $revenue).
# Empty key → PostHogService no-ops (server-side analytics disabled). # Empty key → PostHogService no-ops (server-side analytics disabled).
- POSTHOG_API_KEY=${POSTHOG_API_KEY:-} - POSTHOG_API_KEY=${POSTHOG_API_KEY:-}
@@ -207,11 +213,18 @@ services:
- VINPIN_URL=${VINPIN_URL:-https://login.tr.vinpin.online} - VINPIN_URL=${VINPIN_URL:-https://login.tr.vinpin.online}
- VINPIN_USER=${VINPIN_USER:-} - VINPIN_USER=${VINPIN_USER:-}
- VINPIN_PASS=${VINPIN_PASS:-} - VINPIN_PASS=${VINPIN_PASS:-}
- VINPIN_WARM_DAEMON=${VINPIN_WARM_DAEMON:-false}
# Skip Rpartstore during a known upstream outage (Renault → straight to Dialogys).
- VINPIN_RPARTSTORE_ENABLED=${VINPIN_RPARTSTORE_ENABLED:-true}
# Novu lifecycle e-mail automation — the worker fires trial-ending + win-back # Novu lifecycle e-mail automation — the worker fires trial-ending + win-back
- NOVU_API_URL=${NOVU_API_URL:-https://api.bildirim.semih.ai} - NOVU_API_URL=${NOVU_API_URL:-https://api.bildirim.semih.ai}
- NOVU_API_KEY=${NOVU_API_KEY:-} - NOVU_API_KEY=${NOVU_API_KEY:-}
- APP_PUBLIC_URL=${APP_PUBLIC_URL:-https://sase.tr} - APP_PUBLIC_URL=${APP_PUBLIC_URL:-https://sase.tr}
- MAILTRACK_SECRET=${MAILTRACK_SECRET:-} - MAILTRACK_SECRET=${MAILTRACK_SECRET:-}
# Unsubscribe links (List-Unsubscribe header + mail footer); empty secret = mailto-only
- UNSUBSCRIBE_SECRET=${UNSUBSCRIBE_SECRET:-}
- UNSUBSCRIBE_URL_BASE=${UNSUBSCRIBE_URL_BASE:-}
- UNSUBSCRIBE_EMAIL=${UNSUBSCRIBE_EMAIL:-}
# PostHog server-side analytics (payments, subscription lifecycle, $revenue). # PostHog server-side analytics (payments, subscription lifecycle, $revenue).
# Empty key → PostHogService no-ops (server-side analytics disabled). # Empty key → PostHogService no-ops (server-side analytics disabled).
- POSTHOG_API_KEY=${POSTHOG_API_KEY:-} - POSTHOG_API_KEY=${POSTHOG_API_KEY:-}

View File

@@ -120,6 +120,20 @@ export const envSchema = z.object({
// HMAC secret for signed track.sase.tr click links. When unset, CTAs are passed // HMAC secret for signed track.sase.tr click links. When unset, CTAs are passed
// un-wrapped (no click tracking) — links still work. // un-wrapped (no click tracking) — links still work.
MAILTRACK_SECRET: z.string().optional(), MAILTRACK_SECRET: z.string().optional(),
// Unsubscribe (List-Unsubscribe header + body footer links). When the secret
// is unset, mails carry the mailto: variant only and one-click POSTs are
// rejected — fine for dev, must be set in prod.
UNSUBSCRIBE_SECRET: z.string().optional(),
// "" → undefined preprocess: compose ships `${VAR:-}` so unset values arrive
// as empty strings, and a bare .url()/.email() would crash boot on "".
UNSUBSCRIBE_URL_BASE: z.preprocess(
(v) => (typeof v === "string" && v.trim() === "" ? undefined : v),
z.string().url().optional(),
),
UNSUBSCRIBE_EMAIL: z.preprocess(
(v) => (typeof v === "string" && v.trim() === "" ? undefined : v),
z.string().email().default("unsubscribe@sase.tr"),
),
// OpenTelemetry // OpenTelemetry
OTEL_ENABLED: z OTEL_ENABLED: z

View File

@@ -492,6 +492,31 @@ describe("extractModelYear", () => {
// Aynı 'X' kodu, 2030 referansında artık 2029 olarak makul. // Aynı 'X' kodu, 2030 referansında artık 2029 olarak makul.
expect(extractModelYear("VF31AKFXLXM000752", 2030)).toBe(2029); expect(extractModelYear("VF31AKFXLXM000752", 2030)).toBe(2029);
}); });
// 30-yıllık döngü belirsizliği: pozisyon-10 "T" = 2026 VEYA 1996. VF1553… = eski
// (~1996) Renault 19 (sayısal tip kodu 553). Brand-only decode (model çözülmedi)
// olduğunda güncel döngünün ön kenarına pinlenmiş yıl bir önceki döngüye çekilir,
// böylece eski araç yanlış 2026 olmaz.
it("rolls an old numeric-type-code Renault (brand-only) back a cycle instead of a wrong recent year", () => {
expect(extractModelYear("VF1553K05TR596166", 2026, { modelResolved: false })).toBe(1996);
});
it("does NOT roll back without the brand-only signal (default preserves recent-cycle year)", () => {
// Model çözülmüş (opts yok) → belirsizliğe rağmen dokunulmaz; documented precedence.
expect(extractModelYear("VF1553K05TR596166", 2026)).toBe(2026);
expect(extractModelYear("VF1553K05TR596166", 2026, { modelResolved: true })).toBe(2026);
});
it("leaves a genuinely-recent (letter-led VDS) Renault unaffected even when brand-only", () => {
// VF1RJB… modern şekil (tip kodu 'R'-öncüllü) → eski-şekil heuristiği eşleşmez →
// 'T' güncel döngüde kalır (2026), yanlışlıkla 1996'ya çekilmez.
expect(extractModelYear("VF1RJB00XT5961668", 2026, { modelResolved: false })).toBe(2026);
});
it("leaves a non-Renault brand-only VIN unaffected (heuristic is Renault-scoped)", () => {
// VW (WVW…) brand-only decode → eski-Renault heuristiği kapsamı dışında → 2026.
expect(extractModelYear("WVWZZZ1JZTW597935", 2026, { modelResolved: false })).toBe(2026);
});
}); });
// --------------- utils/currency --------------- // --------------- utils/currency ---------------
@@ -673,7 +698,14 @@ describe("normalizeName (Turkish-locale title-case)", () => {
it("title-cases each segment of a hyphenated name", () => { it("title-cases each segment of a hyphenated name", () => {
expect(normalizeName("mehmet-ali")).toBe("Mehmet-Ali"); expect(normalizeName("mehmet-ali")).toBe("Mehmet-Ali");
expect(normalizeName("ANNA-MARIA")).toBe("Anna-Maria"); // Both segments are title-cased. Note the dotless "ı": under the deliberate
// Turkish locale (required so "YILMAZ" → "Yılmaz", "ÇAĞRI" → "Çağrı"), an
// uppercase Latin "I" (U+0049) lowercases to "ı" — the SAME codepoint is
// Turkish dotless-I, and there is no way to tell it apart from an intended
// international "I" in ALL-CAPS input. Turkish correctness wins for a TR product;
// "MARIA" → "Marıa" is the accepted trade-off (invariant casing would instead
// break every Turkish name, e.g. "Yilmaz"/"Çağri").
expect(normalizeName("ANNA-MARIA")).toBe("Anna-Marıa");
}); });
it("returns '' for null/undefined/whitespace-only", () => { it("returns '' for null/undefined/whitespace-only", () => {

View File

@@ -257,12 +257,55 @@ const VIN_YEAR_CODE_ANCHOR: Record<string, number> = {
* tahminidir. Servis (PL24/EMEX/NHTSA vb.) bir model yılı veriyorsa HER ZAMAN o * tahminidir. Servis (PL24/EMEX/NHTSA vb.) bir model yılı veriyorsa HER ZAMAN o
* değer kullanılmalıdır; bu fonksiyon onun yerine geçmez. * değer kullanılmalıdır; bu fonksiyon onun yerine geçmez.
*/ */
export function extractModelYear(vin: string, referenceYear?: number): number | null { export interface ExtractModelYearOptions {
/**
* Decode SADECE markayı çözebildiyse (model çözülmediyse) `false` geçilir.
* Pozisyon-10 yıl kodu 30 yılda bir tekrarlar; "T" hem 2026 hem 1996'dır ve
* VIN-only kesin bir ayrım YOKTUR. Yalnızca decode brand-only kaldığında VE VIN
* eski Renault sayısal tip-kodu şeklindeyken, güncel döngünün ön kenarına düşen
* (yani "şimdi/gelecek yıl" gibi görünen) belirsiz bir yılı bir önceki döngüye
* çekeriz — böylece 1996 model bir R19 yanlışlıkla 2026 olmaz. Model çözülen ya
* da modern-şekilli VIN'ler ETKİLENMEZ (varsayılan davranış korunur).
*/
modelResolved?: boolean;
}
/**
* Eski Renault/Dacia (pre-2000) VIN şekli: Renault akış WMI'si (VF1/VF2/VF6/VF7
* veya Dacia UU1) + sayısal-öncüllü tip kodu (VDS ilk karakteri RAKAM — ör. "553",
* "5R4"). Modern Renault VDS tip kodları harf-öncüllüdür (RJ/RF/RH gibi), bu yüzden
* bu heuristik modern araçları dışarıda bırakır. Spec kuralı değildir — bu yüzden
* yalnızca brand-only decode ile birlikte (aşağıda) tetiklenir.
*/
function isOldRenaultShape(upperVin: string): boolean {
const isRenaultWmi = /^VF[1267]/.test(upperVin) || upperVin.startsWith("UU1");
if (!isRenaultWmi) return false;
return /^[0-9]$/.test(upperVin[3] ?? "");
}
export function extractModelYear(
vin: string,
referenceYear?: number,
opts?: ExtractModelYearOptions,
): number | null {
if (!vin || vin.length < 10) return null; if (!vin || vin.length < 10) return null;
const anchor = VIN_YEAR_CODE_ANCHOR[vin.toUpperCase()[9]]; const upper = vin.toUpperCase();
const anchor = VIN_YEAR_CODE_ANCHOR[upper[9]];
if (anchor == null) return null; if (anchor == null) return null;
const cutoff = (referenceYear ?? new Date().getFullYear()) + 1; const ref = referenceYear ?? new Date().getFullYear();
const cutoff = ref + 1;
let year = anchor; let year = anchor;
while (year > cutoff) year -= 30; // imkânsız geleceği bir önceki 30-yıllık döngüye çek while (year > cutoff) year -= 30; // imkânsız geleceği bir önceki 30-yıllık döngüye çek
// 30-yıllık döngü belirsizliği (kanıtlı vaka: VF1553K05TR596166 = ~1996 Renault 19,
// pozisyon-10 "T"). Kod hem yakın-geçmiş hem ~30 yıl öncesine denk gelir ve VIN-only
// kesin bir kural yoktur. SADECE elimizde aracın eski olduğuna dair pozitif kanıt
// olduğunda — decode brand-only kaldı (model yok) VE VIN eski Renault sayısal
// tip-kodu şeklinde — güncel döngünün ön kenarına (year >= ref, yani "şimdi/gelecek")
// pinlenmiş yılı bir önceki döngüye çekeriz. Aksi halde eski bir R19 yanlış 2026 olur.
// DAR tutulur: model çözülen ya da modern-şekilli VIN'lerin yılı asla değişmez.
if (opts?.modelResolved === false && year >= ref && isOldRenaultShape(upper)) {
return year - 30;
}
return year; return year;
} }