@bytebrand/fe-ui-core-autobahn 1.0.200 → 1.0.202

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,566 +1,578 @@
1
- // Autobahn (auto.de redesign) — store-car → AutobahnCar mapper (AB-P0-6).
2
- //
3
- // PURE adapter: converts the existing fe-main "store car" (the object
4
- // `SearchResultsStore.getCarsForPage()` returns to the SRP, produced by
5
- // `transformDataForVehicles` in framework/DataTransformers.ts) into the
6
- // `AutobahnCar` view-model the new Autobahn cards consume
7
- // (components/autobahn/cards/types.ts).
8
- //
9
- // WHY a pure function with injected deps:
10
- // The Autobahn cards are pure/presentational and never touch the store. This
11
- // mapper is the single seam that reads the real payload. It is kept pure (no
12
- // store singletons imported here) so it is unit-testable and the SRP container
13
- // injects the real stores/services (imagesStore.getSupportedImageFormat,
14
- // appStore.language). Everything it needs arrives through `deps`.
15
- //
16
- // NEEDS-DATA discipline (the point of the ticket):
17
- // Fields with NO real source on the search payload are left `undefined` so the
18
- // cards render their 'Daten folgt' marker instead of a fabricated number. See
19
- // the per-field rationale in ./fieldMapping.ts. We NEVER synthesize:
20
- // drop, marketLow, marketAvg, marketHigh, watchers, views.
21
- // listPrice / savings are emitted ONLY if a real strike/list price exists.
22
- //
23
- // Every field path below was confirmed against the real code (file:line in
24
- // ./fieldMapping.ts), not guessed.
25
-
26
- import { getPriceRating, getPredictablePrice } from '../utils/priceRating';
27
- import { formatTimestamp } from '../utils/DateUtils';
28
- import { getPowerLabel } from '../utils/power';
29
-
30
- import { AutobahnCar, AutobahnPhev } from '../cards/types';
31
- import { TIER_LABELS, RatingTier, CO2_CLASSES, Co2Class } from '../constants/autobahn';
32
-
33
- /**
34
- * Last-resort placeholder shown in the carousel until the real images for a car
35
- * are loaded. The SRP container SHOULD inject the app's real no-image asset via
36
- * `deps.placeholder` (fe-main exposes PLACEHOLDER_IMAGE_LARGE_URL /
37
- * PLACEHOLDER_IMAGE_SMALL_URL in framework/constants/app.ts, both derived from
38
- * config.imagesAPI.imgUrlBase). We do NOT import that here to keep the mapper
39
- * free of app-config coupling; this empty-data-URI default just guarantees a
40
- * non-broken <img> in tests / before the container wires the real one.
41
- */
42
- export const PLACEHOLDER_IMAGE =
43
- 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
44
-
45
- /**
46
- * The app-wide no-image asset, set ONCE at app start (fe-main's index.tsx passes its
47
- * PLACEHOLDER_IMAGE_LARGE_URL, built from config.imagesAPI.imgUrlBase) — so every card that
48
- * maps a car without a photo shows the "noimage" picture, not the transparent data URI above,
49
- * without each page having to remember `deps.placeholder` (most didn't: the home page, /search,
50
- * favourites and the dashboard all rendered an empty white photo). `deps.placeholder` still
51
- * wins per call; the data URI stays the last resort (tests, an app that never sets this).
52
- */
53
- let defaultPlaceholder: string = PLACEHOLDER_IMAGE;
54
-
55
- export function setPlaceholderImage(url: string): void {
56
- defaultPlaceholder = url || PLACEHOLDER_IMAGE;
57
- }
58
-
59
- /**
60
- * Dependencies the SRP container injects. Everything here is what the mapper
61
- * needs from the outside world — keeping the function itself pure.
62
- */
63
- export interface ToAutobahnCarDeps {
64
- /**
65
- * Build a ready-to-use image URL for a car image.
66
- * Pass `imagesStore.getSupportedImageFormat` straight through (it already
67
- * picks webp/jpeg and the cached size). Signature matches ImagesStore:
68
- * (vehicleID, imageIdentifier, size) => url
69
- */
70
- getImageUrl?: (vehicleID: string, imageIdentifier: string, size: 'small' | 'medium' | 'large') => string;
71
- /**
72
- * Loaded gallery images for this car from `imagesStore.images.get(id)`
73
- * (array of { imageUrlSmall, imageUrlMedium, imageUrlLarge, imageUrl, ... }).
74
- * When present we use these real URLs; otherwise we fall back to the single
75
- * main image via getImageUrl, then to the placeholder. Never faked.
76
- */
77
- loadedImages?: Array<{ imageUrlSmall?: string; imageUrlMedium?: string; imageUrlLarge?: string; imageUrl?: string }>;
78
- /** image size used when building gallery URLs from the main image id. */
79
- imageSize?: 'small' | 'medium' | 'large';
80
- /** translator for cbd:* selector codes (fuel/gearbox). Falls back to a built-in de map, then the raw code. */
81
- t?: (key: string, options?: object) => string;
82
- /** active UI language ('de' | 'en' …). Drives de-DE vs en-IN number grouping for the EnVKV line. */
83
- language?: string;
84
- /** placeholder image URL override (defaults to the one set with setPlaceholderImage). */
85
- placeholder?: string;
86
- /**
87
- * Buyer-activity stats for this car — UserActionsAPI 'stats/viewers' response, loaded async and
88
- * keyed by carId (`searchStore.statsData.get(storeCar.id)`). Pass it straight through; absent
89
- * (not loaded yet, or no stats for this car) → viewsCount/favoritesCount stay undefined and the
90
- * gallery badge row simply omits those pills. Never fabricated.
91
- */
92
- stats?: { totalCarImpCount?: number; totalFavCount?: number };
93
- }
94
-
95
- // ---------------------------------------------------------------------------
96
- // small pure helpers
97
- // ---------------------------------------------------------------------------
98
-
99
- const DEFAULT_LANG = 'de';
100
-
101
- /** locale tag for Number#toLocaleString — de-DE (comma decimals) unless en. */
102
- function localeTag(language?: string): string {
103
- return language === 'en' ? 'en-IN' : 'de-DE';
104
- }
105
-
106
- /** finite-number coercion: accepts number | numeric string, else undefined. */
107
- function num(v: any): number | undefined {
108
- if (v == null) return undefined;
109
- const n = typeof v === 'number' ? v : Number.parseFloat(String(v));
110
- return Number.isFinite(n) ? n : undefined;
111
- }
112
-
113
- /** like num(), but 0/negative count as absent — a 0-filled consumption field is
114
- * "no data" (CBD skips zeros on enrichment), never a real figure to print. */
115
- function pos(v: any): number | undefined {
116
- const n = num(v);
117
- return n != null && n > 0 ? n : undefined;
118
- }
119
-
120
- /** fuels whose consumption is measured in kg/100 km (cbdConsumptionUnit set); Autogas/LPG is in litres. */
121
- const KG_FUELS = ['selector_fuel_naturalGas', 'selector_fuel_hydrogen', 'selector_fuel_ethanol'];
122
-
123
- /**
124
- * EnVKV combined-consumption label, fuel-aware. Electric cars consume kWh — their
125
- * l/100km fields (wltpCombined/consumptionCombined-as-liters) arrive as 0, so the
126
- * flat `l/100 km` template printed "0 l/100 km" on every EV; natural gas/hydrogen cars
127
- * measure kg. WLTP figure preferred, else NEDC — same order as before.
128
- */
129
- function consumptionLabel(consumption: any, language?: string): string {
130
- const fuel = String(consumption.fuel || '');
131
- const electric = fuel === 'selector_fuel_electrical';
132
- const val = electric
133
- ? pos(consumption.wltpPowerCombined) ?? pos(consumption.consumptionPowerCombined) ?? pos(consumption.consumptionCombined)
134
- : pos(consumption.wltpCombined) ?? pos(consumption.consumptionCombined);
135
- if (val == null) return '';
136
- const unit = electric ? 'kWh/100 km' : KG_FUELS.indexOf(fuel) >= 0 ? 'kg/100 km' : 'l/100 km';
137
- return `${val.toLocaleString(localeTag(language))} ${unit}`;
138
- }
139
-
140
- // strike-price ("UVP-Rate"/list-price) eligibility — a separate product rule from the NEU
141
- // badge's own showNewLabel (which also requires a recent modificationDate; see fe-main's
142
- // DataTransformers.ts shouldShowNewLabel). Here: as-good-as-new only — mileage under 1,000 km
143
- // AND first registration either unknown or under 12 months old. Mirrors the identical gate
144
- // added to VehicleDetailedNextPage.tsx's getFinancing() (VDP "Dein Angebot" card).
145
- const STRIKE_MAX_MILEAGE_KM = 1000;
146
- const STRIKE_MAX_AGE_MONTHS = 12;
147
- const STRIKE_AVG_MS_PER_MONTH = 1000 * 60 * 60 * 24 * 30.44;
148
-
149
- /** unix-seconds first registration (info.regDate) — unknown can't disqualify what we can't check. */
150
- function isStrikeAgeEligible(firstRegistration?: number | null): boolean {
151
- if (firstRegistration == null || !Number.isFinite(firstRegistration) || firstRegistration <= 0) return true;
152
- const ageMonths = (Date.now() - firstRegistration * 1000) / STRIKE_AVG_MS_PER_MONTH;
153
- return ageMonths < STRIKE_MAX_AGE_MONTHS;
154
- }
155
-
156
- /**
157
- * Minimal de-DE fallback for the handful of cbd:* selector codes the cards show
158
- * (fuel + gearbox). Used only when no `t` is injected (e.g. in unit tests).
159
- * The full set lives in the cbd locale dictionary (@bytebrand/i18n-dictionaries).
160
- */
161
- const CBD_DE_FALLBACK: Record<string, string> = {
162
- selector_fuel_petrol: 'Benzin',
163
- selector_fuel_diesel: 'Diesel',
164
- selector_fuel_electrical: 'Elektro',
165
- selector_fuel_ethanol: 'Ethanol',
166
- selector_fuel_hybridElectricalDiesel: 'Hybrid (Elektro / Diesel)',
167
- selector_fuel_hybridElectricalPetrol: 'Hybrid (Elektro / Benzin)',
168
- selector_fuel_hydrogen: 'Wasserstoff',
169
- selector_fuel_naturalGas: 'Erdgas',
170
- selector_gearbox_automatic: 'Automatik',
171
- selector_gearbox_manualShift: 'Manuell',
172
- selector_gearbox_semiAutomatic: 'Halbautomatik',
173
- // highlight-chip keys (DataTransformers highlights) — used when no `t` is injected
174
- multimedia_navigationSystem: 'Navigationssystem',
175
- lights_ledHeadlights: 'LED-Scheinwerfer',
176
- lights_xenonHeadlights: 'Xenon-Scheinwerfer',
177
- window_panoramicGlassRoof: 'Panoramadach',
178
- assistants_headUpDisplay: 'Head-up-Display',
179
- assistants_adaptiveCruiseControl: 'Abstandstempomat',
180
- search_seatHeating: 'Sitzheizung',
181
- selector_climatisation_automaticAirCondition: 'Klimaautomatik',
182
- selector_climatisation_airCondition: 'Klimaanlage',
183
- search_parkingAssistants: 'Einparkhilfe',
184
- selector_driveType_allWheelDrive: 'Allradantrieb',
185
- search_trailerHitch: 'Anhängerkupplung',
186
- assistants_cruiseControl: 'Tempomat',
187
- assistants_trafficSignRecognition: 'Verkehrszeichenerkennung',
188
- assistants_collisionAvoidance: 'Notbremsassistent',
189
- window_sunroof: 'Schiebedach',
190
- seats_electricAdjustable: 'Elektr. Sitze',
191
- exterior_metallic: 'Metallic-Lackierung',
192
- multimedia_handsFreePhoneSystem: 'Freisprecheinrichtung',
193
- heatingCooling_auxiliaryHeating: 'Standheizung',
194
- multimedia_bluetooth: 'Bluetooth',
195
- };
196
-
197
- /** translate a cbd:* selector code → human label — the built-in de fallback applies whenever
198
- * no `t` is injected (e.g. no i18next available). */
199
- export function cbd(code: any, t?: (key: string, options?: object) => string): string {
200
- if (code == null || code === 'N/A') return '';
201
- const key = String(code);
202
- if (t) {
203
- const out = t(`cbd:${key}`);
204
- // i18next returns the key back when missing; treat that as "no translation".
205
- if (out && out !== `cbd:${key}` && out !== key) return out;
206
- }
207
- return CBD_DE_FALLBACK[key] || key;
208
- }
209
-
210
- /**
211
- * Map the store's energy-efficiency-class selector code (or a bare letter) to a
212
- * single CO2_CLASSES letter ('A'…'G'). A+/A++/A+++ collapse to 'A' so the card's
213
- * colored InlineCls (which does CO2_CLASSES.indexOf) still resolves a band color.
214
- * Returns '' when there is no class (caller decides what to render).
215
- */
216
- export function co2ClassLetter(code: any): Co2Class | '' {
217
- if (code == null || code === 'N/A') return '';
218
- const raw = String(code);
219
- // selector_energyEfficiencyClass_appp → 'a', _ap → 'a', _b → 'b', …
220
- const m = raw.match(/selector_energyEfficiencyClass_(a|b|c|d|e|f|g)/i);
221
- const letter = (m ? m[1] : raw.replace(/\+/g, '').trim().charAt(0)).toUpperCase();
222
- return (CO2_CLASSES as readonly string[]).includes(letter) ? (letter as Co2Class) : '';
223
- }
224
-
225
- /**
226
- * Real Preisbewertung → AutobahnCar rating tone + German label.
227
- *
228
- * Source of truth (confirmed against the live SRP card,
229
- * VehicleSmallCard/VehicleInfo.tsx:160): the legacy card renders
230
- * getPriceRating(price.currentSalesPrice, price.mlCurrentSalesPricePredicted)
231
- * which returns a numeric tier using priceRatings:
232
- * 0 noRating · 1 highPrice · 2 increasedPrice · 3 fairPrice · 4 goodPrice · 5 topPrice
233
- * (constants/price.ts in this package).
234
- *
235
- * We map that real number onto the Autobahn 5-tier scale (TIER_LABELS,
236
- * components/autobahn/constants.ts), where index 0=Top … 4=Hoch:
237
- * topPrice(5)→0 'Top Preis' · goodPrice(4)→1 'Guter Preis' ·
238
- * fairPrice(3)→2 'Fairer Preis' · increasedPrice(2)→3 'Erhöht' ·
239
- * highPrice(1)→4 'Hoher Preis'.
240
- * noRating(0) has no real comparison → neutral 'Fairer Preis' (tier 2) WITHOUT a
241
- * flattering label (documented in fieldMapping.ts). The card only special-cases
242
- * the 'fair' tone (warn pill); every other tone is the good/green pill.
243
- *
244
- * AutobahnCar.rating is a free string; CarCard does `rating === 'fair' ? warn : good`.
245
- * We emit the autobahn tier key ('top'|'good'|'fair'|'raised'|'high') so the
246
- * neutral 'fair' maps to the warn pill exactly like the design intends.
247
- */
248
- const LEGACY_TO_TIER: Record<number, RatingTier> = {
249
- 5: 0, // topPrice → Top Preis
250
- 4: 1, // goodPrice → Guter Preis
251
- 3: 2, // fairPrice → Fairer Preis
252
- 2: 3, // increasedPrice → Erhöht
253
- 1: 4, // highPrice → Hoher Preis
254
- };
255
- const TIER_TONE: Record<RatingTier, string> = {
256
- 0: 'top',
257
- 1: 'good',
258
- 2: 'fair',
259
- 3: 'raised',
260
- 4: 'high',
261
- };
262
-
263
- export function mapRating(currentSalesPrice?: number, predicted?: number): { rating: string; ratingLabel: string } {
264
- const legacy = getPriceRating(currentSalesPrice as number, predicted as number); // 0..5
265
- // 0 = noRating: keep neutral (tier 2) — never invent a flattering rating.
266
- const tier: RatingTier = legacy === 0 ? 2 : LEGACY_TO_TIER[legacy] ?? 2;
267
- return { rating: TIER_TONE[tier], ratingLabel: TIER_LABELS[tier] };
268
- }
269
-
270
- /**
271
- * Map the 5-tier rating to a 2-tone signal — only 'top'/'good' read as a genuinely good deal
272
- * (green); 'fair'/'raised'/'high' all get the warn/peach tone (Figma: "Erhöhter-Preis" is
273
- * peach, not green). Pure/non-React on purpose: shared by the web card's StatChip via
274
- * cards/cardParts.tsx's re-export.
275
- */
276
- export function ratingTone(rating: string): 'good' | 'warn' {
277
- return rating === 'top' || rating === 'good' ? 'good' : 'warn';
278
- }
279
-
280
- /** Is this car a plug-in hybrid? Determined by fuel type, mirroring ADV-88 in VehicleInfo.tsx. */
281
- function isPluginHybrid(fuel: any): boolean {
282
- return fuel === 'selector_fuel_hybridElectricalDiesel' || fuel === 'selector_fuel_hybridElectricalPetrol';
283
- }
284
-
285
- /** Build the gallery URL list from real images, falling back to main image, then placeholder.
286
- * `sizeOverride` lets a caller ask for a different size than `deps.imageSize` (e.g. a full-res
287
- * set for a lightbox, while the card thumbnail itself stays on the smaller default). */
288
- function buildGallery(storeCar: any, deps: ToAutobahnCarDeps, sizeOverride?: 'small' | 'medium' | 'large'): string[] {
289
- const placeholder = deps.placeholder || defaultPlaceholder;
290
- // Only 'small' and 'large' variants are pre-generated by image-generator; 'medium' has no cached file.
291
- const size = sizeOverride || deps.imageSize || 'small';
292
-
293
- // 1) Real loaded images from imagesStore.images.get(id).
294
- if (Array.isArray(deps.loadedImages) && deps.loadedImages.length) {
295
- const urls = deps.loadedImages
296
- .map((img) =>
297
- size === 'large'
298
- ? img.imageUrlLarge || img.imageUrlMedium || img.imageUrl
299
- : size === 'small'
300
- ? img.imageUrlSmall || img.imageUrlMedium || img.imageUrl
301
- : img.imageUrlMedium || img.imageUrlLarge || img.imageUrl
302
- )
303
- .filter((u): u is string => !!u);
304
- if (urls.length) return urls;
305
- }
306
-
307
- // 2) Not loaded yet, but we have a main image id + a URL builder → single real image.
308
- const id = storeCar.id;
309
- const mainImageId = storeCar.mainImageId;
310
- const hasImages = num(storeCar.imagesCount);
311
- if (deps.getImageUrl && id && mainImageId && hasImages) {
312
- const url = deps.getImageUrl(id, mainImageId, size);
313
- if (url) return [url];
314
- }
315
-
316
- // 3) Nothing real yet — single placeholder (never a fabricated photo).
317
- return [placeholder];
318
- }
319
-
320
- /** Build the optional PHEV EnVKV sub-block when the car is a plug-in hybrid and weighted data exists. */
321
- function buildPhev(storeCar: any, language?: string): AutobahnPhev | undefined {
322
- const c = storeCar.consumption || {};
323
- const e = storeCar.environmentEmissions || {};
324
- if (!isPluginHybrid(c.fuel)) return undefined;
325
-
326
- const consEl = num(c.wltpWeightedPowerCombined) ?? num(c.consumptionPowerCombined);
327
- const consFuel = num(c.wltpWeightedCombined);
328
- const consDis = num(c.wltpCombined) ?? num(c.consumptionCombined);
329
- const co2w = num(e.wltpCo2) ?? num(e.co2);
330
- const clsW = co2ClassLetter(e.wltpEnergyEfficiencyClass);
331
- const clsD = co2ClassLetter(e.wltpDischargedEnergyEfficiencyClass);
332
-
333
- // Only emit the dual PHEV line when we actually have the weighted figures the
334
- // EcoLine PHEV branch needs; otherwise let the normal single line render.
335
- if (consEl == null || consFuel == null || co2w == null) return undefined;
336
-
337
- return {
338
- consEl: `${consEl.toLocaleString(localeTag(language))} kWh/100 km`,
339
- consFuel: `${consFuel.toLocaleString(localeTag(language))} l/100 km`,
340
- consDis: consDis != null ? `${consDis.toLocaleString(localeTag(language))} l/100 km` : '–',
341
- co2w: `${co2w.toLocaleString(localeTag(language))} g/km`,
342
- co2classW: clsW || '–',
343
- co2classD: clsD || clsW || '–',
344
- };
345
- }
346
-
347
- // ---------------------------------------------------------------------------
348
- // main mapper
349
- // ---------------------------------------------------------------------------
350
-
351
- /**
352
- * Convert one fe-main store car → AutobahnCar.
353
- *
354
- * @param storeCar the object from SearchResultsStore.getCarsForPage()
355
- * (shape = transformDataForVehicles output). `any` because the store car is
356
- * itself untyped (`getCarsForPage: (page) => any[]`).
357
- * @param deps injected services/locale (see ToAutobahnCarDeps). Optional so the
358
- * mapper still runs in tests with zero wiring (gallery → placeholder, labels →
359
- * built-in de fallback).
360
- */
361
- export function toAutobahnCar(storeCar: any, deps: ToAutobahnCarDeps = {}): AutobahnCar {
362
- const language = deps.language || DEFAULT_LANG;
363
- const t = deps.t;
364
-
365
- const title = storeCar.title || {};
366
- const info = storeCar.info || {};
367
- const engineData = storeCar.engineData || {};
368
- const consumption = storeCar.consumption || {};
369
- const emissions = storeCar.environmentEmissions || {};
370
- const price = storeCar.price || {};
371
-
372
- // --- price / monthly (REQUIRED) ---
373
- // monthly ← price.financing.monthlyInstallment. This is the financing rate
374
- // produced by FinancingStore via getComputedFinancing(config).financing
375
- // (getFinancing.ts:82 `monthlyInstallment`), spread into price.financing by
376
- // transformDataForVehicles (DataTransformers.ts:345). It is the LEAD price.
377
- const monthly = num(price?.financing?.monthlyInstallment) ?? 0;
378
- // financing terms the monthly rate was computed with — same merged per-car
379
- // config (dealer rate + the user's saved localStorage adjustments, ADV-157).
380
- // Emitted only when real; the cards fall back to the default-config terms.
381
- // paybackPeriod FIRST: it carries the user's saved term, while rawPaybackPeriod
382
- // is stamped from the dealer rate at normalize time and never reflects
383
- // adjustments (normalizeRateObject.ts `rawPaybackPeriod: paybackPeriod`).
384
- const finFirstInstallment = num(price?.financing?.firstInstallment);
385
- const finMonths = num(price?.financing?.paybackPeriod) ?? num(price?.financing?.rawPaybackPeriod);
386
- // price ← price.currentSalesPrice (DataTransformers.ts:352).
387
- const purchase = num(price?.currentSalesPrice) ?? 0;
388
-
389
- // --- rating (REQUIRED-WHEN-PRICED) ← real Preisbewertung ---
390
- // BL-08 (P1, MONEY): getPriceRating(0, 0) mathematically resolves to tier 5
391
- // ("Top Preis" — the BEST possible rating). Its internal min/max bands are all
392
- // `predicted * (1 ± pct)`, which collapse to 0 when predicted is 0, and the
393
- // topPrice branch checks `currentSalesPrice <= min` — 0 <= 0 is true. A
394
- // missing/broken price payload must NEVER get dressed up as the best deal on
395
- // the lot. Only compute/emit a rating when there is a real, positive sales
396
- // price; otherwise rating/ratingLabel stay '' (falsy) — every consumer
397
- // (CarCard.tsx, cardParts.tsx, FinanceCalculator.tsx) already treats a falsy
398
- // rating as "no badge", so no type change is needed here.
399
- const predicted =
400
- purchase > 0 ? getPredictablePrice(purchase, num(price?.mlCurrentSalesPricePredicted) as number) : undefined;
401
- const { rating, ratingLabel } = purchase > 0 ? mapRating(purchase, predicted) : { rating: '', ratingLabel: '' };
402
-
403
- // --- key specs ---
404
- const powerKW = num(engineData.powerKW);
405
- const powerPS = num(engineData.powerPS);
406
- const power = getPowerLabel(powerKW as number, powerPS as number); // "150 kW (204 PS)"
407
-
408
- const regTs = num(info.regDate);
409
- const reg = regTs ? formatTimestamp({ timestamp: regTs, format: 'MM/YYYY' }) : '';
410
-
411
- const ownersN = num(info.numberOfPreviousOwners);
412
-
413
- // --- EnVKV consumption line (REQUIRED on every German car ad) ---
414
- // Prefer WLTP figures when present (the legacy cards do too), else NEDC.
415
- const co2Val = num(emissions.wltpCo2) ?? num(emissions.co2);
416
- const cons = consumptionLabel(consumption, language);
417
- const co2 = co2Val != null ? `${co2Val.toLocaleString(localeTag(language))} g/km` : '';
418
- const co2class = co2ClassLetter(emissions.wltpEnergyEfficiencyClass);
419
- const phev = buildPhev(storeCar, language);
420
-
421
- // --- media ---
422
- const gallery = buildGallery(storeCar, deps);
423
- // Card grids ask for a smaller `imageSize` (perf) — but a lightbox opened FROM that card
424
- // (CarCard's photo-count pill → VdpViewer) shouldn't be stuck showing the small thumbnails
425
- // blown up full-screen. Build a real full-res set alongside, from the same already-loaded
426
- // images (no extra fetch) — only when the requested size isn't already 'large'.
427
- const galleryLarge = (deps.imageSize || 'small') !== 'large' ? buildGallery(storeCar, deps, 'large') : undefined;
428
- const photos = num(storeCar.imagesCount) ?? 0;
429
-
430
- // --- optional: leasing rate — ONLY when leasing is actually active for this car.
431
- // SearchResultsStore.getCarsForPage stamps price.leasing.isActive via getLeasingActive
432
- // (car age + mileage within the leasing limits). Legacy SRP shows "Leasing ---" when
433
- // inactive; we mirror that by leaving `lease` undefined so PricePaths omits the row
434
- // (instead of computing/showing a leasing rate the car isn't eligible for).
435
- const leasingActive = !!(price && price.leasing && price.leasing.isActive);
436
- const lease = leasingActive ? num(price?.leasing?.monthlyInstallment) : undefined;
437
- // leasing terms the lease rate was computed with — same merged per-car config
438
- // as the financing terms above (annualMileage/paybackPeriod carry the user's
439
- // saved adjustments). Only meaningful alongside an active lease rate.
440
- const leaseMileage = leasingActive ? num(price?.leasing?.annualMileage) : undefined;
441
- const leaseMonths = leasingActive ? num(price?.leasing?.paybackPeriod) : undefined;
442
- const leaseFirstInstallment = leasingActive ? num(price?.leasing?.firstInstallment) : undefined;
443
-
444
- // --- optional: list price / savings — ONLY from a real strike price ---
445
- // transformDataForVehicles exposes oldMonthlyInstallment / highestPrice via
446
- // the financing spread, and price.historyPriceDifference. There is NO reliable
447
- // purchase-price strike on the search payload today, so we leave listPrice /
448
- // savings UNDEFINED unless a real highestPrice strike exists above the sale
449
- // price. See fieldMapping.ts — flagged for backend confirmation.
450
- // asGoodAsNew — mileage (info.mileage, same source as `km` below) + regTs (info.regDate,
451
- // same raw timestamp as `reg` above) gate: see isStrikeAgeEligible.
452
- const asGoodAsNew = Number(num(info.mileage) ?? 0) < STRIKE_MAX_MILEAGE_KM && isStrikeAgeEligible(regTs);
453
- const isStrikeShown = !!price?.financing?.isStrikeShown && asGoodAsNew;
454
- const highest = num(price?.financing?.highestPrice) ?? num(price?.highestPrice);
455
- let listPrice: number | undefined;
456
- let savings: number | undefined;
457
- if (isStrikeShown && highest != null && purchase > 0 && highest > purchase) {
458
- listPrice = highest;
459
- savings = highest - purchase;
460
- }
461
-
462
- // --- struck-through old rate per payment path — same isStrikeShown gate as the Kaufen
463
- // strike above. getFinancing.ts/getLeasing.ts each compute their own real
464
- // oldMonthlyInstallment from the same common.highestPrice; only emitted when the tabbed
465
- // hero price actually has something real to strike against.
466
- const oldMonthly = isStrikeShown ? num(price?.financing?.oldMonthlyInstallment) : undefined;
467
- const oldLease = isStrikeShown && leasingActive ? num(price?.leasing?.oldMonthlyInstallment) : undefined;
468
-
469
- // --- price drop (REAL) — mirrors the legacy SRL green "−X €" badge: show the reduction only
470
- // when price.historyPriceDifference is a meaningful amount (≥ 500 €, the legacy threshold).
471
- const histDrop = num(price?.historyPriceDifference);
472
- const drop = histDrop != null && histDrop >= 500 ? histDrop : undefined;
473
- // percent reduction (historyPriceDifferencePerCent) — paired with `drop` for the −X% badge.
474
- const histPct = num(price?.historyPriceDifferencePerCent);
475
- const dropPct = drop != null && histPct != null && histPct > 0 ? Math.round(histPct) : undefined;
476
-
477
- // --- NEU badge (REAL) — the legacy showNewLabel flag carried on the store car. ---
478
- const isNew = !!storeCar.showNewLabel;
479
-
480
- // --- availability (REAL) — offer.availabilityMode. 'always' → immediately available. ---
481
- const offer = storeCar.offer && typeof storeCar.offer === 'object' ? storeCar.offer : {};
482
- const availability =
483
- offer.availabilityMode === 'selector_availabilityMode_always'
484
- ? t
485
- ? t('autobahn:availability.immediately')
486
- : 'Sofort verfügbar'
487
- : undefined;
488
- // 0 € Anzahlung available — transform sets offer.showDownPayment = (raw showDownPayment && zero first installment).
489
- const zeroDown = !!offer.showDownPayment;
490
-
491
- // --- gallery activity strip (REAL) — UserActionsAPI 'stats/viewers', injected via deps.stats. ---
492
- const viewsCount = num(deps.stats?.totalCarImpCount);
493
- const favoritesCount = num(deps.stats?.totalFavCount);
494
-
495
- const carView: AutobahnCar = {
496
- // identity / headline
497
- make: String(title.make ?? ''),
498
- model: String(title.model ?? ''),
499
- trim: String(title.subModel ?? ''),
500
-
501
- // key specs
502
- km: num(info.mileage) ?? 0,
503
- reg,
504
- power,
505
- fuel: cbd(consumption.fuel, t),
506
- gear: cbd(info.gearbox, t),
507
- owners: ownersN ?? 0,
508
-
509
- // price
510
- monthly,
511
- ...(finFirstInstallment != null ? { finFirstInstallment } : {}),
512
- ...(finMonths != null ? { finMonths } : {}),
513
- price: purchase,
514
-
515
- // media
516
- gallery,
517
- ...(galleryLarge ? { galleryLarge } : {}),
518
- photos,
519
-
520
- // EnVKV
521
- cons,
522
- co2,
523
- co2class: co2class || '',
524
- ...(phev ? { phev } : {}),
525
-
526
- // trust / features — equipment highlight chips (Matrix-LED, Virtual Cockpit, AHK, ACC, …).
527
- // transformDataForVehicles extracted the present highlight selector-keys via getActualHighlights
528
- // (reading the raw equipment categories); translate them to labels here (cbd → t('cbd:<key>')).
529
- // First 4, like the design's card. Empty when the car has no notable equipment.
530
- features: (Array.isArray((storeCar as any).highlights) ? (storeCar as any).highlights : [])
531
- .map((k: any) => cbd(k, t))
532
- .filter((s: string) => !!s)
533
- .slice(0, 4),
534
- rating,
535
- ratingLabel,
536
-
537
- // optional (only when real)
538
- // full spec+equipment footer line — pass through as-is when the caller already built it
539
- // (fe-landing's transformSearchResultItem); no fallback assembly here, since the exact
540
- // seoFields/highlights order is caller-specific (see AutobahnCar.seoText's own comment).
541
- ...(typeof (storeCar as any).seoText === 'string' && (storeCar as any).seoText ? { seoText: (storeCar as any).seoText } : {}),
542
- ...(listPrice != null ? { listPrice } : {}),
543
- ...(savings != null ? { savings } : {}),
544
- ...(oldMonthly != null && oldMonthly > monthly ? { oldMonthly } : {}),
545
- ...(oldLease != null && lease != null && oldLease > lease ? { oldLease } : {}),
546
- ...(lease != null ? { lease } : {}),
547
- ...(leaseMileage != null ? { leaseMileage } : {}),
548
- ...(leaseMonths != null ? { leaseMonths } : {}),
549
- ...(leaseFirstInstallment != null ? { leaseFirstInstallment } : {}),
550
- ...(drop != null ? { drop } : {}),
551
- ...(dropPct != null ? { dropPct } : {}),
552
- ...(zeroDown ? { zeroDown } : {}),
553
- ...(isNew ? { isNew } : {}),
554
- asGoodAsNew,
555
- ...(availability ? { availability } : {}),
556
- ...(viewsCount != null ? { viewsCount } : {}),
557
- ...(favoritesCount != null ? { favoritesCount } : {}),
558
-
559
- // NEEDS-DATA: deliberately omitted (marketLow, marketAvg, marketHigh, watchers, views).
560
- // The cards render 'Daten folgt' for these until a real backend exists.
561
- };
562
-
563
- return carView;
564
- }
565
-
566
- export default toAutobahnCar;
1
+ // Autobahn (auto.de redesign) — store-car → AutobahnCar mapper (AB-P0-6).
2
+ //
3
+ // PURE adapter: converts the existing fe-main "store car" (the object
4
+ // `SearchResultsStore.getCarsForPage()` returns to the SRP, produced by
5
+ // `transformDataForVehicles` in framework/DataTransformers.ts) into the
6
+ // `AutobahnCar` view-model the new Autobahn cards consume
7
+ // (components/autobahn/cards/types.ts).
8
+ //
9
+ // WHY a pure function with injected deps:
10
+ // The Autobahn cards are pure/presentational and never touch the store. This
11
+ // mapper is the single seam that reads the real payload. It is kept pure (no
12
+ // store singletons imported here) so it is unit-testable and the SRP container
13
+ // injects the real stores/services (imagesStore.getSupportedImageFormat,
14
+ // appStore.language). Everything it needs arrives through `deps`.
15
+ //
16
+ // NEEDS-DATA discipline (the point of the ticket):
17
+ // Fields with NO real source on the search payload are left `undefined` so the
18
+ // cards render their 'Daten folgt' marker instead of a fabricated number. See
19
+ // the per-field rationale in ./fieldMapping.ts. We NEVER synthesize:
20
+ // drop, marketLow, marketAvg, marketHigh, watchers, views.
21
+ // listPrice / savings are emitted ONLY if a real strike/list price exists.
22
+ //
23
+ // Every field path below was confirmed against the real code (file:line in
24
+ // ./fieldMapping.ts), not guessed.
25
+
26
+ import { getPriceRating, getPredictablePrice } from '../utils/priceRating';
27
+ import { formatTimestamp } from '../utils/DateUtils';
28
+ import { getPowerLabel } from '../utils/power';
29
+
30
+ import { AutobahnCar, AutobahnPhev } from '../cards/types';
31
+ import { TIER_LABELS, RatingTier, CO2_CLASSES, Co2Class } from '../constants/autobahn';
32
+
33
+ /**
34
+ * Last-resort placeholder shown in the carousel until the real images for a car
35
+ * are loaded. The SRP container SHOULD inject the app's real no-image asset via
36
+ * `deps.placeholder` (fe-main exposes PLACEHOLDER_IMAGE_LARGE_URL /
37
+ * PLACEHOLDER_IMAGE_SMALL_URL in framework/constants/app.ts, both derived from
38
+ * config.imagesAPI.imgUrlBase). We do NOT import that here to keep the mapper
39
+ * free of app-config coupling; this empty-data-URI default just guarantees a
40
+ * non-broken <img> in tests / before the container wires the real one.
41
+ */
42
+ export const PLACEHOLDER_IMAGE =
43
+ 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
44
+
45
+ /**
46
+ * The app-wide no-image asset, set ONCE at app start (fe-main's index.tsx passes its
47
+ * PLACEHOLDER_IMAGE_LARGE_URL, built from config.imagesAPI.imgUrlBase) — so every card that
48
+ * maps a car without a photo shows the "noimage" picture, not the transparent data URI above,
49
+ * without each page having to remember `deps.placeholder` (most didn't: the home page, /search,
50
+ * favourites and the dashboard all rendered an empty white photo). `deps.placeholder` still
51
+ * wins per call; the data URI stays the last resort (tests, an app that never sets this).
52
+ */
53
+ let defaultPlaceholder: string = PLACEHOLDER_IMAGE;
54
+
55
+ export function setPlaceholderImage(url: string): void {
56
+ defaultPlaceholder = url || PLACEHOLDER_IMAGE;
57
+ }
58
+
59
+ /**
60
+ * Dependencies the SRP container injects. Everything here is what the mapper
61
+ * needs from the outside world — keeping the function itself pure.
62
+ */
63
+ export interface ToAutobahnCarDeps {
64
+ /**
65
+ * Build a ready-to-use image URL for a car image.
66
+ * Pass `imagesStore.getSupportedImageFormat` straight through (it already
67
+ * picks webp/jpeg and the cached size). Signature matches ImagesStore:
68
+ * (vehicleID, imageIdentifier, size) => url
69
+ */
70
+ getImageUrl?: (vehicleID: string, imageIdentifier: string, size: 'small' | 'medium' | 'large') => string;
71
+ /**
72
+ * Loaded gallery images for this car from `imagesStore.images.get(id)`
73
+ * (array of { imageUrlSmall, imageUrlMedium, imageUrlLarge, imageUrl, ... }).
74
+ * When present we use these real URLs; otherwise we fall back to the single
75
+ * main image via getImageUrl, then to the placeholder. Never faked.
76
+ */
77
+ loadedImages?: Array<{ imageUrlSmall?: string; imageUrlMedium?: string; imageUrlLarge?: string; imageUrl?: string }>;
78
+ /** image size used when building gallery URLs from the main image id. */
79
+ imageSize?: 'small' | 'medium' | 'large';
80
+ /** translator for cbd:* selector codes (fuel/gearbox). Falls back to a built-in de map, then the raw code. */
81
+ t?: (key: string, options?: object) => string;
82
+ /** active UI language ('de' | 'en' …). Drives de-DE vs en-IN number grouping for the EnVKV line. */
83
+ language?: string;
84
+ /** placeholder image URL override (defaults to the one set with setPlaceholderImage). */
85
+ placeholder?: string;
86
+ /**
87
+ * Buyer-activity stats for this car — UserActionsAPI 'stats/viewers' response, loaded async and
88
+ * keyed by carId (`searchStore.statsData.get(storeCar.id)`). Pass it straight through; absent
89
+ * (not loaded yet, or no stats for this car) → viewsCount/favoritesCount stay undefined and the
90
+ * gallery badge row simply omits those pills. Never fabricated.
91
+ */
92
+ stats?: { totalCarImpCount?: number; totalFavCount?: number };
93
+ }
94
+
95
+ // ---------------------------------------------------------------------------
96
+ // small pure helpers
97
+ // ---------------------------------------------------------------------------
98
+
99
+ const DEFAULT_LANG = 'de';
100
+
101
+ /** locale tag for Number#toLocaleString — de-DE (comma decimals) unless en. */
102
+ function localeTag(language?: string): string {
103
+ return language === 'en' ? 'en-IN' : 'de-DE';
104
+ }
105
+
106
+ /** finite-number coercion: accepts number | numeric string, else undefined. */
107
+ function num(v: any): number | undefined {
108
+ if (v == null) return undefined;
109
+ const n = typeof v === 'number' ? v : Number.parseFloat(String(v));
110
+ return Number.isFinite(n) ? n : undefined;
111
+ }
112
+
113
+ /** like num(), but 0/negative count as absent — a 0-filled consumption field is
114
+ * "no data" (CBD skips zeros on enrichment), never a real figure to print. */
115
+ function pos(v: any): number | undefined {
116
+ const n = num(v);
117
+ return n != null && n > 0 ? n : undefined;
118
+ }
119
+
120
+ /** fuels whose consumption is measured in kg/100 km (cbdConsumptionUnit set); Autogas/LPG is in litres. */
121
+ const KG_FUELS = ['selector_fuel_naturalGas', 'selector_fuel_hydrogen', 'selector_fuel_ethanol'];
122
+
123
+ /**
124
+ * EnVKV combined-consumption label, fuel-aware. Electric cars consume kWh — their
125
+ * l/100km fields (wltpCombined/consumptionCombined-as-liters) arrive as 0, so the
126
+ * flat `l/100 km` template printed "0 l/100 km" on every EV; natural gas/hydrogen cars
127
+ * measure kg. WLTP figure preferred, else NEDC — same order as before.
128
+ */
129
+ function consumptionLabel(consumption: any, language?: string): string {
130
+ const fuel = String(consumption.fuel || '');
131
+ const electric = fuel === 'selector_fuel_electrical';
132
+ const val = electric
133
+ ? pos(consumption.wltpPowerCombined) ?? pos(consumption.consumptionPowerCombined) ?? pos(consumption.consumptionCombined)
134
+ : pos(consumption.wltpCombined) ?? pos(consumption.consumptionCombined);
135
+ if (val == null) return '';
136
+ const unit = electric ? 'kWh/100 km' : KG_FUELS.indexOf(fuel) >= 0 ? 'kg/100 km' : 'l/100 km';
137
+ return `${val.toLocaleString(localeTag(language))} ${unit}`;
138
+ }
139
+
140
+ // strike-price ("UVP-Rate"/list-price) eligibility — a separate product rule from the NEU
141
+ // badge's own showNewLabel (which also requires a recent modificationDate; see fe-main's
142
+ // DataTransformers.ts shouldShowNewLabel). Here: as-good-as-new only — mileage under 1,000 km
143
+ // AND first registration either unknown or under 12 months old. Mirrors the identical gate
144
+ // added to VehicleDetailedNextPage.tsx's getFinancing() (VDP "Dein Angebot" card).
145
+ const STRIKE_MAX_MILEAGE_KM = 1000;
146
+ const STRIKE_MAX_AGE_MONTHS = 12;
147
+ const STRIKE_AVG_MS_PER_MONTH = 1000 * 60 * 60 * 24 * 30.44;
148
+
149
+ /** unix-seconds first registration (info.regDate) — unknown can't disqualify what we can't check. */
150
+ function isStrikeAgeEligible(firstRegistration?: number | null): boolean {
151
+ if (firstRegistration == null || !Number.isFinite(firstRegistration) || firstRegistration <= 0) return true;
152
+ const ageMonths = (Date.now() - firstRegistration * 1000) / STRIKE_AVG_MS_PER_MONTH;
153
+ return ageMonths < STRIKE_MAX_AGE_MONTHS;
154
+ }
155
+
156
+ /**
157
+ * Minimal de-DE fallback for the handful of cbd:* selector codes the cards show
158
+ * (fuel + gearbox). Used only when no `t` is injected (e.g. in unit tests).
159
+ * The full set lives in the cbd locale dictionary (@bytebrand/i18n-dictionaries).
160
+ */
161
+ const CBD_DE_FALLBACK: Record<string, string> = {
162
+ selector_fuel_petrol: 'Benzin',
163
+ selector_fuel_diesel: 'Diesel',
164
+ selector_fuel_electrical: 'Elektro',
165
+ selector_fuel_ethanol: 'Ethanol',
166
+ selector_fuel_hybridElectricalDiesel: 'Hybrid (Elektro / Diesel)',
167
+ selector_fuel_hybridElectricalPetrol: 'Hybrid (Elektro / Benzin)',
168
+ selector_fuel_hydrogen: 'Wasserstoff',
169
+ selector_fuel_naturalGas: 'Erdgas',
170
+ selector_gearbox_automatic: 'Automatik',
171
+ selector_gearbox_manualShift: 'Manuell',
172
+ selector_gearbox_semiAutomatic: 'Halbautomatik',
173
+ // highlight-chip keys (DataTransformers highlights) — used when no `t` is injected
174
+ multimedia_navigationSystem: 'Navigationssystem',
175
+ lights_ledHeadlights: 'LED-Scheinwerfer',
176
+ lights_xenonHeadlights: 'Xenon-Scheinwerfer',
177
+ window_panoramicGlassRoof: 'Panoramadach',
178
+ assistants_headUpDisplay: 'Head-up-Display',
179
+ assistants_adaptiveCruiseControl: 'Abstandstempomat',
180
+ search_seatHeating: 'Sitzheizung',
181
+ selector_climatisation_automaticAirCondition: 'Klimaautomatik',
182
+ selector_climatisation_airCondition: 'Klimaanlage',
183
+ search_parkingAssistants: 'Einparkhilfe',
184
+ selector_driveType_allWheelDrive: 'Allradantrieb',
185
+ search_trailerHitch: 'Anhängerkupplung',
186
+ assistants_cruiseControl: 'Tempomat',
187
+ assistants_trafficSignRecognition: 'Verkehrszeichenerkennung',
188
+ assistants_collisionAvoidance: 'Notbremsassistent',
189
+ window_sunroof: 'Schiebedach',
190
+ seats_electricAdjustable: 'Elektr. Sitze',
191
+ exterior_metallic: 'Metallic-Lackierung',
192
+ multimedia_handsFreePhoneSystem: 'Freisprecheinrichtung',
193
+ heatingCooling_auxiliaryHeating: 'Standheizung',
194
+ multimedia_bluetooth: 'Bluetooth',
195
+ };
196
+
197
+ /** translate a cbd:* selector code → human label — the built-in de fallback applies whenever
198
+ * no `t` is injected (e.g. no i18next available). */
199
+ export function cbd(code: any, t?: (key: string, options?: object) => string): string {
200
+ if (code == null || code === 'N/A') return '';
201
+ const key = String(code);
202
+ if (t) {
203
+ const out = t(`cbd:${key}`);
204
+ // i18next returns the key back when missing; treat that as "no translation".
205
+ if (out && out !== `cbd:${key}` && out !== key) return out;
206
+ }
207
+ return CBD_DE_FALLBACK[key] || key;
208
+ }
209
+
210
+ /**
211
+ * Map the store's energy-efficiency-class selector code (or a bare letter) to a
212
+ * single CO2_CLASSES letter ('A'…'G'). A+/A++/A+++ collapse to 'A' so the card's
213
+ * colored InlineCls (which does CO2_CLASSES.indexOf) still resolves a band color.
214
+ * Returns '' when there is no class (caller decides what to render).
215
+ */
216
+ export function co2ClassLetter(code: any): Co2Class | '' {
217
+ if (code == null || code === 'N/A') return '';
218
+ const raw = String(code);
219
+ // selector_energyEfficiencyClass_appp → 'a', _ap → 'a', _b → 'b', …
220
+ const m = raw.match(/selector_energyEfficiencyClass_(a|b|c|d|e|f|g)/i);
221
+ const letter = (m ? m[1] : raw.replace(/\+/g, '').trim().charAt(0)).toUpperCase();
222
+ return (CO2_CLASSES as readonly string[]).includes(letter) ? (letter as Co2Class) : '';
223
+ }
224
+
225
+ /**
226
+ * Real Preisbewertung → AutobahnCar rating tone + German label.
227
+ *
228
+ * Source of truth (confirmed against the live SRP card,
229
+ * VehicleSmallCard/VehicleInfo.tsx:160): the legacy card renders
230
+ * getPriceRating(price.currentSalesPrice, price.mlCurrentSalesPricePredicted)
231
+ * which returns a numeric tier using priceRatings:
232
+ * 0 noRating · 1 highPrice · 2 increasedPrice · 3 fairPrice · 4 goodPrice · 5 topPrice
233
+ * (constants/price.ts in this package).
234
+ *
235
+ * We map that real number onto the Autobahn 5-tier scale (TIER_LABELS,
236
+ * components/autobahn/constants.ts), where index 0=Top … 4=Hoch:
237
+ * topPrice(5)→0 'Top Preis' · goodPrice(4)→1 'Guter Preis' ·
238
+ * fairPrice(3)→2 'Fairer Preis' · increasedPrice(2)→3 'Erhöht' ·
239
+ * highPrice(1)→4 'Hoher Preis'.
240
+ * noRating(0) has no real comparison → neutral 'Fairer Preis' (tier 2) WITHOUT a
241
+ * flattering label (documented in fieldMapping.ts). The card only special-cases
242
+ * the 'fair' tone (warn pill); every other tone is the good/green pill.
243
+ *
244
+ * AutobahnCar.rating is a free string; CarCard does `rating === 'fair' ? warn : good`.
245
+ * We emit the autobahn tier key ('top'|'good'|'fair'|'raised'|'high') so the
246
+ * neutral 'fair' maps to the warn pill exactly like the design intends.
247
+ */
248
+ const LEGACY_TO_TIER: Record<number, RatingTier> = {
249
+ 5: 0, // topPrice → Top Preis
250
+ 4: 1, // goodPrice → Guter Preis
251
+ 3: 2, // fairPrice → Fairer Preis
252
+ 2: 3, // increasedPrice → Erhöht
253
+ 1: 4, // highPrice → Hoher Preis
254
+ };
255
+ const TIER_TONE: Record<RatingTier, string> = {
256
+ 0: 'top',
257
+ 1: 'good',
258
+ 2: 'fair',
259
+ 3: 'raised',
260
+ 4: 'high',
261
+ };
262
+
263
+ export function mapRating(currentSalesPrice?: number, predicted?: number): { rating: string; ratingLabel: string } {
264
+ const legacy = getPriceRating(currentSalesPrice as number, predicted as number); // 0..5
265
+ // 0 = noRating: keep neutral (tier 2) — never invent a flattering rating.
266
+ const tier: RatingTier = legacy === 0 ? 2 : LEGACY_TO_TIER[legacy] ?? 2;
267
+ return { rating: TIER_TONE[tier], ratingLabel: TIER_LABELS[tier] };
268
+ }
269
+
270
+ /**
271
+ * Map the 5-tier rating to a 2-tone signal — only 'top'/'good' read as a genuinely good deal
272
+ * (green); 'fair'/'raised'/'high' all get the warn/peach tone (Figma: "Erhöhter-Preis" is
273
+ * peach, not green). Pure/non-React on purpose: shared by the web card's StatChip via
274
+ * cards/cardParts.tsx's re-export.
275
+ */
276
+ export function ratingTone(rating: string): 'good' | 'warn' {
277
+ return rating === 'top' || rating === 'good' ? 'good' : 'warn';
278
+ }
279
+
280
+ /** Is this car a plug-in hybrid? Determined by fuel type, mirroring ADV-88 in VehicleInfo.tsx. */
281
+ function isPluginHybrid(fuel: any): boolean {
282
+ return fuel === 'selector_fuel_hybridElectricalDiesel' || fuel === 'selector_fuel_hybridElectricalPetrol';
283
+ }
284
+
285
+ /** Build the gallery URL list from real images, falling back to main image, then placeholder.
286
+ * `sizeOverride` lets a caller ask for a different size than `deps.imageSize` (e.g. a full-res
287
+ * set for a lightbox, while the card thumbnail itself stays on the smaller default). */
288
+ function buildGallery(storeCar: any, deps: ToAutobahnCarDeps, sizeOverride?: 'small' | 'medium' | 'large'): string[] {
289
+ const placeholder = deps.placeholder || defaultPlaceholder;
290
+ // Only 'small' and 'large' variants are pre-generated by image-generator; 'medium' has no cached file.
291
+ const size = sizeOverride || deps.imageSize || 'small';
292
+
293
+ // 1) Real loaded images from imagesStore.images.get(id).
294
+ if (Array.isArray(deps.loadedImages) && deps.loadedImages.length) {
295
+ const urls = deps.loadedImages
296
+ .map((img) =>
297
+ size === 'large'
298
+ ? img.imageUrlLarge || img.imageUrlMedium || img.imageUrl
299
+ : size === 'small'
300
+ ? img.imageUrlSmall || img.imageUrlMedium || img.imageUrl
301
+ : img.imageUrlMedium || img.imageUrlLarge || img.imageUrl
302
+ )
303
+ .filter((u): u is string => !!u);
304
+ if (urls.length) return urls;
305
+ }
306
+
307
+ // 2) Not loaded yet, but we have a main image id + a URL builder → single real image.
308
+ const id = storeCar.id;
309
+ const mainImageId = storeCar.mainImageId;
310
+ const hasImages = num(storeCar.imagesCount);
311
+ if (deps.getImageUrl && id && mainImageId && hasImages) {
312
+ const url = deps.getImageUrl(id, mainImageId, size);
313
+ if (url) return [url];
314
+ }
315
+
316
+ // 3) Nothing real yet — single placeholder (never a fabricated photo).
317
+ return [placeholder];
318
+ }
319
+
320
+ /** Build the optional PHEV EnVKV sub-block when the car is a plug-in hybrid and weighted data exists. */
321
+ function buildPhev(storeCar: any, language?: string): AutobahnPhev | undefined {
322
+ const c = storeCar.consumption || {};
323
+ const e = storeCar.environmentEmissions || {};
324
+ if (!isPluginHybrid(c.fuel)) return undefined;
325
+
326
+ const consEl = num(c.wltpWeightedPowerCombined) ?? num(c.consumptionPowerCombined);
327
+ const consFuel = num(c.wltpWeightedCombined);
328
+ const consDis = num(c.wltpCombined) ?? num(c.consumptionCombined);
329
+ const co2w = num(e.wltpCo2) ?? num(e.co2);
330
+ const clsW = co2ClassLetter(e.wltpEnergyEfficiencyClass);
331
+ const clsD = co2ClassLetter(e.wltpDischargedEnergyEfficiencyClass);
332
+
333
+ // Only emit the dual PHEV line when we actually have the weighted figures the
334
+ // EcoLine PHEV branch needs; otherwise let the normal single line render.
335
+ if (consEl == null || consFuel == null || co2w == null) return undefined;
336
+
337
+ return {
338
+ consEl: `${consEl.toLocaleString(localeTag(language))} kWh/100 km`,
339
+ consFuel: `${consFuel.toLocaleString(localeTag(language))} l/100 km`,
340
+ consDis: consDis != null ? `${consDis.toLocaleString(localeTag(language))} l/100 km` : '–',
341
+ co2w: `${co2w.toLocaleString(localeTag(language))} g/km`,
342
+ co2classW: clsW || '–',
343
+ co2classD: clsD || clsW || '–',
344
+ };
345
+ }
346
+
347
+ // ---------------------------------------------------------------------------
348
+ // main mapper
349
+ // ---------------------------------------------------------------------------
350
+
351
+ /**
352
+ * Convert one fe-main store car → AutobahnCar.
353
+ *
354
+ * @param storeCar the object from SearchResultsStore.getCarsForPage()
355
+ * (shape = transformDataForVehicles output). `any` because the store car is
356
+ * itself untyped (`getCarsForPage: (page) => any[]`).
357
+ * @param deps injected services/locale (see ToAutobahnCarDeps). Optional so the
358
+ * mapper still runs in tests with zero wiring (gallery → placeholder, labels →
359
+ * built-in de fallback).
360
+ */
361
+ export function toAutobahnCar(storeCar: any, deps: ToAutobahnCarDeps = {}): AutobahnCar {
362
+ const language = deps.language || DEFAULT_LANG;
363
+ const t = deps.t;
364
+
365
+ const title = storeCar.title || {};
366
+ const info = storeCar.info || {};
367
+ const engineData = storeCar.engineData || {};
368
+ const consumption = storeCar.consumption || {};
369
+ const emissions = storeCar.environmentEmissions || {};
370
+ const price = storeCar.price || {};
371
+
372
+ // --- price / monthly (REQUIRED) ---
373
+ // monthly ← price.financing.monthlyInstallment. This is the financing rate
374
+ // produced by FinancingStore via getComputedFinancing(config).financing
375
+ // (getFinancing.ts:82 `monthlyInstallment`), spread into price.financing by
376
+ // transformDataForVehicles (DataTransformers.ts:345). It is the LEAD price.
377
+ const monthly = num(price?.financing?.monthlyInstallment) ?? 0;
378
+ // financing terms the monthly rate was computed with — same merged per-car
379
+ // config (dealer rate + the user's saved localStorage adjustments, ADV-157).
380
+ // Emitted only when real; the cards fall back to the default-config terms.
381
+ // paybackPeriod FIRST: it carries the user's saved term, while rawPaybackPeriod
382
+ // is stamped from the dealer rate at normalize time and never reflects
383
+ // adjustments (normalizeRateObject.ts `rawPaybackPeriod: paybackPeriod`).
384
+ const finFirstInstallment = num(price?.financing?.firstInstallment);
385
+ const finMonths = num(price?.financing?.paybackPeriod) ?? num(price?.financing?.rawPaybackPeriod);
386
+ // ADV-405 key figures of that same computed financing (getFinancing output), as the
387
+ // Finanzierungsdetails layer shows them.
388
+ const finNetLoan = num(price?.financing?.netLoanAmount);
389
+ const finTotal = num(price?.financing?.totalFinancingAmount) ?? num(price?.financing?.grossLoanAmount);
390
+ const finNominal = num(price?.financing?.nominalInterestRate);
391
+ const finApr = num(price?.financing?.annualPercentageRate);
392
+ const finFinal = num(price?.financing?.finalInstallment);
393
+ // price ← price.currentSalesPrice (DataTransformers.ts:352).
394
+ const purchase = num(price?.currentSalesPrice) ?? 0;
395
+
396
+ // --- rating (REQUIRED-WHEN-PRICED) ← real Preisbewertung ---
397
+ // BL-08 (P1, MONEY): getPriceRating(0, 0) mathematically resolves to tier 5
398
+ // ("Top Preis" — the BEST possible rating). Its internal min/max bands are all
399
+ // `predicted * (1 ± pct)`, which collapse to 0 when predicted is 0, and the
400
+ // topPrice branch checks `currentSalesPrice <= min` — 0 <= 0 is true. A
401
+ // missing/broken price payload must NEVER get dressed up as the best deal on
402
+ // the lot. Only compute/emit a rating when there is a real, positive sales
403
+ // price; otherwise rating/ratingLabel stay '' (falsy) — every consumer
404
+ // (CarCard.tsx, cardParts.tsx, FinanceCalculator.tsx) already treats a falsy
405
+ // rating as "no badge", so no type change is needed here.
406
+ const predicted =
407
+ purchase > 0 ? getPredictablePrice(purchase, num(price?.mlCurrentSalesPricePredicted) as number) : undefined;
408
+ const { rating, ratingLabel } = purchase > 0 ? mapRating(purchase, predicted) : { rating: '', ratingLabel: '' };
409
+
410
+ // --- key specs ---
411
+ const powerKW = num(engineData.powerKW);
412
+ const powerPS = num(engineData.powerPS);
413
+ const power = getPowerLabel(powerKW as number, powerPS as number); // "150 kW (204 PS)"
414
+
415
+ const regTs = num(info.regDate);
416
+ const reg = regTs ? formatTimestamp({ timestamp: regTs, format: 'MM/YYYY' }) : '';
417
+
418
+ const ownersN = num(info.numberOfPreviousOwners);
419
+
420
+ // --- EnVKV consumption line (REQUIRED on every German car ad) ---
421
+ // Prefer WLTP figures when present (the legacy cards do too), else NEDC.
422
+ const co2Val = num(emissions.wltpCo2) ?? num(emissions.co2);
423
+ const cons = consumptionLabel(consumption, language);
424
+ const co2 = co2Val != null ? `${co2Val.toLocaleString(localeTag(language))} g/km` : '';
425
+ const co2class = co2ClassLetter(emissions.wltpEnergyEfficiencyClass);
426
+ const phev = buildPhev(storeCar, language);
427
+
428
+ // --- media ---
429
+ const gallery = buildGallery(storeCar, deps);
430
+ // Card grids ask for a smaller `imageSize` (perf) — but a lightbox opened FROM that card
431
+ // (CarCard's photo-count pill → VdpViewer) shouldn't be stuck showing the small thumbnails
432
+ // blown up full-screen. Build a real full-res set alongside, from the same already-loaded
433
+ // images (no extra fetch) — only when the requested size isn't already 'large'.
434
+ const galleryLarge = (deps.imageSize || 'small') !== 'large' ? buildGallery(storeCar, deps, 'large') : undefined;
435
+ const photos = num(storeCar.imagesCount) ?? 0;
436
+
437
+ // --- optional: leasing rate — ONLY when leasing is actually active for this car.
438
+ // SearchResultsStore.getCarsForPage stamps price.leasing.isActive via getLeasingActive
439
+ // (car age + mileage within the leasing limits). Legacy SRP shows "Leasing ---" when
440
+ // inactive; we mirror that by leaving `lease` undefined so PricePaths omits the row
441
+ // (instead of computing/showing a leasing rate the car isn't eligible for).
442
+ const leasingActive = !!(price && price.leasing && price.leasing.isActive);
443
+ const lease = leasingActive ? num(price?.leasing?.monthlyInstallment) : undefined;
444
+ // leasing terms the lease rate was computed with — same merged per-car config
445
+ // as the financing terms above (annualMileage/paybackPeriod carry the user's
446
+ // saved adjustments). Only meaningful alongside an active lease rate.
447
+ const leaseMileage = leasingActive ? num(price?.leasing?.annualMileage) : undefined;
448
+ const leaseMonths = leasingActive ? num(price?.leasing?.paybackPeriod) : undefined;
449
+ const leaseFirstInstallment = leasingActive ? num(price?.leasing?.firstInstallment) : undefined;
450
+
451
+ // --- optional: list price / savings — ONLY from a real strike price ---
452
+ // transformDataForVehicles exposes oldMonthlyInstallment / highestPrice via
453
+ // the financing spread, and price.historyPriceDifference. There is NO reliable
454
+ // purchase-price strike on the search payload today, so we leave listPrice /
455
+ // savings UNDEFINED unless a real highestPrice strike exists above the sale
456
+ // price. See fieldMapping.ts — flagged for backend confirmation.
457
+ // asGoodAsNew — mileage (info.mileage, same source as `km` below) + regTs (info.regDate,
458
+ // same raw timestamp as `reg` above) gate: see isStrikeAgeEligible.
459
+ const asGoodAsNew = Number(num(info.mileage) ?? 0) < STRIKE_MAX_MILEAGE_KM && isStrikeAgeEligible(regTs);
460
+ const isStrikeShown = !!price?.financing?.isStrikeShown && asGoodAsNew;
461
+ const highest = num(price?.financing?.highestPrice) ?? num(price?.highestPrice);
462
+ let listPrice: number | undefined;
463
+ let savings: number | undefined;
464
+ if (isStrikeShown && highest != null && purchase > 0 && highest > purchase) {
465
+ listPrice = highest;
466
+ savings = highest - purchase;
467
+ }
468
+
469
+ // --- struck-through old rate per payment path — same isStrikeShown gate as the Kaufen
470
+ // strike above. getFinancing.ts/getLeasing.ts each compute their own real
471
+ // oldMonthlyInstallment from the same common.highestPrice; only emitted when the tabbed
472
+ // hero price actually has something real to strike against.
473
+ const oldMonthly = isStrikeShown ? num(price?.financing?.oldMonthlyInstallment) : undefined;
474
+ const oldLease = isStrikeShown && leasingActive ? num(price?.leasing?.oldMonthlyInstallment) : undefined;
475
+
476
+ // --- price drop (REAL) — mirrors the legacy SRL green "−X €" badge: show the reduction only
477
+ // when price.historyPriceDifference is a meaningful amount (≥ 500 €, the legacy threshold).
478
+ const histDrop = num(price?.historyPriceDifference);
479
+ const drop = histDrop != null && histDrop >= 500 ? histDrop : undefined;
480
+ // percent reduction (historyPriceDifferencePerCent) — paired with `drop` for the −X% badge.
481
+ const histPct = num(price?.historyPriceDifferencePerCent);
482
+ const dropPct = drop != null && histPct != null && histPct > 0 ? Math.round(histPct) : undefined;
483
+
484
+ // --- NEU badge (REAL) — the legacy showNewLabel flag carried on the store car. ---
485
+ const isNew = !!storeCar.showNewLabel;
486
+
487
+ // --- availability (REAL) — offer.availabilityMode. 'always' → immediately available. ---
488
+ const offer = storeCar.offer && typeof storeCar.offer === 'object' ? storeCar.offer : {};
489
+ const availability =
490
+ offer.availabilityMode === 'selector_availabilityMode_always'
491
+ ? t
492
+ ? t('autobahn:availability.immediately')
493
+ : 'Sofort verfügbar'
494
+ : undefined;
495
+ // 0 € Anzahlung available — transform sets offer.showDownPayment = (raw showDownPayment && zero first installment).
496
+ const zeroDown = !!offer.showDownPayment;
497
+
498
+ // --- gallery activity strip (REAL) — UserActionsAPI 'stats/viewers', injected via deps.stats. ---
499
+ const viewsCount = num(deps.stats?.totalCarImpCount);
500
+ const favoritesCount = num(deps.stats?.totalFavCount);
501
+
502
+ const carView: AutobahnCar = {
503
+ // identity / headline
504
+ make: String(title.make ?? ''),
505
+ model: String(title.model ?? ''),
506
+ trim: String(title.subModel ?? ''),
507
+
508
+ // key specs
509
+ km: num(info.mileage) ?? 0,
510
+ reg,
511
+ power,
512
+ fuel: cbd(consumption.fuel, t),
513
+ gear: cbd(info.gearbox, t),
514
+ owners: ownersN ?? 0,
515
+
516
+ // price
517
+ monthly,
518
+ ...(finFirstInstallment != null ? { finFirstInstallment } : {}),
519
+ ...(finMonths != null ? { finMonths } : {}),
520
+ ...(finNetLoan != null ? { finNetLoan } : {}),
521
+ ...(finTotal != null ? { finTotal } : {}),
522
+ ...(finNominal != null ? { finNominal } : {}),
523
+ ...(finApr != null ? { finApr } : {}),
524
+ ...(finFinal != null ? { finFinal } : {}),
525
+ price: purchase,
526
+
527
+ // media
528
+ gallery,
529
+ ...(galleryLarge ? { galleryLarge } : {}),
530
+ photos,
531
+
532
+ // EnVKV
533
+ cons,
534
+ co2,
535
+ co2class: co2class || '',
536
+ ...(phev ? { phev } : {}),
537
+
538
+ // trust / features — equipment highlight chips (Matrix-LED, Virtual Cockpit, AHK, ACC, …).
539
+ // transformDataForVehicles extracted the present highlight selector-keys via getActualHighlights
540
+ // (reading the raw equipment categories); translate them to labels here (cbd → t('cbd:<key>')).
541
+ // First 4, like the design's card. Empty when the car has no notable equipment.
542
+ features: (Array.isArray((storeCar as any).highlights) ? (storeCar as any).highlights : [])
543
+ .map((k: any) => cbd(k, t))
544
+ .filter((s: string) => !!s)
545
+ .slice(0, 4),
546
+ rating,
547
+ ratingLabel,
548
+
549
+ // optional (only when real)
550
+ // full spec+equipment footer line — pass through as-is when the caller already built it
551
+ // (fe-landing's transformSearchResultItem); no fallback assembly here, since the exact
552
+ // seoFields/highlights order is caller-specific (see AutobahnCar.seoText's own comment).
553
+ ...(typeof (storeCar as any).seoText === 'string' && (storeCar as any).seoText ? { seoText: (storeCar as any).seoText } : {}),
554
+ ...(listPrice != null ? { listPrice } : {}),
555
+ ...(savings != null ? { savings } : {}),
556
+ ...(oldMonthly != null && oldMonthly > monthly ? { oldMonthly } : {}),
557
+ ...(oldLease != null && lease != null && oldLease > lease ? { oldLease } : {}),
558
+ ...(lease != null ? { lease } : {}),
559
+ ...(leaseMileage != null ? { leaseMileage } : {}),
560
+ ...(leaseMonths != null ? { leaseMonths } : {}),
561
+ ...(leaseFirstInstallment != null ? { leaseFirstInstallment } : {}),
562
+ ...(drop != null ? { drop } : {}),
563
+ ...(dropPct != null ? { dropPct } : {}),
564
+ ...(zeroDown ? { zeroDown } : {}),
565
+ ...(isNew ? { isNew } : {}),
566
+ asGoodAsNew,
567
+ ...(availability ? { availability } : {}),
568
+ ...(viewsCount != null ? { viewsCount } : {}),
569
+ ...(favoritesCount != null ? { favoritesCount } : {}),
570
+
571
+ // NEEDS-DATA: deliberately omitted (marketLow, marketAvg, marketHigh, watchers, views).
572
+ // The cards render 'Daten folgt' for these until a real backend exists.
573
+ };
574
+
575
+ return carView;
576
+ }
577
+
578
+ export default toAutobahnCar;