@bytebrand/fe-ui-core-autobahn 1.0.209 → 1.0.210

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