diff --git a/CLAUDE.md b/CLAUDE.md index f730980..138a60d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -70,7 +70,7 @@ Android is accepted as the cost of leaving a working path alone. ## Catalog data -`data/catalog_vehicles.json` holds 170 trims (EV, hybrid, PHEV only; no petrol-only cars). +`data/catalog_vehicles.json` holds 171 trims (EV, hybrid, PHEV only; no petrol-only cars). paultan.org is the source of record (`registered_basis: paultan_exact`), and most catalog `id`s are paultan slugs (about 25 are not, e.g. `mg4` = `mg-4`, `smart-1` = `smart-smart-1`). Its compare pages order columns by price, not URL order, and show each model's entry variant, @@ -87,12 +87,26 @@ specs at the petrol base price; check the variant table on the model's paultan p certified kW (the figure in each `road_tax_note`); a horsepower conversion lands on the wrong side of a 10 kW band edge. Hybrids and PHEVs use `ice_road_tax(cc, non_saloon)`. +Servicing: 24 rows carry a published figure; the rest use the price-band fit in +`engines._maintenance_fallback`. Rows filled from 2026-11-14 hold `maintenance_5yr_rm` (the +distributor's own schedule or prepaid package over five years / 100,000 km, which the engine +reads), `maintenance_rm_yr` (its rounded fifth) and `maintenance_note` (what was counted, the +document and its date). Sources that work: honda.com.my/doc/maintenance/ PDFs, the +emas.proton.com/services-e-mas-*/ tables, UMW Toyota price lists (Toyota Service Savers). +Run `scripts/build_provenance.py --apply` after adding one so the note reaches provenance. + ## Docs - `DEPLOYMENT.md`: Vercel projects, secrets, migrations (`RUN_MIGRATIONS=0` on Vercel), Large Functions, the daily refresh. - `frontend/DESIGN.md`: the design and motion contract. Read before any UI or animation change; the visual identity is preserved, not replaced. +- `data/policy/*.md`: the analyst's and the chat's policy brief, loaded whole into both prompts. + `home-energy.md` holds TNB ToU, NEM vs Solar ATAP and solar with a battery; + `malaysia-incentives.md` holds incentives, fuel and the BUDI95 quota. Dated; recheck before + quoting. The solar banner is computed by `backend/app/services/solar.py` from + `data/solar_avg.json` assumptions and `tariff.json`, and the BUDI95 quota lives in + `data/fuel.json` under `budi95` (set by hand: the daily fuel refresh leaves it alone). - `issue.md`: the measured defect log for the TOPSIS engine (`backend/app/engines/`, `backend/app/services/scoring.py`). Read before changing scoring. - `FEATURES.md`: proposed features, in suggested order. diff --git a/backend/app/engines/engines.py b/backend/app/engines/engines.py index fa1a485..e18996b 100644 --- a/backend/app/engines/engines.py +++ b/backend/app/engines/engines.py @@ -793,9 +793,19 @@ def maintenance_rm_yr(vehicle: dict) -> tuple[float, str]: Returns the basis alongside the number, the same shape as resale_retained_pct, so the results page can tell a reader which of the two - it is looking at. 16 of 170 trims are measured. + it is looking at. 24 of 171 trims are measured (14 Nov 2026), and those are + the ones most buyers are looking at: the best-selling models were filled + first. """ - measured = (vehicle.get("ownership") or {}).get("maintenance_rm_yr") + own = vehicle.get("ownership") or {} + # A published five-year total (the distributor's schedule or prepaid + # package, with its source in maintenance_note) is the figure itself; the + # annual one is that divided by five, so read it here rather than the + # rounded annual copy beside it. + five_year = own.get("maintenance_5yr_rm") + if five_year: + return float(five_year) / 5.0, "measured" + measured = own.get("maintenance_rm_yr") if measured: return float(measured), "measured" return _maintenance_fallback(vehicle), "estimated" @@ -1137,6 +1147,35 @@ def _charger_efficiency(tariff: dict) -> float: return float(tariff.get("home_household_assumptions", {}).get("charger_efficiency", 0.9) or 0.9) +def petrol_cost_rm(litres_yr: float, fuel: dict) -> float: + """A year of RON95, with BUDI95's monthly quota. + + BUDI95 sells an eligible Malaysian RON95 at the subsidised pump price only + up to a monthly quota (300 L since 1 Sep 2026); every litre past it is paid + at the unsubsidised price. Pricing every litre at RM1.99 told a high-mileage + buyer of a thirsty hybrid that petrol stays cheap however far they drive, + and that is the case where the cap bites: a 9 L/100 km car passes 3,600 L at + 40,000 km a year. + + The quota is applied to the year's litres averaged over twelve months. A + month with a long trip can pass the quota in a year that does not, so this + slightly understates the cost for lumpy driving. It assumes the buyer is + eligible and that this car has their whole quota to itself; both are in + data/policy/malaysia-incentives.md for the analyst to say out loud. + + `fuel` is the scenario block from services.energy_context. The "market" + scenario carries no quota, since every litre is already at market price. + """ + litres = max(0.0, float(litres_yr)) + subsidised = float(fuel["ron95_rm_per_l"]) + quota = fuel.get("ron95_quota_l_yr") + over = fuel.get("ron95_over_quota_rm_per_l") + if not quota or over is None: + return litres * subsidised + within = min(litres, float(quota)) + return within * subsidised + (litres - within) * float(over) + + def energy_engine(vehicle: dict, profile: dict, feature: dict, energy: dict) -> dict: annual = feature["annual_km"] tariff = energy["tariff"] @@ -1206,13 +1245,13 @@ def _electricity_cost(drawn_kwh_yr: float, extra_home_kwh_yr: float = 0.0) -> fl kwh_yr = (annual / 100) * kwh100 * ev_share litres_yr = (annual / 100) * l100 * (1 - ev_share) drawn = kwh_yr / eff - cost = _electricity_cost(drawn) + litres_yr * float(fuel["ron95_rm_per_l"]) + cost = _electricity_cost(drawn) + petrol_cost_rm(litres_yr, fuel) co2_yr = drawn * grid_co2 + litres_yr * float(co2["petrol"]) else: l100 = float(specs.get("fuel_l_per_100km", 5.0) or 5.0) kwh_yr = 0.0 litres_yr = (annual / 100) * l100 - cost = litres_yr * float(fuel["ron95_rm_per_l"]) + cost = petrol_cost_rm(litres_yr, fuel) co2_yr = litres_yr * float(co2["petrol"]) return { diff --git a/backend/app/routers/config.py b/backend/app/routers/config.py index 433df43..b323998 100644 --- a/backend/app/routers/config.py +++ b/backend/app/routers/config.py @@ -2,7 +2,8 @@ from fastapi import APIRouter -from ..config import load_solar, load_sponsor +from ..config import load_sponsor +from ..services.solar import solar_estimate from ..schemas import INTERVIEW_QUESTIONS router = APIRouter(prefix="/config", tags=["config"]) @@ -16,7 +17,7 @@ async def interview_script() -> dict: @router.get("/solar") async def solar() -> dict: - return {"solar": load_solar()} + return {"solar": solar_estimate()} @router.get("/sponsor") diff --git a/backend/app/routers/report.py b/backend/app/routers/report.py index ec9c7cc..1f73d72 100644 --- a/backend/app/routers/report.py +++ b/backend/app/routers/report.py @@ -12,7 +12,8 @@ from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession -from ..config import load_solar, settings +from ..config import settings +from ..services.solar import solar_estimate from ..db import Profile, Recommendation, ReportRequest, TopsisResult, get_db from ..schemas import ReportRequest as ReportRequestSchema from ..services.report_pdf import MYT, build_pdf @@ -68,7 +69,7 @@ async def email_report(body: ReportRequestSchema, db: AsyncSession = Depends(get lang = str((profile_row.profile_json or {}).get("language", "en")).lower() subject = ("Laporan keputusan VoltPilot anda" if lang == "bm" else "Your VoltPilot decision report") - solar = load_solar() if result.overview_json.get("solar_eligible") else None + solar = solar_estimate() if result.overview_json.get("solar_eligible") else None pdf = build_pdf({ "token": body.result_token, "profile": profile_row.profile_json, diff --git a/backend/app/routers/results.py b/backend/app/routers/results.py index 8188c6a..99b797e 100644 --- a/backend/app/routers/results.py +++ b/backend/app/routers/results.py @@ -2,6 +2,7 @@ import asyncio import logging +import math import time from datetime import datetime @@ -9,7 +10,8 @@ from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession -from ..config import brand_contact, load_policy_markdown, load_solar, settings +from ..config import brand_contact, load_policy_markdown, settings +from ..services.solar import solar_estimate from ..db import ( AsyncSessionLocal, MindChange, Profile, Recommendation, ResultTiming, TopsisResult, get_db, ) @@ -85,7 +87,7 @@ async def get_results(token: str, db: AsyncSession = Depends(get_db)): # scoring time so the page does not re-run 400 rankings on every read. "stability": result.overview_json.get("stability"), "fuel_scenario": result.overview_json.get("fuel_scenario", "subsidised"), - "solar": load_solar() if result.overview_json.get("solar_eligible") else None, + "solar": solar_estimate() if result.overview_json.get("solar_eligible") else None, "profile": profile_row.profile_json if profile_row else None, "recommendation": recommendation.analyst_json if recommendation else None, # Where to actually go and buy the thing. Attached per ranked row rather @@ -129,7 +131,9 @@ async def _build_and_store(token: str, db: AsyncSession) -> Recommendation: "weights": result.weights, "ranking": result.ranking_json, "features": result.overview_json.get("features", {}), - "solar": result.overview_json.get("solar_eligible", False), + # The figures, not a flag: the analyst echoes this as solar_banner, and + # given only True it had nothing true to echo. + "solar": solar_estimate() if result.overview_json.get("solar_eligible") else None, "policy_context": load_policy_markdown(), } analyst = await build_recommendation(bundle, lang) @@ -291,7 +295,35 @@ async def get_breakeven(token: str, db: AsyncSession = Depends(get_db)): name: breakeven_km_per_year(ev, hybrid, energy_context(name), profile, features) for name in ("subsidised", "market") } - return {"token": token, "available": True, "scenarios": scenarios} + # What the panel says about BUDI95, from data rather than from copy: the + # copy said RM3.77 long after fuel.json moved to RM3.87. + from ..engines.engines import energy_engine + + sub = energy_context("subsidised")["fuel"] + litres_yr = energy_engine(hybrid, profile, features, energy_context("subsidised"))["litres_yr"] + fuel = { + "ron95_rm_per_l": float(sub["ron95_rm_per_l"]), + "ron95_market_rm_per_l": float(energy_context("market")["fuel"]["ron95_rm_per_l"]), + "quota_l_month": (float(sub["ron95_quota_l_yr"]) / 12 + if sub.get("ron95_quota_l_yr") else None), + "hybrid_litres_month": round(float(litres_yr) / 12, 0), + } + # The chart: every mileage from zero to twice the buyer's, at least 40,000 + # km and never past the 100,000 km break-even ceiling. + from ..services.costing import five_year_cost_curve + + yours = float(features.get("annual_km", 0) or 0) + max_km = min(100_000.0, max(40_000.0, math.ceil(yours * 2 / 10_000) * 10_000)) + curve = five_year_cost_curve( + ev, hybrid, {name: energy_context(name) for name in ("subsidised", "market")}, + profile, features, max_km, + ) + names = { + "ev": " ".join(x for x in (ev.get("brand"), ev.get("model")) if x), + "hybrid": " ".join(x for x in (hybrid.get("brand"), hybrid.get("model")) if x), + } + return {"token": token, "available": True, "scenarios": scenarios, "fuel": fuel, + "curve": curve, "names": names} @router.get("/{token}/compare") diff --git a/backend/app/services/__init__.py b/backend/app/services/__init__.py index 5c6b938..8ad842e 100644 --- a/backend/app/services/__init__.py +++ b/backend/app/services/__init__.py @@ -26,6 +26,13 @@ def energy_context(scenario: str = "subsidised") -> dict: tariff = load_tariff() fuel = load_fuel() fuel_block = dict(fuel["fuel"]) + # BUDI95: the pump price holds only up to the monthly quota; litres past + # it are paid at market. engines.petrol_cost_rm reads these two keys. + quota_month = float((fuel.get("budi95") or {}).get("quota_l_per_month") or 0) + market_ron95 = (fuel.get("market_rm_per_l") or {}).get("ron95") + if scenario == "subsidised" and quota_month > 0 and market_ron95: + fuel_block["ron95_quota_l_yr"] = quota_month * 12 + fuel_block["ron95_over_quota_rm_per_l"] = float(market_ron95) if scenario == "market": market = fuel.get("market_rm_per_l") or {} if market.get("ron95"): diff --git a/backend/app/services/analyst.py b/backend/app/services/analyst.py index fc97f27..4397e2f 100644 --- a/backend/app/services/analyst.py +++ b/backend/app/services/analyst.py @@ -16,7 +16,7 @@ from datetime import datetime, timedelta, timezone from typing import Any -from ..config import load_fuel, settings +from ..config import load_fuel, load_policy_markdown, settings from ..schemas import INTERVIEW_QUESTIONS logger = logging.getLogger(__name__) @@ -330,6 +330,9 @@ async def gemini_analyst(bundle: dict, lang: str) -> dict | None: ) ) data = _extract_json(resp.text or "") + # The banner's figures are computed (services/solar.py), so they are copied + # in rather than trusted to the model, which had been inventing its own. + data["solar_banner"] = bundle.get("solar") or None if not data.get("top_hybrid_slug"): hybrid = next((r for r in bundle["ranking"] if r["type"] == "hybrid"), None) if hybrid: @@ -362,9 +365,69 @@ async def build_recommendation(bundle: dict, lang: str) -> dict: # --------------------------------------------------------------------------- CHAT_SYSTEM = """You are the friendly analyst for the Malaysian EV-vs-hybrid platform. -You see the user's profile, ranking and roadmap. Answer concisely (under 150 words). -If asked about battery degradation, explain it as a warning only (it does not change the -score). Reply in the user's language ({lang}).""" +You see the user's profile, their top five cars and the roadmap, plus a policy brief. +Answer concisely (under 150 words) and reply in the user's language ({lang}). + +- Use the numbers you are given. Each car carries body, specs (seats, boot_l, range_km, + battery_kwh, fuel_l_per_100km) and cost_breakdown_5yr: the five-year cost lines in RM, + including "maintenance". cost_breakdown_5yr.maintenance_basis says whether servicing is + the brand's published schedule ("measured", source in maintenance_note) or the engine's + estimate from drivetrain and price ("estimated"); say which when you quote it. litres_yr + is the car's yearly petrol at the buyer's mileage. +- Family questions: compare seats, boot_l and body across the top five, then say which fits. +- Policy, tariffs, fuel quota, ToU, solar schemes (NEM, Solar ATAP) and home batteries: + answer from the policy brief only. If it does not cover the question, say you do not know + rather than guess, and point to TNB, SEDA or the Energy Commission. +- Battery degradation is a warning only; it does not change the score. +- Never invent prices, rebates or dates.""" + + +_CHAT_SPECS = ("seats", "boot_l", "range_km", "battery_kwh", "energy_kwh_per_100km", + "fuel_l_per_100km", "charge_power_kw_dc", "power_hp") + + +def _chat_car(row: dict) -> dict: + """The part of a ranking row the chat answers from. + + A full row is about 3,400 characters, most of it provenance strings and + insurance and loan notes no buyer asks about, and five of them made the + chat prompt slow enough to brush the 20 s call limit and fall back to the + canned reply. This keeps what the system prompt promises the model. + """ + specs = row.get("specs") or {} + breakdown = row.get("cost_breakdown_5yr") or {} + own = row.get("ownership") or {} + return { + "rank": row.get("rank"), + "car": " ".join(str(x) for x in (row.get("brand"), row.get("model"), row.get("variant")) if x), + "type": row.get("type"), + "body": row.get("body"), + "price_rm": row.get("price_rm"), + "specs": {k: specs[k] for k in _CHAT_SPECS if specs.get(k) is not None}, + "running_cost_rm_yr": row.get("running_cost_rm_yr"), + "litres_yr": row.get("litres_yr"), + "kwh_yr": row.get("kwh_yr"), + "co2_kg_yr": row.get("co2_kg_yr"), + "total_cost_5yr_rm": row.get("total_cost_5yr_rm"), + "resale_retained_pct": row.get("resale_retained_pct"), + "road_tax_rm": own.get("road_tax_rm"), + "warranty_battery_yrs": own.get("warranty_battery_yrs"), + "cost_breakdown_5yr": { + "lines": {ln["key"]: ln["amount_rm"] for ln in breakdown.get("lines") or []}, + "maintenance_basis": breakdown.get("maintenance_basis"), + "maintenance_note": breakdown.get("maintenance_note"), + }, + } + + +def _solar_reference() -> dict | None: + try: + from .solar import solar_estimate + + return solar_estimate() + except Exception: # the chat must answer even if the solar inputs are broken + logger.exception("solar estimate failed; chat continues without it") + return None async def chat_reply(result: dict, message: str, lang: str) -> str: @@ -376,12 +439,20 @@ async def chat_reply(result: dict, message: str, lang: str) -> str: + "\n\nContext:\n" + json.dumps( { - "ranking_top5": result["ranking"][:5], + "ranking_top5": [_chat_car(r) for r in result["ranking"][:5]], "roadmap": result.get("roadmap"), "profile": result.get("profile"), + # The banner's figures for its reference home, so a solar + # answer quotes them instead of inventing a payback. + "solar_reference": _solar_reference(), }, ensure_ascii=False, ) + # The chat used to see no policy brief at all, only the ranking, so + # questions on ToU, the BUDI95 quota or NEM against ATAP were + # answered from the model's own (dated) memory. + + "\n\nPolicy brief:\n" + + load_policy_markdown() } resp = await _with_key_rotation( lambda client: _generate_once(client, contents=message, config=config) @@ -399,6 +470,26 @@ async def chat_reply(result: dict, message: str, lang: str) -> str: def _mock_chat(result: dict, message: str, lang: str) -> str: top = result["ranking"][0] msg = message.lower() + # Solar first: "is a battery worth it?" is a solar question, not degradation. + if any(k in msg for k in ("solar", "atap")) or re.search(r"\bnem\b", msg): + from .solar import solar_estimate + + s = solar_estimate() + return _t( + f"Pemasangan baharu kini di bawah Solar ATAP (NEM ditutup kepada pemohon baharu pada " + f"30 Jun 2025). Sistem {s['system_kw_peak']} kW: kira-kira RM{s['capex_rm']:,.0f}, " + f"jimat ~RM{s['savings_rm_per_year']:,.0f} setahun, bayar balik ~{s['payback_years']} " + f"tahun. Eksport hanya dikreditkan pada caj tenaga, jadi cas kereta pada waktu siang " + f"bila boleh. Bateri {s['battery']['kwh']} kWh menambah ~RM{s['battery']['capex_rm']:,.0f} " + f"untuk ~RM{s['battery']['extra_savings_rm_per_year']:,.0f} setahun.", + f"New installs now go on Solar ATAP (NEM closed to new applicants on 30 Jun 2025). " + f"A {s['system_kw_peak']} kW system: about RM{s['capex_rm']:,.0f}, saving " + f"~RM{s['savings_rm_per_year']:,.0f} a year, paying back in ~{s['payback_years']} years. " + f"Exports earn only the energy charge, so charge the car in daylight when you can. " + f"A {s['battery']['kwh']} kWh battery adds ~RM{s['battery']['capex_rm']:,.0f} for " + f"~RM{s['battery']['extra_savings_rm_per_year']:,.0f} a year more.", + lang, + ) if any(k in msg for k in ("battery", "bateri", "degrad", "degradasi")): return _t( "Bateri EV merosot ~1-2% setahun secara purata. Jaminan bateri biasanya 8 tahun / " @@ -408,12 +499,55 @@ def _mock_chat(result: dict, message: str, lang: str) -> str: "(warning only).", lang, ) - if any(k in msg for k in ("solar")): + if any(k in msg for k in ("family", "keluarga", "seat", "tempat duduk")): + top5 = result["ranking"][:5] + roomy = max( + top5, + key=lambda r: ( + (r.get("specs") or {}).get("seats") or 0, + (r.get("specs") or {}).get("boot_l") or 0, + ), + ) + sp = roomy.get("specs") or {} + return _t( + f"Untuk keluarga, {roomy['brand']} {roomy['model']} paling luas antara lima teratas " + f"anda: {sp.get('seats', '?')} tempat duduk, but {sp.get('boot_l', '?')} L.", + f"For a family, the {roomy['brand']} {roomy['model']} is the roomiest of your top " + f"five: {sp.get('seats', '?')} seats and a {sp.get('boot_l', '?')} L boot.", + lang, + ) + if any(k in msg for k in ("servic", "maintenance", "servis", "penyelenggaraan")): + def five_yr(r: dict) -> float: + lines = (r.get("cost_breakdown_5yr") or {}).get("lines") or [] + return next((ln["amount_rm"] for ln in lines if ln["key"] == "maintenance"), 0.0) + + top5 = [r for r in result["ranking"][:5] if five_yr(r) > 0] + if top5: + cheap = min(top5, key=five_yr) + return _t( + f"Paling murah diservis dalam lima tahun: {cheap['brand']} {cheap['model']}, " + f"kira-kira RM{five_yr(cheap):,.0f}.", + f"Cheapest to service over five years: the {cheap['brand']} {cheap['model']}, " + f"about RM{five_yr(cheap):,.0f}.", + lang, + ) + if any(k in msg for k in ("budi95", "quota", "kuota", "subsid")): + quota = int((load_fuel().get("budi95") or {}).get("quota_l_per_month") or 300) + return _t( + f"BUDI95 memberi {quota} liter RON95 sebulan pada RM1.99 kepada rakyat Malaysia yang " + "layak; liter selebihnya dibayar pada harga tanpa subsidi. Enjin kos kami sudah " + "mengambil kira had ini untuk perbatuan anda.", + f"BUDI95 gives eligible Malaysians {quota} litres of RON95 a month at RM1.99; litres " + "beyond that are paid at the unsubsidised price. Our cost engine already applies " + "that cap to your mileage.", + lang, + ) + if re.search(r"\btou\b|time.of.use|cheapest time|masa paling murah|off.peak|luar puncak", msg): return _t( - "Dengan panel solar di rumah, kos pengecasan boleh turun ke hampir sifar pada siang " - "hari. Pulangan purata Malaysia: bayar balik ~7-8 tahun.", - "With rooftop solar at home your daytime charging cost can drop toward zero. " - "Average Malaysia payback is around 7-8 years.", + "Dengan tarif ToU TNB (pilihan, perlu meter pintar), waktu luar puncak ialah 10 malam " + "hingga 2 petang hari bekerja dan sepanjang hujung minggu: cas kereta selepas 10 malam.", + "On TNB's Time-of-Use tariff (opt-in, needs a smart meter) off-peak is 10pm to 2pm on " + "weekdays and all weekend: schedule charging to start after 10pm.", lang, ) if any(k in msg for k in ("hybrid", "hibrid", "why", "kenapa")): diff --git a/backend/app/services/calculators.py b/backend/app/services/calculators.py index cd35800..c97ec01 100644 --- a/backend/app/services/calculators.py +++ b/backend/app/services/calculators.py @@ -211,6 +211,11 @@ def road_tax_for_catalog_vehicle(slug: str) -> dict | None: # --- affordability (the loan, solved backwards) -------------------------- +# The drivetrains the catalogue holds; anything else (a custom "ice" car) is +# not filtered, since the catalogue has no petrol-only rows to match it to. +DRIVETRAINS = ("ev", "hybrid", "phev") + + def affordability(monthly_budget_rm: float, *, vehicle_type: str = "ev", tenure_years: int = DEFAULT_TENURE_YEARS, down_payment_rm: float = 0.0, @@ -237,7 +242,14 @@ def affordability(monthly_budget_rm: float, *, vehicle_type: str = "ev", financed = monthly * months / (1 + (rate_pct / 100) * years) price = financed + down - affordable = [v for v in load_catalog() if float(v["price_rm"]) <= price] + # The drivetrain chosen on the page decides the list, not only the loan + # rate. It used to filter on price alone, so the plug-in hybrid tab listed + # the dearest cars of any kind under the price (a Hilux EV, a Lexus LBX + # hybrid) and the count covered all 170 trims whatever was selected. + catalog = load_catalog() + if vehicle_type in DRIVETRAINS: + catalog = [v for v in catalog if v.get("type") == vehicle_type] + affordable = [v for v in catalog if float(v["price_rm"]) <= price] affordable.sort(key=lambda v: -float(v["price_rm"])) return { @@ -248,8 +260,9 @@ def affordability(monthly_budget_rm: float, *, vehicle_type: str = "ev", "max_price_rm": _half_up(price), "financed_rm": _half_up(financed), "total_interest_rm": _half_up(financed * (rate_pct / 100) * years), + "vehicle_type": vehicle_type, "cars_in_range": len(affordable), - "catalog_total": len(load_catalog()), + "catalog_total": len(catalog), "examples": [ {"slug": v["id"], "label": " ".join(x for x in (v["brand"], v["model"], v.get("variant") or "") if x).strip(), diff --git a/backend/app/services/costing.py b/backend/app/services/costing.py index f006729..7cca3ea 100644 --- a/backend/app/services/costing.py +++ b/backend/app/services/costing.py @@ -106,9 +106,13 @@ def five_year_breakdown(vehicle: dict, running_cost_rm_yr: float) -> dict: "resale_value_rm": round(price * retained_pct / 100.0, 0), "retained_pct": round(retained_pct, 1), "retained_basis": retained_basis, - # 16 of 170 trims carry a measured servicing figure; the rest are fitted - # from drivetrain and price band. Surfaced so the page can say which. + # 24 of 171 trims carry a published servicing figure (the best sellers); + # the rest are fitted from drivetrain and price band. Surfaced so the + # page can say which. "maintenance_basis": maintenance_basis, + # Where a published figure came from (distributor, document, date), so + # the page can name the source instead of only saying "measured". + "maintenance_note": own.get("maintenance_note"), "lines": [ { "key": key, @@ -122,62 +126,124 @@ def five_year_breakdown(vehicle: dict, running_cost_rm_yr: float) -> dict: def breakeven_km_per_year(ev: dict, hybrid: dict, energy: dict, profile: dict, features: dict) -> dict: - """Annual mileage at which the EV's five-year cost overtakes the hybrid's. - - Everything except energy is fixed per car, so the two totals are straight - lines in annual mileage and cross at most once. At subsidised RON95 the EV - is often dearer per kilometre than an efficient hybrid, in which case the - lines diverge and there is no crossing. Saying that plainly is the point of - the feature. + """Annual mileage at which the EV's five-year cost crosses the hybrid's. + + Everything except energy is fixed per car, so the gap between the two + totals moves only with mileage. It used to be treated as two straight lines + from rates measured at 10,000 km, which stopped being true twice over: the + home charging rate climbs as the kWh push the household up TNB's tariff + steps, and since BUDI95's quota is priced in, a hybrid's petrol jumps from + RM1.99 to the unsubsidised price past 3,600 L a year. A thirsty hybrid can + therefore be cheaper than an EV at 20,000 km and dearer at 50,000, a + crossing the straight lines put at the wrong mileage or missed entirely. + + So the gap is evaluated on the real cost functions across every plausible + mileage and the first sign change is refined by bisection. At subsidised + RON95 the EV is often dearer per kilometre than an efficient hybrid and the + totals never cross; saying that plainly is the point of the feature. """ - def at(vehicle: dict, km: float) -> tuple[float, float]: + fixed = { + "ev": five_year_breakdown(ev, 0.0)["total_rm"], + "hybrid": five_year_breakdown(hybrid, 0.0)["total_rm"], + } + + def per_year(vehicle: dict, km: float) -> float: feat = {**features, "annual_km": km} - per_year = engines.energy_engine(vehicle, profile, feat, energy)["cost_rm_yr"] - fixed = five_year_breakdown(vehicle, 0.0)["total_rm"] - return fixed, per_year + return engines.energy_engine(vehicle, profile, feat, energy)["cost_rm_yr"] - ev_fixed, ev_rate = at(ev, 10_000.0) - hy_fixed, hy_rate = at(hybrid, 10_000.0) - # cost(km) = fixed + rate_per_km * km * YEARS, rate measured at 10,000 km + def gap(km: float) -> float: + """EV five-year total minus the hybrid's; negative means the EV is cheaper.""" + return (fixed["ev"] + per_year(ev, km) * OWNERSHIP_YEARS) - ( + fixed["hybrid"] + per_year(hybrid, km) * OWNERSHIP_YEARS + ) + + ev_rate = per_year(ev, 10_000.0) + hy_rate = per_year(hybrid, 10_000.0) ev_per_km = ev_rate / 10_000.0 hy_per_km = hy_rate / 10_000.0 - slope = (ev_per_km - hy_per_km) * OWNERSHIP_YEARS - intercept = ev_fixed - hy_fixed result = { "ev_slug": ev["id"], "hybrid_slug": hybrid["id"], "ev_rm_per_100km": round(ev_per_km * 100, 2), "hybrid_rm_per_100km": round(hy_per_km * 100, 2), - "ev_fixed_5yr_rm": round(ev_fixed, 0), - "hybrid_fixed_5yr_rm": round(hy_fixed, 0), + "ev_fixed_5yr_rm": round(fixed["ev"], 0), + "hybrid_fixed_5yr_rm": round(fixed["hybrid"], 0), "your_km_per_year": round(features.get("annual_km", 0), 0), } # Beyond this the crossover is arithmetic rather than advice: 100,000 km a # year is 274 km every single day. When the two cost-per-km figures are # close the lines are nearly parallel and cross somewhere absurd, which is # not a break-even a buyer can act on. - MAX_PLAUSIBLE_KM = 100_000.0 - - if slope >= 0 and intercept >= 0: - result["breakeven_km_per_year"] = None - result["verdict"] = "hybrid_always" - elif slope <= 0 and intercept <= 0: - result["breakeven_km_per_year"] = None - result["verdict"] = "ev_always" - else: - km = -intercept / slope - if 0 < km <= MAX_PLAUSIBLE_KM: - result["breakeven_km_per_year"] = round(km, 0) - result["verdict"] = "crossover" - result["you_are_past_it"] = features.get("annual_km", 0) >= km - else: - # The lines do cross, but not inside any mileage a person drives. - result["breakeven_km_per_year"] = None - result["verdict"] = "hybrid_always" if intercept > 0 else "ev_always" - result["note"] = ( - "the two are within RM" - f"{abs(ev_per_km - hy_per_km) * 100:.2f} per 100 km, so mileage " - "does not decide this one" - ) + MIN_KM, MAX_PLAUSIBLE_KM, STEP_KM = 1_000.0, 100_000.0, 1_000.0 + + lo_km, lo_gap = MIN_KM, gap(MIN_KM) + first_gap = lo_gap + crossing = None + km = MIN_KM + while km < MAX_PLAUSIBLE_KM: + km = min(km + STEP_KM, MAX_PLAUSIBLE_KM) + g = gap(km) + if (g < 0) != (lo_gap < 0): + a, b, ga = lo_km, km, lo_gap + for _ in range(20): # to within 1 km + mid = (a + b) / 2 + gm = gap(mid) + if (gm < 0) == (ga < 0): + a, ga = mid, gm + else: + b = mid + crossing = (a + b) / 2 + break + lo_km, lo_gap = km, g + + if crossing is not None: + result["breakeven_km_per_year"] = round(crossing, 0) + result["verdict"] = "crossover" + # Which car is cheaper on the low-mileage side of the crossing. It used + # to be the EV by construction; the fuel quota made the other order real. + result["cheaper_below"] = "ev" if first_gap < 0 else "hybrid" + result["you_are_past_it"] = features.get("annual_km", 0) >= crossing + return result + + result["breakeven_km_per_year"] = None + result["verdict"] = "hybrid_always" if first_gap > 0 else "ev_always" + # The gap closes across the whole range without reaching zero: the lines + # would cross, but not inside any mileage a person drives. + if abs(lo_gap) < abs(first_gap): + result["note"] = ( + "the two are within RM" + f"{abs(ev_per_km - hy_per_km) * 100:.2f} per 100 km, so mileage " + "does not decide this one" + ) return result + + +def five_year_cost_curve(ev: dict, hybrid: dict, energies: dict[str, dict], + profile: dict, features: dict, max_km: float, + points: int = 21) -> list[dict]: + """Five-year total of the best EV and best hybrid across annual mileages. + + What the fuel panel draws: one EV line (electricity does not depend on the + RON95 scenario) and one hybrid line per scenario in `energies`, so the + reader sees the subsidy as the gap between two hybrid lines and the quota as + the bend in the subsidised one. The same arithmetic as breakeven_km_per_year, + sampled instead of solved. + """ + fixed_ev = five_year_breakdown(ev, 0.0)["total_rm"] + fixed_hy = five_year_breakdown(hybrid, 0.0)["total_rm"] + any_energy = next(iter(energies.values())) + out = [] + for i in range(points): + km = max_km * i / (points - 1) + feat = {**features, "annual_km": km} + row = { + "km": round(km, 0), + "ev_rm": round(fixed_ev + engines.energy_engine( + ev, profile, feat, any_energy)["cost_rm_yr"] * OWNERSHIP_YEARS, 0), + } + for name, energy in energies.items(): + per_year = engines.energy_engine(hybrid, profile, feat, energy)["cost_rm_yr"] + row[f"hybrid_{name}_rm"] = round(fixed_hy + per_year * OWNERSHIP_YEARS, 0) + out.append(row) + return out diff --git a/backend/app/services/report_pdf.py b/backend/app/services/report_pdf.py index 20fa5b9..6ec6be4 100644 --- a/backend/app/services/report_pdf.py +++ b/backend/app/services/report_pdf.py @@ -694,9 +694,14 @@ def step(title: str, text: str, basis: str) -> None: s = ctx["solar"] step( t("how_solar", lang), - f"Capex RM{_rm(s.get('capex_rm'))}, saving about RM{_rm(s.get('savings_rm_per_year'))} " - f"a year, paying back in {s.get('payback_years', '—')} years. Daytime charging then " - f"costs close to nothing.", + f"Under Solar ATAP, a {s.get('system_kw_peak', 5)} kW rooftop system for a typical " + f"home with an EV costs about RM{_rm(s.get('capex_rm'))} and saves about " + f"RM{_rm(s.get('savings_rm_per_year'))} a year, paying back in " + f"{s.get('payback_years', '—')} years. Exports earn only the energy charge, so " + f"charging the car from the panels in daylight is worth more than exporting. " + f"A {(s.get('battery') or {}).get('kwh', 10)} kWh battery adds about " + f"RM{_rm((s.get('battery') or {}).get('capex_rm'))} for RM" + f"{_rm((s.get('battery') or {}).get('extra_savings_rm_per_year'))} a year more.", "", ) return out diff --git a/backend/app/services/solar.py b/backend/app/services/solar.py new file mode 100644 index 0000000..8c26ee6 --- /dev/null +++ b/backend/app/services/solar.py @@ -0,0 +1,135 @@ +"""Rooftop solar under Solar ATAP, with and without a home battery (D-SOLAR). + +The banner used to print three constants: RM34,000, RM4,300 a year, 7.9 years. +They came from the NEM era, when every exported kWh was netted against an +imported one at the full retail rate and spare credit rolled over for a year. +NEM 3.0 took its last applications on 30 Jun 2025. A home installing now goes +on Solar ATAP (Energy Commission GP/ST/No.60/2025, in force 1 Jan 2026), which +credits exports at the Energy Charge alone, only up to that month's imports, +and forfeits the rest. That is worth roughly half as much per exported kWh, +which is also why a battery is now a question worth asking. + +So the banner is computed instead: one reference household (data/solar_avg.json) +is billed on TNB's own arithmetic, engines.tnb_tou_bill over tariff.json, with +no panels, with panels, and with panels plus a battery. Because the bill comes +from tariff.json, the figures move when the tariff or the monthly AFA does. + +The household is on the standard Domestic tariff, not ToU. ToU is opt-in and +most homes have not opted in, and the Energy Charge that ATAP credits exports +at is the standard tariff's one. Still one reference household, as D6 decided: +no irradiance model, no per-buyer roof. +""" + +from __future__ import annotations + +from ..config import load_solar, load_tariff +from ..engines import engines + + +def _general_tariff(tariff: dict) -> dict: + """tariff.json's ToU block with both periods at the standard Energy Charge. + + The standard Domestic tariff differs from ToU only in the energy rate, which + is one figure around the clock. Everything else (capacity, network, retail, + AFA, the efficiency incentive, KWTBB, service tax) is shared, so the ToU + bill function prices it exactly once both periods carry the same rate. + """ + tou = dict(tariff["domestic_tou"]) + general = tariff["domestic_general"] + for tier in ("energy_tier1", "energy_tier2"): + rate = float(general[tier]) + tou[tier] = {"peak": rate, "off_peak": rate} + return tou + + +def _bill(kwh: float, tou: dict) -> float: + """A month's bill for `kwh` imported. One rate, so the split is immaterial.""" + return engines.tnb_tou_bill(kwh, 0.0, tou) + + +def _month(imported: float, exported: float, tou: dict, energy_charge: float) -> dict: + """One month under Solar ATAP. + + Exports earn the Energy Charge, capped at what the house imported that + month; the rest is forfeited. The credit cannot touch AFA, and a negative + bill is set to zero with no payout (guideline 3.6.1, 14.1). + """ + credited = min(exported, imported) + bill = _bill(imported, tou) + afa = imported * float(tou.get("afa_rm_per_kwh", 0) or 0) if imported > float( + tou.get("usage_threshold_kwh", 600) or 600 + ) else 0.0 + credit = min(credited * energy_charge, max(0.0, bill - afa)) + return { + "bill_rm": bill - credit, + "credited_kwh": credited, + "forfeited_kwh": exported - credited, + } + + +def solar_estimate() -> dict: + """Capex, yearly saving and payback for the reference household. + + Two options, panels alone and panels with a battery, each against the same + house with neither. The battery soaks up the day's surplus and gives it back + in the evening, so a stored kWh is worth the full import rate it avoids + instead of the Energy Charge it would have been credited at. + """ + s = load_solar() + tariff = load_tariff()["tnb_tariffs"] + tou = _general_tariff(tariff) + + house = float(s["household_kwh_month"]) + ev = float(s["ev_kwh_month"]) + demand = house + ev + generation = float(s["system_kw"]) * float(s["yield_kwh_per_kwp_yr"]) / 12.0 + + # Panels make power by day; the car charges overnight. + used_direct = min(generation, house * float(s["household_daytime_share"])) + surplus = generation - used_direct + + # Tier 1 holds while the house imports under 1,501 kWh a month, which this + # one always does; read it from the tariff rather than assume it. + energy_charge = float(tariff["domestic_general"]["energy_tier1"]) + + before = _bill(demand, tou) + solar = _month(demand - used_direct, surplus, tou, energy_charge) + + # One full cycle a day, limited by what the day leaves over. + days = 365.0 / 12.0 + stored = min(surplus, float(s["battery_kwh"]) * days) + returned = stored * float(s["battery_round_trip"]) + imported_b = max(0.0, demand - used_direct - returned) + battery = _month(imported_b, surplus - stored, tou, energy_charge) + + capex = float(s["system_kw"]) * float(s["capex_rm_per_kw"]) + battery_capex = float(s["battery_capex_rm"]) + saving = (before - solar["bill_rm"]) * 12 + saving_b = (before - battery["bill_rm"]) * 12 + extra = saving_b - saving + + def years(cost: float, per_year: float) -> float | None: + return round(cost / per_year, 1) if per_year > 0 else None + + return { + "scheme": "Solar ATAP", + "system_kw_peak": s["system_kw"], + "capex_rm": round(capex, -2), + "savings_rm_per_year": round(saving, -1), + "payback_years": years(capex, saving), + "bill_before_rm_month": round(before, 0), + "bill_after_rm_month": round(solar["bill_rm"], 0), + "self_used_share": round(used_direct / generation, 2) if generation else 0.0, + "forfeited_kwh_month": round(solar["forfeited_kwh"], 0), + "credit_years": s["credit_years"], + "battery": { + "kwh": s["battery_kwh"], + "capex_rm": round(battery_capex, -2), + "extra_savings_rm_per_year": round(extra, -1), + "payback_years": years(battery_capex, extra), + "combined_payback_years": years(capex + battery_capex, saving_b), + }, + "household_kwh_month": house, + "ev_kwh_month": ev, + "rebate_note": s.get("rebate_note", ""), + } diff --git a/backend/tests/test_calculators.py b/backend/tests/test_calculators.py index bb89920..7ed2c52 100644 --- a/backend/tests/test_calculators.py +++ b/backend/tests/test_calculators.py @@ -156,10 +156,27 @@ def test_a_longer_tenure_reaches_further(self): def test_it_reports_what_is_actually_in_range(self, catalog): out = calc.affordability(1_500, down_payment_rm=20_000) - expected = sum(1 for v in catalog if v["price_rm"] <= out["max_price_rm"]) + expected = sum(1 for v in catalog + if v["type"] == "ev" and v["price_rm"] <= out["max_price_rm"]) assert out["cars_in_range"] == expected + assert out["catalog_total"] == sum(1 for v in catalog if v["type"] == "ev") assert all(e["price_rm"] <= out["max_price_rm"] for e in out["examples"]) + @pytest.mark.parametrize("drivetrain", ["ev", "hybrid", "phev"]) + def test_the_list_follows_the_chosen_drivetrain(self, catalog, drivetrain): + """The plug-in hybrid tab once listed a Hilux EV and a Lexus LBX hybrid: + the drivetrain changed the loan rate and nothing else.""" + out = calc.affordability(4_000, vehicle_type=drivetrain, down_payment_rm=30_000) + assert out["examples"], drivetrain + assert {e["type"] for e in out["examples"]} == {drivetrain} + expected = sum(1 for v in catalog + if v["type"] == drivetrain and v["price_rm"] <= out["max_price_rm"]) + assert out["cars_in_range"] == expected + + def test_the_hilux_is_never_offered_as_a_plug_in_hybrid(self): + out = calc.affordability(4_000, vehicle_type="phev", down_payment_rm=30_000) + assert "toyota-hilux" not in {e["slug"] for e in out["examples"]} + def test_a_zero_budget_reaches_only_the_deposit(self): assert calc.affordability(0, down_payment_rm=50_000)["max_price_rm"] == 50_000 diff --git a/backend/tests/test_engines.py b/backend/tests/test_engines.py index 2de8c1f..9a21df3 100644 --- a/backend/tests/test_engines.py +++ b/backend/tests/test_engines.py @@ -432,7 +432,12 @@ def test_a_measured_row_is_never_overwritten_by_the_fit(self): measured = self._measured()[0] value, basis = engines.maintenance_rm_yr(measured) assert basis == "measured" - assert value == float(measured["ownership"]["maintenance_rm_yr"]) + own = measured["ownership"] + # A published five-year total is the figure; the annual key is its + # rounded copy for readers of the file. + expected = (own["maintenance_5yr_rm"] / 5 if own.get("maintenance_5yr_rm") + else own["maintenance_rm_yr"]) + assert value == pytest.approx(float(expected)) def test_an_unmeasured_row_is_reported_as_estimated(self): value, basis = engines.maintenance_rm_yr({"type": "ev", "price_rm": 120_000}) diff --git a/backend/tests/test_quota_solar_servicing.py b/backend/tests/test_quota_solar_servicing.py new file mode 100644 index 0000000..c91293a --- /dev/null +++ b/backend/tests/test_quota_solar_servicing.py @@ -0,0 +1,166 @@ +"""The 14 Nov 2026 round: BUDI95's monthly quota, Solar ATAP, published servicing, +and the chat analyst's knowledge. + +Each test pins a behaviour a buyer would notice if it regressed: petrol past the +quota priced as if it were still subsidised, a solar payback credited at NEM's +full retail rate, a servicing figure that is not the brand's published one, or a +chat that answers tariff questions without the policy brief. +""" + +from __future__ import annotations + +import pytest + +from app.config import load_catalog, load_fuel +from app.engines import engines +from app.engines.engines import build_features +from app.services import analyst as A +from app.services import energy_context +from app.services.costing import breakeven_km_per_year, five_year_breakdown +from app.services.solar import solar_estimate + +from test_golden_ranking import GOLDEN_PROFILES + +CATALOG = {v["id"]: v for v in load_catalog()} + + +def _without_quota(energy: dict) -> dict: + fuel = {k: v for k, v in energy["fuel"].items() + if k not in ("ron95_quota_l_yr", "ron95_over_quota_rm_per_l")} + return {**energy, "fuel": fuel} + + +class TestBudi95Quota: + def test_quota_comes_from_fuel_json(self): + quota = load_fuel()["budi95"]["quota_l_per_month"] + assert energy_context("subsidised")["fuel"]["ron95_quota_l_yr"] == quota * 12 + + def test_litres_within_the_quota_pay_the_pump_price(self): + fuel = energy_context("subsidised")["fuel"] + litres = fuel["ron95_quota_l_yr"] - 1 + assert engines.petrol_cost_rm(litres, fuel) == pytest.approx(litres * fuel["ron95_rm_per_l"]) + + def test_litres_past_the_quota_pay_the_market_price(self): + fuel = energy_context("subsidised")["fuel"] + quota = fuel["ron95_quota_l_yr"] + cost = engines.petrol_cost_rm(quota + 1000, fuel) + assert cost == pytest.approx( + quota * fuel["ron95_rm_per_l"] + 1000 * fuel["ron95_over_quota_rm_per_l"]) + + def test_the_market_scenario_has_no_quota_to_apply(self): + fuel = energy_context("market")["fuel"] + assert "ron95_quota_l_yr" not in fuel + assert engines.petrol_cost_rm(5000, fuel) == pytest.approx(5000 * fuel["ron95_rm_per_l"]) + + def test_a_thirsty_hybrid_at_high_mileage_costs_more_than_flat_pricing(self): + profile = GOLDEN_PROFILES["kv_home_charging"] + hybrid = CATALOG["toyota-vios"] + hybrid = {**hybrid, "specs": {**hybrid["specs"], "fuel_l_per_100km": 9.0}} + feat = {**build_features(profile), "annual_km": 60_000} + with_quota = engines.energy_engine(hybrid, profile, feat, energy_context("subsidised")) + flat = engines.energy_engine(hybrid, profile, feat, _without_quota(energy_context("subsidised"))) + assert with_quota["cost_rm_yr"] > flat["cost_rm_yr"] + + def test_the_quota_creates_a_breakeven_the_flat_price_hid(self): + """Against a 9 L/100 km hybrid the hybrid is cheaper at low mileage, and + only the quota makes the EV win at high mileage. The crossing used to be + drawn the EV-first way by construction.""" + profile = GOLDEN_PROFILES["kv_home_charging"] + features = build_features(profile) + hybrid = CATALOG["toyota-vios"] + hybrid = {**hybrid, "specs": {**hybrid["specs"], "fuel_l_per_100km": 9.0}} + ev = CATALOG["byd-sealion-7"] + energy = energy_context("subsidised") + + out = breakeven_km_per_year(ev, hybrid, energy, profile, features) + assert out["verdict"] == "crossover" + assert out["cheaper_below"] == "hybrid" + quota_km = energy["fuel"]["ron95_quota_l_yr"] / 9.0 * 100 + assert out["breakeven_km_per_year"] > quota_km + + flat = breakeven_km_per_year(ev, hybrid, _without_quota(energy), profile, features) + assert flat["verdict"] == "hybrid_always" + + +class TestSolarAtap: + def test_banner_is_computed_under_atap(self): + s = solar_estimate() + assert s["scheme"] == "Solar ATAP" + assert s["capex_rm"] > 0 and s["savings_rm_per_year"] > 0 + # The reference home pays back inside the 10 years ATAP credits run. + assert s["payback_years"] < s["credit_years"] + + def test_exports_are_worth_less_than_the_old_nem_banner_claimed(self): + """NEM's static banner said RM4,300 a year; ATAP credits only the energy + charge, so the same 5 kW roof cannot be worth that to this household.""" + assert solar_estimate()["savings_rm_per_year"] < 4300 + + def test_a_battery_saves_less_than_the_panels_do(self): + s = solar_estimate() + assert 0 <= s["battery"]["extra_savings_rm_per_year"] < s["savings_rm_per_year"] + + def test_credit_is_capped_at_imports(self, monkeypatch): + """Past the point where exports exceed what the house imports, a bigger + roof earns nothing more: the extra is forfeited. Capacity and network + charges stay on the bill because the credit is worth the energy charge + only, so it never reaches zero this way either.""" + from app.services import solar as solar_mod + + base = solar_mod.load_solar() + + def at(kw: float) -> dict: + monkeypatch.setattr(solar_mod, "load_solar", lambda: dict(base, system_kw=kw)) + return solar_mod.solar_estimate() + + big, huge = at(20), at(50) + assert huge["bill_after_rm_month"] == big["bill_after_rm_month"] > 0 + assert huge["forfeited_kwh_month"] > big["forfeited_kwh_month"] > 0 + + +class TestPublishedServicing: + def test_the_five_year_line_is_the_published_total(self): + car = CATALOG["honda-city"] + line = next(ln for ln in five_year_breakdown(car, 0.0)["lines"] + if ln["key"] == "maintenance") + assert line["amount_rm"] == round(car["ownership"]["maintenance_5yr_rm"]) + + def test_published_rows_name_their_source(self): + for car in CATALOG.values(): + own = car.get("ownership") or {} + if own.get("maintenance_5yr_rm"): + assert own.get("maintenance_note"), car["id"] + assert own["maintenance_rm_yr"] == round(own["maintenance_5yr_rm"] / 5), car["id"] + assert five_year_breakdown(car, 0.0)["maintenance_basis"] == "measured" + + def test_the_best_sellers_are_covered(self): + """The point of the round: the cars most buyers look at carry the + brand's own figure, not the price-band estimate.""" + for slug in ("proton-emas-5", "proton-emas-7", "honda-city", "honda-hrv-ehev", + "toyota-yaris-cross", "toyota-vios", "honda-cr-v"): + assert engines.maintenance_rm_yr(CATALOG[slug])[1] == "measured", slug + + +class TestChatKnowledge: + @pytest.mark.asyncio + async def test_the_chat_sees_the_policy_brief(self, monkeypatch): + seen = {} + + async def fake_generate(client, *, contents, config): + seen["system"] = config["system_instruction"] + return type("R", (), {"text": "ok"})() + + async def fake_rotation(run): + return await run(None) + + monkeypatch.setattr(A.settings, "gemini_api_keys", ["k"]) + monkeypatch.setattr(A, "_generate_once", fake_generate) + monkeypatch.setattr(A, "_with_key_rotation", fake_rotation) + await A.chat_reply({"ranking": [], "profile": {}}, "When should I charge?", "en") + system = seen["system"] + assert "Solar ATAP" in system and "BUDI95" in system and "2pm-10pm" in system + assert "solar_reference" in system + + def test_offline_solar_question_is_not_answered_as_degradation(self): + reply = A._mock_chat({"ranking": [{"brand": "X", "model": "Y", "type": "ev"}]}, + "Should I add solar at home, and is a battery worth it?", "en") + assert "ATAP" in reply and "degrade" not in reply diff --git a/data/catalog_vehicles.json b/data/catalog_vehicles.json index 8eba4b6..b23c072 100644 --- a/data/catalog_vehicles.json +++ b/data/catalog_vehicles.json @@ -23,7 +23,9 @@ }, "ownership": { "warranty_battery_yrs": 8, - "maintenance_rm_yr": 650, + "maintenance_rm_yr": 238, + "maintenance_5yr_rm": 1188.21, + "maintenance_note": "the 5 services due by month 60 (3, 15, 27, 39, 51 months), labour + parts + 8% SST; Proton e.MAS official service intervals, emas.proton.com/services-e-mas-5/, page updated 2 Apr 2026", "road_tax_note": "EV road tax (JPJ kW schedule, 2026) (power 85 kW)", "road_tax_rm": 60, "insurance_note": "comprehensive car+battery only, Peninsular, 0% NCD, incl. SST+stamp (calculatormalaysia.com EV formula) (SI RM72,800 @ 2.60%)", @@ -60,7 +62,7 @@ }, "maintenance_rm_yr": { "method": "measured", - "basis": "published service schedule" + "basis": "the 5 services due by month 60 (3, 15, 27, 39, 51 months), labour + parts + 8% SST; Proton e.MAS official service intervals, emas.proton.com/services-e-mas-5/, page updated 2 Apr 2026" }, "energy_kwh_per_100km": { "method": "measured", @@ -217,14 +219,14 @@ "id": "tesla-model-3", "brand": "Tesla", "model": "Model 3", - "variant": "Rear-Wheel Drive", + "variant": "Standard RWD", "type": "ev", "price_rm": 149000, "source": "official", - "as_of_date": "2026-04-15", + "as_of_date": "2026-11-15", "specs": { - "battery_kwh": 60, - "range_km": 513, + "battery_kwh": 62.5, + "range_km": 534, "energy_kwh_per_100km": 12.4, "motor_kw": 208, "charge_power_kw_ac": 11, @@ -278,7 +280,8 @@ "method": "measured", "basis": "manufacturer figure" } - } + }, + "source_url": "https://paultan.org/research/tesla/model-3/" }, { "id": "tesla-model-y", @@ -1011,7 +1014,9 @@ "ownership": { "warranty_battery_yrs": 8, "warranty_battery_km": 150000, - "maintenance_rm_yr": 950, + "maintenance_rm_yr": 821, + "maintenance_5yr_rm": 4103.66, + "maintenance_note": "the 11 services due by month 60 / 100,000 km (first one free); Honda Malaysia periodic maintenance schedule, honda.com.my/doc/maintenance/2265, price as of 8 Oct 2026, after Honda's 15% discount", "road_tax_rm": 120, "road_tax_note": "hybrid road tax by engine cc (JPJ) (1498cc non-saloon)", "insurance_note": "comprehensive, Peninsular, 0% NCD (carbase.my formula) (1498cc band2 x RM143,900)", @@ -1048,7 +1053,7 @@ }, "maintenance_rm_yr": { "method": "measured", - "basis": "published service schedule" + "basis": "the 11 services due by month 60 / 100,000 km (first one free); Honda Malaysia periodic maintenance schedule, honda.com.my/doc/maintenance/2265, price as of 8 Oct 2026, after Honda's 15% discount" }, "fuel_l_per_100km": { "method": "measured", @@ -1082,7 +1087,9 @@ "ownership": { "warranty_battery_yrs": 8, "warranty_battery_km": 150000, - "maintenance_rm_yr": 950, + "maintenance_rm_yr": 918, + "maintenance_5yr_rm": 4590.54, + "maintenance_note": "the 11 services due by month 60 / 100,000 km (first one free); Honda Malaysia periodic maintenance schedule, honda.com.my/doc/maintenance/2756, price as of 8 Oct 2026, after Honda's 15% discount", "road_tax_rm": 376, "road_tax_note": "hybrid road tax by engine cc (JPJ) (1993cc saloon)", "insurance_note": "comprehensive, Peninsular, 0% NCD (carbase.my formula) (1993cc band3 x RM167,900)", @@ -1119,7 +1126,7 @@ }, "maintenance_rm_yr": { "method": "measured", - "basis": "published service schedule" + "basis": "the 11 services due by month 60 / 100,000 km (first one free); Honda Malaysia periodic maintenance schedule, honda.com.my/doc/maintenance/2756, price as of 8 Oct 2026, after Honda's 15% discount" }, "fuel_l_per_100km": { "method": "measured", @@ -1137,7 +1144,7 @@ "type": "ev", "price_rm": 67800, "source": "paultan", - "as_of_date": "2026-08-10", + "as_of_date": "2026-11-15", "source_url": "https://paultan.org/research/wuling/bingo/", "body": "Hatchback", "segment": "B-Segment", @@ -1157,8 +1164,8 @@ "insurance_rm_yr": 1914 }, "specs": { - "battery_kwh": 37.9, - "range_km": 337.0, + "battery_kwh": 31.9, + "range_km": 273.0, "power_hp": 67, "energy_kwh_per_100km": 10.1, "charge_power_kw_dc": 50.0, @@ -1191,33 +1198,37 @@ "method": "measured", "basis": "manufacturer figure" } - } + }, + "variant": "Pro" }, { "id": "perodua-qv-e", "brand": "Perodua", "model": "QV-E", "type": "ev", - "price_rm": 87499, + "price_rm": 93999, "source": "paultan", - "as_of_date": "2026-11-12", - "source_url": "https://paultan.org/2026/09/15/perodua-qv-e-gets-an-additional-rm10k-rebate-now-priced-from-rm53499-with-baas-rm77499-full-purchase/", + "as_of_date": "2026-11-15", + "source_url": "https://paultan.org/research/perodua/qv-e/", "body": "SUV", "segment": "B-Segment", "launch": "2025-12-01", - "monthly_rm": 892, + "monthly_rm": 960, "ownership": { "road_tax_yr": 160, "road_tax_rm": 160, "road_tax_note": "EV road tax (JPJ kW schedule, 2026) (power 150 kW)", - "insurance_note": "comprehensive car+battery only, Peninsular, 0% NCD, incl. SST+stamp (calculatormalaysia.com EV formula) (SI RM87,499 @ 2.60%)", + "insurance_note": "comprehensive car+battery only, Peninsular, 0% NCD, incl. SST+stamp (calculatormalaysia.com EV formula) (SI RM93,999 @ 2.60%)", "loan_rate_pct": 1.75, "loan_tenure_yrs": 7, - "loan_down_payment_rm": 8750, - "loan_monthly_rm": 1052.33, - "loan_total_interest_rm": 9647, + "loan_down_payment_rm": 9400, + "loan_monthly_rm": 1130.51, + "loan_total_interest_rm": 10363, + "maintenance_rm_yr": 283, + "maintenance_5yr_rm": 1416.08, + "maintenance_note": "Perodua's yearly schedule over five years / 100,000 km; Perodua service schedule as reported by paultan.org, 7 Aug 2026 (paultan.org/2026/08/07/2026-perodua-qv-e-maintenance-costs/)", "loan_note": "hire purchase, 7yr @ 1.75% flat, 90% financing (ev @ 1.75% flat x 7yr, 90% financing)", - "insurance_rm_yr": 2467 + "insurance_rm_yr": 2649 }, "specs": { "battery_kwh": 52.5, @@ -1228,7 +1239,7 @@ "boot_l": 320, "seats": 5 }, - "price_display": "RM87,499", + "price_display": "RM93,999", "registered_my": 549, "popularity_rating": 3, "registered_basis": "paultan_exact", @@ -1250,6 +1261,10 @@ "method": "computed", "basis": "hire purchase, 7yr @ 1.75% flat, 90% financing (ev @ 1.75% flat x 7yr, 90% financing)" }, + "maintenance_rm_yr": { + "method": "measured", + "basis": "Perodua's yearly schedule over five years / 100,000 km; Perodua service schedule as reported by paultan.org, 7 Aug 2026 (paultan.org/2026/08/07/2026-perodua-qv-e-maintenance-costs/)" + }, "energy_kwh_per_100km": { "method": "measured", "basis": "manufacturer figure" @@ -1516,7 +1531,7 @@ "type": "ev", "price_rm": 103800, "source": "paultan", - "as_of_date": "2026-08-10", + "as_of_date": "2026-11-15", "source_url": "https://paultan.org/research/proton/emas-7/", "body": "SUV", "segment": "C-Segment", @@ -1532,12 +1547,15 @@ "loan_down_payment_rm": 10380, "loan_monthly_rm": 1248.38, "loan_total_interest_rm": 11444, + "maintenance_rm_yr": 299, + "maintenance_5yr_rm": 1496.45, + "maintenance_note": "the 5 services due by month 60 (3, 15, 27, 39, 51 months), labour + parts + 8% SST; Proton e.MAS official service intervals, emas.proton.com/services-e-mas-7/, page updated 13 Oct 2026", "loan_note": "hire purchase, 7yr @ 1.75% flat, 90% financing (ev @ 1.75% flat x 7yr, 90% financing)", "insurance_rm_yr": 2813 }, "specs": { - "battery_kwh": 60.22, - "range_km": 410.0, + "battery_kwh": 49.52, + "range_km": 345.0, "power_hp": 215, "energy_kwh_per_100km": 13.2, "charge_power_kw_dc": 80.0, @@ -1566,11 +1584,16 @@ "method": "computed", "basis": "hire purchase, 7yr @ 1.75% flat, 90% financing (ev @ 1.75% flat x 7yr, 90% financing)" }, + "maintenance_rm_yr": { + "method": "measured", + "basis": "the 5 services due by month 60 (3, 15, 27, 39, 51 months), labour + parts + 8% SST; Proton e.MAS official service intervals, emas.proton.com/services-e-mas-7/, page updated 13 Oct 2026" + }, "energy_kwh_per_100km": { "method": "measured", "basis": "manufacturer figure" } - } + }, + "variant": "Prime" }, { "id": "aion-es", @@ -1769,7 +1792,7 @@ "type": "ev", "price_rm": 109800, "source": "paultan", - "as_of_date": "2026-08-10", + "as_of_date": "2026-11-15", "source_url": "https://paultan.org/research/byd/m6/", "body": "MPV", "segment": "C-Segment", @@ -1789,11 +1812,11 @@ "insurance_rm_yr": 2975 }, "specs": { - "battery_kwh": 71.8, - "range_km": 530.0, + "battery_kwh": 55.4, + "range_km": 420.0, "power_hp": 161, "energy_kwh_per_100km": 12.2, - "charge_power_kw_dc": 115.0, + "charge_power_kw_dc": 89.0, "boot_l": 580, "seats": 7 }, @@ -1823,7 +1846,8 @@ "method": "measured", "basis": "manufacturer figure" } - } + }, + "variant": "Standard Range" }, { "id": "mg-s5", @@ -2268,7 +2292,7 @@ "type": "ev", "price_rm": 163800, "source": "paultan", - "as_of_date": "2026-08-10", + "as_of_date": "2026-11-15", "source_url": "https://paultan.org/research/byd/sealion-7/", "body": "SUV", "segment": "Compact Executive", @@ -2288,8 +2312,8 @@ "insurance_rm_yr": 4433 }, "specs": { - "battery_kwh": 82.5, - "range_km": 542.0, + "battery_kwh": 71.8, + "range_km": 520.0, "power_hp": 228, "energy_kwh_per_100km": 13.7, "charge_power_kw_dc": 110.0, @@ -2322,7 +2346,8 @@ "method": "measured", "basis": "manufacturer figure" } - } + }, + "variant": "Dynamic" }, { "id": "renault-zoe", @@ -2457,7 +2482,7 @@ "type": "ev", "price_rm": 169000, "source": "paultan", - "as_of_date": "2026-08-10", + "as_of_date": "2026-11-15", "source_url": "https://paultan.org/research/smart/smart-1/", "body": "SUV", "segment": "B-Segment", @@ -2477,13 +2502,13 @@ "insurance_rm_yr": 4573 }, "specs": { - "battery_kwh": 66.0, - "range_km": 440.0, + "battery_kwh": 49.0, + "range_km": 315.0, "power_hp": 268, "energy_kwh_per_100km": 13.5, "charge_power_kw_dc": 150.0, "seats": 5, - "boot_l": 313 + "boot_l": 411 }, "price_display": "RM169,000 –RM249,000", "registered_my": 1424, @@ -2511,7 +2536,8 @@ "method": "measured", "basis": "manufacturer figure" } - } + }, + "variant": "Pro" }, { "id": "dongfeng-007", @@ -2583,7 +2609,7 @@ "type": "ev", "price_rm": 182800, "source": "paultan", - "as_of_date": "2026-08-10", + "as_of_date": "2026-11-15", "source_url": "https://paultan.org/research/zeekr/7x/", "body": "SUV", "segment": "Compact Executive", @@ -2603,8 +2629,8 @@ "insurance_rm_yr": 4946 }, "specs": { - "battery_kwh": 100.0, - "range_km": 543.0, + "battery_kwh": 75.0, + "range_km": 480.0, "power_hp": 416, "energy_kwh_per_100km": 16.6, "charge_power_kw_dc": 450.0, @@ -2637,7 +2663,8 @@ "method": "measured", "basis": "manufacturer figure" } - } + }, + "variant": "RWD Standard Range" }, { "id": "suzuki-evitara", @@ -3148,7 +3175,7 @@ "type": "ev", "price_rm": 248888, "source": "paultan", - "as_of_date": "2026-08-10", + "as_of_date": "2026-11-15", "source_url": "https://paultan.org/research/volvo/ec40/", "body": "SUV", "segment": "Compact Executive", @@ -3168,8 +3195,8 @@ "insurance_rm_yr": 6461 }, "specs": { - "battery_kwh": 78.0, - "range_km": 440.0, + "battery_kwh": 70.0, + "range_km": 488.0, "power_hp": 235, "energy_kwh_per_100km": 16.0, "charge_power_kw_dc": 200.0, @@ -3202,7 +3229,8 @@ "method": "measured", "basis": "manufacturer figure" } - } + }, + "variant": "Ultra Single Motor" }, { "id": "bmw-ix1", @@ -3456,7 +3484,7 @@ "type": "ev", "price_rm": 281073, "source": "paultan", - "as_of_date": "2026-08-10", + "as_of_date": "2026-11-15", "source_url": "https://paultan.org/research/xpeng/x9/", "body": "MPV", "segment": "D-Segment", @@ -3476,8 +3504,8 @@ "insurance_rm_yr": 7295 }, "specs": { - "battery_kwh": 110.0, - "range_km": 580.0, + "battery_kwh": 94.8, + "range_km": 535.0, "power_hp": 315, "energy_kwh_per_100km": 17.1, "charge_power_kw_dc": 537.0, @@ -3510,7 +3538,8 @@ "method": "measured", "basis": "manufacturer figure" } - } + }, + "variant": "2WD Standard Range" }, { "id": "bmw-ix2", @@ -4339,7 +4368,7 @@ "type": "ev", "price_rm": 425800, "source": "paultan", - "as_of_date": "2026-08-10", + "as_of_date": "2026-11-15", "source_url": "https://paultan.org/research/bmw/ix/", "body": "SUV", "segment": "Executive", @@ -4359,8 +4388,8 @@ "insurance_rm_yr": 10817 }, "specs": { - "battery_kwh": 111.5, - "range_km": 701.0, + "battery_kwh": 100.6, + "range_km": 602.0, "power_hp": 402, "energy_kwh_per_100km": 14.3, "charge_power_kw_dc": 175.0, @@ -4393,7 +4422,8 @@ "method": "measured", "basis": "manufacturer figure" } - } + }, + "variant": "xDrive45 Sport" }, { "id": "lexus-rz", @@ -5616,6 +5646,9 @@ "loan_down_payment_rm": 10390, "loan_monthly_rm": 1269.06, "loan_total_interest_rm": 13091, + "maintenance_rm_yr": 730, + "maintenance_5yr_rm": 3650.0, + "maintenance_note": "prepaid scheduled servicing for five years or 100,000 km; UMW Toyota Service Savers 5 Years / 100,000km package, RM3,650 (optional at order; UMW Toyota Vios HEV price list, Jan 2026)", "loan_note": "hire purchase, 7yr @ 2.00% flat, 90% financing (hybrid @ 2.00% flat x 7yr, 90% financing)", "insurance_rm_yr": 2981 }, @@ -5650,6 +5683,10 @@ "method": "computed", "basis": "hire purchase, 7yr @ 2.00% flat, 90% financing (hybrid @ 2.00% flat x 7yr, 90% financing)" }, + "maintenance_rm_yr": { + "method": "measured", + "basis": "prepaid scheduled servicing for five years or 100,000 km; UMW Toyota Service Savers 5 Years / 100,000km package, RM3,650 (optional at order; UMW Toyota Vios HEV price list, Jan 2026)" + }, "fuel_l_per_100km": { "method": "measured", "basis": "manufacturer figure" @@ -5679,6 +5716,9 @@ "loan_down_payment_rm": 10980, "loan_monthly_rm": 1341.13, "loan_total_interest_rm": 13835, + "maintenance_rm_yr": 732, + "maintenance_5yr_rm": 3661.36, + "maintenance_note": "the 6 services due by month 60 (3, 12, 24, 36, 48, 60 months), labour + parts + 8% SST; Proton e.MAS official service intervals, emas.proton.com/services-e-mas-7-phev/, page updated 15 Sep 2026", "loan_note": "hire purchase, 7yr @ 2.00% flat, 90% financing (phev @ 2.00% flat x 7yr, 90% financing)", "insurance_rm_yr": 3134 }, @@ -5720,6 +5760,10 @@ "method": "computed", "basis": "hire purchase, 7yr @ 2.00% flat, 90% financing (phev @ 2.00% flat x 7yr, 90% financing)" }, + "maintenance_rm_yr": { + "method": "measured", + "basis": "the 6 services due by month 60 (3, 12, 24, 36, 48, 60 months), labour + parts + 8% SST; Proton e.MAS official service intervals, emas.proton.com/services-e-mas-7-phev/, page updated 15 Sep 2026" + }, "fuel_l_per_100km": { "method": "measured", "basis": "official", @@ -5755,6 +5799,9 @@ "loan_down_payment_rm": 10990, "loan_monthly_rm": 1342.35, "loan_total_interest_rm": 13847, + "maintenance_rm_yr": 730, + "maintenance_5yr_rm": 3650.0, + "maintenance_note": "prepaid scheduled servicing for five years or 100,000 km; UMW Toyota Service Savers 5 Years / 100,000km package, RM3,650 (optional at order; paultan.org launch report, 8 May 2026)", "loan_note": "hire purchase, 7yr @ 2.00% flat, 90% financing (hybrid @ 2.00% flat x 7yr, 90% financing)", "insurance_rm_yr": 3137 }, @@ -5792,6 +5839,10 @@ "method": "computed", "basis": "hire purchase, 7yr @ 2.00% flat, 90% financing (hybrid @ 2.00% flat x 7yr, 90% financing)" }, + "maintenance_rm_yr": { + "method": "measured", + "basis": "prepaid scheduled servicing for five years or 100,000 km; UMW Toyota Service Savers 5 Years / 100,000km package, RM3,650 (optional at order; paultan.org launch report, 8 May 2026)" + }, "fuel_l_per_100km": { "method": "measured", "basis": "official", @@ -5825,6 +5876,9 @@ "loan_down_payment_rm": 11190, "loan_monthly_rm": 1366.78, "loan_total_interest_rm": 14099, + "maintenance_rm_yr": 814, + "maintenance_5yr_rm": 4072.06, + "maintenance_note": "the 11 services due by month 60 / 100,000 km (first one free); Honda Malaysia periodic maintenance schedule, honda.com.my/doc/maintenance/3102, price as of 1 Sep 2026, after Honda's 15% discount", "loan_note": "hire purchase, 7yr @ 2.00% flat, 90% financing (hybrid @ 2.00% flat x 7yr, 90% financing)", "insurance_rm_yr": 3189 }, @@ -5860,6 +5914,10 @@ "method": "computed", "basis": "hire purchase, 7yr @ 2.00% flat, 90% financing (hybrid @ 2.00% flat x 7yr, 90% financing)" }, + "maintenance_rm_yr": { + "method": "measured", + "basis": "the 11 services due by month 60 / 100,000 km (first one free); Honda Malaysia periodic maintenance schedule, honda.com.my/doc/maintenance/3102, price as of 1 Sep 2026, after Honda's 15% discount" + }, "fuel_l_per_100km": { "method": "measured", "basis": "manufacturer figure" @@ -5889,6 +5947,9 @@ "loan_down_payment_rm": 11290, "loan_monthly_rm": 1378.99, "loan_total_interest_rm": 14225, + "maintenance_rm_yr": 863, + "maintenance_5yr_rm": 4313.16, + "maintenance_note": "the 11 services due by month 60 / 100,000 km (first one free); Honda Malaysia periodic maintenance schedule, honda.com.my/doc/maintenance/3178, price as of 1 Sep 2026, after Honda's 15% discount", "loan_note": "hire purchase, 7yr @ 2.00% flat, 90% financing (hybrid @ 2.00% flat x 7yr, 90% financing)", "insurance_rm_yr": 3215 }, @@ -5927,6 +5988,10 @@ "method": "computed", "basis": "hire purchase, 7yr @ 2.00% flat, 90% financing (hybrid @ 2.00% flat x 7yr, 90% financing)" }, + "maintenance_rm_yr": { + "method": "measured", + "basis": "the 11 services due by month 60 / 100,000 km (first one free); Honda Malaysia periodic maintenance schedule, honda.com.my/doc/maintenance/3178, price as of 1 Sep 2026, after Honda's 15% discount" + }, "fuel_l_per_100km": { "method": "measured", "basis": "official", @@ -6441,6 +6506,9 @@ "loan_down_payment_rm": 17820, "loan_monthly_rm": 2176.59, "loan_total_interest_rm": 22453, + "maintenance_rm_yr": 918, + "maintenance_5yr_rm": 4590.54, + "maintenance_note": "the 11 services due by month 60 / 100,000 km (first one free); Honda Malaysia periodic maintenance schedule, honda.com.my/doc/maintenance/2565, price as of 8 Oct 2026, after Honda's 15% discount", "loan_note": "hire purchase, 7yr @ 2.00% flat, 90% financing (hybrid @ 2.00% flat x 7yr, 90% financing)", "insurance_rm_yr": 4946 }, @@ -6475,6 +6543,10 @@ "method": "computed", "basis": "hire purchase, 7yr @ 2.00% flat, 90% financing (hybrid @ 2.00% flat x 7yr, 90% financing)" }, + "maintenance_rm_yr": { + "method": "measured", + "basis": "the 11 services due by month 60 / 100,000 km (first one free); Honda Malaysia periodic maintenance schedule, honda.com.my/doc/maintenance/2565, price as of 8 Oct 2026, after Honda's 15% discount" + }, "fuel_l_per_100km": { "method": "measured", "basis": "manufacturer figure" @@ -11324,6 +11396,68 @@ "popularity_rating": 1, "registered_basis": "paultan_no_records", "registered_as_of": "2026-10" + }, + { + "id": "jac-t9-ev", + "brand": "JAC", + "model": "T9 EV", + "variant": "Luxury", + "type": "ev", + "price_rm": 199888, + "source": "paultan", + "as_of_date": "2026-11-15", + "ckd": false, + "source_url": "https://paultan.org/research/jac/t9-ev/", + "body": "Pickup", + "segment": "Truck/4X4", + "monthly_rm": 2040, + "price_display": "RM199,888", + "ownership": { + "road_tax_rm": 305, + "road_tax_note": "EV road tax (JPJ kW schedule, 2026) (power 215 kW, from 288 hp: no JPJ certified figure yet)", + "insurance_rm_yr": 5407, + "insurance_note": "comprehensive car+battery only, Peninsular, 0% NCD, incl. SST+stamp (calculatormalaysia.com EV formula) (SI RM199,888 @ 2.50%)", + "loan_rate_pct": 1.75, + "loan_tenure_yrs": 7, + "loan_down_payment_rm": 19989, + "loan_monthly_rm": 2404.01, + "loan_total_interest_rm": 22038, + "loan_note": "hire purchase, 7yr @ 1.75% flat, 90% financing (ev @ 1.75% flat x 7yr, 90% financing)" + }, + "specs": { + "battery_kwh": 88.0, + "range_km": 340.0, + "power_hp": 288, + "charge_power_kw_dc": 88.0, + "charge_power_kw_ac": 11.0, + "seats": 5 + }, + "registered_my": 0, + "popularity_rating": 1, + "registered_basis": "paultan_no_records", + "registered_as_of": "2026-10", + "provenance": { + "price_rm": { + "method": "measured", + "basis": "published on-the-road price" + }, + "road_tax_rm": { + "method": "computed", + "basis": "JPJ Lampiran B, EV kW schedule (2026)" + }, + "insurance_rm_yr": { + "method": "computed", + "basis": "calculatormalaysia.com EV formula, Peninsular, 0% NCD, incl. SST + stamp" + }, + "loan_total_interest_rm": { + "method": "computed", + "basis": "hire purchase, 7yr @ 1.75% flat, 90% financing (ev @ 1.75% flat x 7yr, 90% financing)" + }, + "energy_kwh_per_100km": { + "method": "computed", + "basis": "battery_kwh / range_km" + } + } } ] } diff --git a/data/fuel.json b/data/fuel.json index 4108be2..f13e311 100644 --- a/data/fuel.json +++ b/data/fuel.json @@ -31,5 +31,10 @@ "diesel_skds": 2.15, "ron95_budi95": 1.99, "diesel_eastmsia": 4.87 + }, + "budi95": { + "quota_l_per_month": 300, + "since": "2026-09-01", + "note": "BUDI95: RON95 at the subsidised pump price (fuel.ron95_rm_per_l) for eligible Malaysians with a valid driving licence, up to quota_l_per_month per person; every litre past it in a month is paid at market_rm_per_l.ron95. Restored to 300 L on 1 Sep 2026 after 200 L from 1 Apr to 31 Aug 2026 (MOF / Bernama, 30 Aug 2026). Set by policy announcement, not by data.gov.my, so scripts/update_fuel_prices.py leaves this block alone; change it by hand when the quota moves." } } diff --git a/data/policy/home-energy.md b/data/policy/home-energy.md new file mode 100644 index 0000000..61ae967 --- /dev/null +++ b/data/policy/home-energy.md @@ -0,0 +1,73 @@ +# Home energy: TNB Time-of-Use, rooftop solar schemes, and solar with a battery + +Injected into the analyst and chat prompts with malaysia-incentives.md. Checked 14 Nov 2026. +Peninsular Malaysia (TNB) only: Sabah (SESB) and Sarawak (SEB) run their own tariffs and solar +schemes, so tell an East Malaysian buyer to check with their utility. + +## TNB Time-of-Use (ToU), domestic + +- Since **1 July 2025** a domestic bill is: energy charge + capacity 4.55 sen/kWh + network + 12.85 sen/kWh + RM10 retail charge (only above 600 kWh a month) + AFA fuel adjustment (only + above 600 kWh; waived up to 800 kWh until Dec 2026) + the Energy Efficiency Incentive rebate + (up to 1,000 kWh; bigger the less you use) + 1.6% KWTBB (above 300 kWh) + 8% service tax on + usage above 600 kWh. +- **Standard tariff** (most homes): one energy charge all day, 27.03 sen/kWh up to 1,500 kWh a + month, 37.03 sen on every kWh above that. +- **ToU tariff** (opt-in): peak **2pm-10pm Monday to Friday**; off-peak **10pm-2pm on weekdays and + all day Saturday and Sunday**. Energy charge 28.52 sen peak / 24.43 sen off-peak up to 1,500 kWh + a month (38.52 / 34.43 above). Capacity, network and the rest are the same as standard. +- **Is ToU worth it?** It saves money when **less than about 64%** of the household's kWh fall in + the weekday 2pm-10pm window (break-even: (27.03 - 24.43) / (28.52 - 24.43) = 0.64). An EV that + charges after 10pm pulls the share down: each off-peak kWh is 2.6 sen cheaper than standard. + The saving is real but small, about RM3 a month on 150 kWh of overnight charging, so ToU is a + habit, not a reason to choose a car. +- **How to switch**: apply in the myTNB app or portal. ToU takes effect once an activated smart + meter is in place; TNB fits one if needed, which can take up to about two months. Most EVs and + wallboxes can schedule charging to start at 10pm. +- **What VoltPilot assumes**: home charging is priced on ToU with 90% of charging off-peak, as + the marginal bill increase on a 400 kWh household (or the bill the buyer typed in). + +## Rooftop solar: which scheme (NEM or Solar ATAP) + +- **New installation today: Solar ATAP is the only scheme open to homes.** NEM 3.0 (NEM Rakyat + for homes, NEM GoMEn for government) took its last applications on **30 Jun 2025**. Solar ATAP + (Energy Commission guideline GP/ST/No.60/2025) started **1 Jan 2026**. +- **Solar ATAP rules (homes)**: use your own solar first; surplus exported to TNB earns a bill + credit at the **energy charge only** (27.03 sen/kWh, not capacity, network, retail or AFA); + credit only up to what you import **in the same month**, and anything beyond that is + **forfeited** (no carry-forward, no cash). Credits run **10 years** from commencement, then the + system is self-consumption only. Up to **5 kW single-phase / 15 kW three-phase** without a TNB + connection check (bigger needs one, RM1,000). A battery (BESS) may be added to an ATAP system. +- **Already on NEM Rakyat? Stay on it.** Existing NEM contracts keep 1:1 kWh offsetting for 10 + years from commencement, with surplus credit rolling over for up to 12 months within the + calendar-year settlement period (ST revision, 19 Aug 2026). In July 2025 the government said + NEM Rakyat users keep the offset on energy, capacity and network charges. A NEM user can + convert to ATAP only by ending the NEM contract, and the ATAP contract then runs only for the + NEM contract's remaining years, so converting is almost never worth it. +- **SuRIA Home rebate**: RM600 per kWac, up to **RM3,000**, for homes commissioned under Solar ATAP + with TNB by **31 Dec 2026**, first come first served, until its 250 MW quota is used. +- **Prices (installer quotes, 2026)**: about RM3,500-4,000 per kW installed, so roughly + RM17,500-20,000 for 5 kW. A rooftop kW yields roughly 1,300-1,450 kWh a year in the Peninsula. + +## Solar alone, or solar with a battery + +- Under ATAP an exported kWh is worth the 27.03 sen energy charge, while a kWh you avoid importing + is worth about 44.4 sen plus taxes (energy + capacity + network). So the panels pay most on + power used **in the house as it is generated**, and a battery's only bill saving is moving + surplus from daytime export into evening use: about **17 sen per kWh stored**, plus any surplus + that would otherwise be forfeited. +- A 10 kWh battery cycling fully every day therefore saves at most about RM50 a month, and + less once the panels have already pushed the bill toward zero. Installed batteries cost about + **RM24,000-36,000** (7-16 kWh, 2026), so the bill alone pays one back in decades, past its + roughly 10-year warranty. +- **When a battery makes sense**: frequent outages (backup for fridge, lights, Wi-Fi, medical + equipment), a household that uses most of its power at night and exports a lot by day, or a bill + still high after solar. Otherwise, solar alone. +- **Solar and an EV**: the car is the biggest battery the house has. Charging it in daylight + (weekends, working from home) stores solar at the full import rate's value, which an export + never earns. Charging after 10pm on ToU is the next cheapest. Solar does not make overnight + charging free: at night the car draws from TNB like any other load. +- The platform's solar banner (`solar_reference` in the chat context, `solar_banner` in the + analyst payload) carries the computed figures for its reference household: 400 kWh a month plus + an EV at 150 kWh, standard tariff, 5 kW of panels, a 10 kWh battery. Quote those numbers rather + than inventing your own, and say they are for a typical home, not this buyer's roof. diff --git a/data/policy/malaysia-incentives.md b/data/policy/malaysia-incentives.md index f9350a8..52cfe6a 100644 --- a/data/policy/malaysia-incentives.md +++ b/data/policy/malaysia-incentives.md @@ -1,6 +1,8 @@ # Static policy context injected into the Gemini 3.6 Flash analyst prompt (D13). No vector store; plain markdown loaded per prompt. -Snapshot checked 12 Nov 2026. Figures that move weekly or monthly carry their date. +Snapshot checked 12 Nov 2026 (fuel quota, solar and ToU rechecked 14 Nov 2026). Figures that move +weekly or monthly carry their date. ToU, rooftop solar schemes and home batteries are in +home-energy.md. ## Malaysia EV incentives @@ -13,7 +15,8 @@ Snapshot checked 12 Nov 2026. Figures that move weekly or monthly carry their da year at 150 kW and RM280 at 210 kW; the old RM2 flat rate is gone. **Hybrids and plug-in hybrids pay the standard engine-cc formula.** - **Charging relief**: individual income-tax relief up to **RM2,500** for EV charging equipment. -- **Solar**: NEM Rakyat (net energy metering) lets residential solar exports offset consumption. +- **Solar**: new home installations go on **Solar ATAP** (since 1 Jan 2026); NEM closed to new + applicants on 30 Jun 2025. SuRIA Home rebate up to RM3,000 until 31 Dec 2026. See home-energy.md. - **JPJ**: green number plates for EVs. ## Home charging @@ -21,7 +24,8 @@ Snapshot checked 12 Nov 2026. Figures that move weekly or monthly carry their da - There is **no special EV tariff**: the old RM0.25/kWh residential EV block no longer exists. Home charging is billed under the TNB domestic tariff (since July 2025): generation 27.03 sen/kWh (37.03 sen above 1,500 kWh a month), capacity 4.55 sen, network 12.85 sen; Time-of-Use energy - 28.52 sen peak / 24.43 sen off-peak. Charging overnight off-peak is the cheapest option. + 28.52 sen peak / 24.43 sen off-peak (opt-in; peak is 2pm-10pm on weekdays). Charging after + 10pm is the cheapest option. Details in home-energy.md. - **AFA fuel surcharge**: +3.60 sen/kWh for November 2026; waived for households using 800 kWh a month or less until Dec 2026 (600 kWh or less from Jan 2027). - **Public charging**: about **RM1.10/kWh AC** and **RM1.40/kWh DC** (JomCharge, Aug 2026); prices @@ -32,6 +36,16 @@ Snapshot checked 12 Nov 2026. Figures that move weekly or monthly carry their da ## Fuel (week of 12 Nov 2026, data.gov.my; changes weekly) - **RON95**: RM1.99/L for eligible Malaysians (BUDI95); RM3.87/L unsubsidised. +- **BUDI95 monthly quota: 300 litres** per eligible Malaysian with a valid driving licence, + restored on **1 Sep 2026** (it was cut to 200 L from 1 Apr to 31 Aug 2026 when fuel prices + surged). Every litre past the quota in a month is paid at the unsubsidised price. Registered + e-hailing drivers get a larger quota (800 L during the 200 L period). Non-citizens pay the + unsubsidised price for every litre. The quota belongs to the person, not the car, so a second + car in the household drawing on it leaves less for this one. +- **What VoltPilot assumes**: the buyer is eligible and the car uses the whole quota. Hybrid and + PHEV petrol is priced at RM1.99 up to 300 L a month (3,600 L a year) and at the unsubsidised + price beyond it. At 5 L/100 km the quota covers 72,000 km a year, so it binds only for high + mileage or thirsty cars (a 9 L/100 km hybrid passes it at 40,000 km a year). - **RON97**: RM4.20/L. **Diesel**: RM2.10/L subsidised (BUDI, Peninsular); RM4.87/L market. ## CO2 diff --git a/data/solar_avg.json b/data/solar_avg.json index a7a3180..9ae40a9 100644 --- a/data/solar_avg.json +++ b/data/solar_avg.json @@ -1,15 +1,28 @@ { "_meta": { "currency": "RM", - "note": "Static average-Malaysia residential solar return (D6). No irradiance model, no Open-Meteo. Used ONLY for the conditional savings banner (D-SOLAR). Auto-hidden if home charging is unavailable or user did not tick 'consider solar'." + "updated_at": "2026-11-14", + "note": "Inputs for the solar banner (D6, D-SOLAR), shown only when the buyer ticked 'consider solar' AND can charge at home. These are ASSUMPTIONS for one reference household, not figures: backend/app/services/solar.py turns them into capex, yearly savings and payback by billing the household on TNB's own arithmetic (engines.tnb_tou_bill over tariff.json), with and without the panels, under Solar ATAP rules. So the banner follows tariff.json when the tariff or AFA moves. Replaces the NEM-era static 'RM34,000 / RM4,300 a year / 7.9 years', which credited every exported kWh at the full retail rate; NEM 3.0 closed to new applications on 30 Jun 2025.", + "scheme": "Solar ATAP (Energy Commission guideline GP/ST/No.60/2025, in force 1 Jan 2026, Peninsular Malaysia): domestic exports are credited at the Energy Charge only (no capacity, network, retail or AFA), only up to what the house imports that month, and the remainder is forfeited with no carry-forward. Credits run 10 years from commencement; after that the system is self-consumption only. Single-phase homes up to 5 kW without a connection check." }, "solar": { - "system_kw_peak": 5, - "capex_rm": 34000, - "savings_rm_per_year": 4300, - "payback_years": 7.9, + "system_kw": 5, + "capex_rm_per_kw": 3750, + "capex_source": "Installer pricing RM3,500-4,000 per kW installed, residential, 2026 (solaratap.com.my calculator); midpoint taken.", + "yield_kwh_per_kwp_yr": 1350, + "yield_source": "Peninsular rooftop planning range 1,300-1,450 kWh/kWp/yr after system losses (installer and calculator guides, 2026).", + "household_kwh_month": 400, + "household_peak_share": 0.6, + "household_daytime_share": 0.35, + "household_note": "The engine's reference household (tariff.json home_household_assumptions: 400 kWh a month). daytime_share is the part of the household's own use that happens while the panels generate; a house that is empty on weekdays sits near a third.", + "ev_kwh_month": 150, + "ev_note": "The reference EV draw in tariff.json, charged overnight, so none of it comes straight off the panels.", + "battery_kwh": 10, + "battery_capex_rm": 25000, + "battery_round_trip": 0.9, + "battery_source": "Installed home batteries RM23,999 (7 kWh) to RM35,999 (14 kWh), RM24,999 (16 kWh) (trexon.my 2026 price list); RM25,000 for a 10 kWh unit taken.", + "credit_years": 10, "lifetime_years": 25, - "savings_10yr_rm": 43000, - "note": "Typical 5kWp system, average Malaysian insolation, net-metering (NEM) rooftop program." + "rebate_note": "SuRIA Home pays RM600 per kWac, up to RM3,000, to Solar ATAP homes commissioned with TNB by 31 Dec 2026 or until its 250 MW quota is used. Not subtracted from capex: it ends inside the year." } -} \ No newline at end of file +} diff --git a/data/tariff.json b/data/tariff.json index 9d54644..807680d 100644 --- a/data/tariff.json +++ b/data/tariff.json @@ -1,7 +1,7 @@ { "_meta": { "currency": "RM", - "updated_at": "2026-11-12", + "updated_at": "2026-11-14", "source": "TNB Domestic ToU (TNB calculator-domesticTOU.js v1.1.65) + JomCharge app Aug 2026. The 2023 EV residential block (home_ev_special RM0.25) no longer exists; home EV charging is billed under the standard Domestic ToU tariff.", "notes": [ "home_ev_marginal_rm_per_kwh is the MARGINAL cost of adding EV charging to a baseline 400 kWh/month household under Domestic ToU (10% peak / 90% off-peak overnight charging), validated in scripts/used_market/compute_charging_cost.py. Representative 150 kWh/month EV draw -> RM74.79 marginal bill delta.", @@ -106,6 +106,11 @@ ] ] } + }, + "domestic_general": { + "note": "The standard (non-ToU) Domestic tariff most homes are on: one Energy Charge for every hour, 27.03 sen/kWh up to 1,500 kWh a month and 37.03 sen on every kWh above. Capacity, network, retail, AFA, the efficiency incentive, KWTBB and service tax are the same as under domestic_tou. ToU is opt-in through myTNB and needs a smart meter. Solar ATAP credits a home's exports at this Energy Charge.", + "energy_tier1": 0.2703, + "energy_tier2": 0.3703 } }, "public_charging_rm_per_kwh": { @@ -120,4 +125,4 @@ "from_2026": "JPJ kW schedule", "hybrid_road_tax": "standard ICE formula" } -} \ No newline at end of file +} diff --git a/data/used_market_raw/catalog_flat.json b/data/used_market_raw/catalog_flat.json index 243d497..4ffb6a4 100644 --- a/data/used_market_raw/catalog_flat.json +++ b/data/used_market_raw/catalog_flat.json @@ -1 +1 @@ -[{"brand": "Proton", "model": "eMas 5", "id": "proton-emas-5"}, {"brand": "BYD", "model": "Atto 3", "id": "byd-atto-3"}, {"brand": "BYD", "model": "Seal", "id": "byd-seal"}, {"brand": "Tesla", "model": "Model 3", "id": "tesla-model-3"}, {"brand": "Tesla", "model": "Model Y", "id": "tesla-model-y"}, {"brand": "XPeng", "model": "G6", "id": "xpeng-g6"}, {"brand": "Volvo", "model": "EX30", "id": "volvo-ex30"}, {"brand": "MG", "model": "4", "id": "mg4"}, {"brand": "Aion", "model": "Y Plus", "id": "gac-aion-y-plus"}, {"brand": "GWM", "model": "Ora Good Cat", "id": "ora-good-cat"}, {"brand": "Chery", "model": "Omoda E5", "id": "chery-omoda-e5"}, {"brand": "smart", "model": "#3", "id": "smart-3"}, {"brand": "Toyota", "model": "Corolla Cross", "id": "toyota-corolla-cross-hybrid"}, {"brand": "Toyota", "model": "Camry", "id": "toyota-camry-hybrid"}, {"brand": "Honda", "model": "HR-V", "id": "honda-hrv-ehev"}, {"brand": "Honda", "model": "Civic", "id": "honda-civic-ehev"}, {"brand": "Wuling", "model": "Bingo", "id": "wuling-bingo"}, {"brand": "Perodua", "model": "QV-E", "id": "perodua-qv-e"}, {"brand": "Seres", "model": "3", "id": "seres-3"}, {"brand": "BYD", "model": "Atto 2", "id": "byd-atto-2"}, {"brand": "BYD", "model": "Seal 6", "id": "byd-seal-6"}, {"brand": "Dongfeng", "model": "Box", "id": "dongfeng-box"}, {"brand": "Proton", "model": "eMas 7", "id": "proton-emas-7"}, {"brand": "Aion", "model": "ES", "id": "aion-es"}, {"brand": "Leapmotor", "model": "B10", "id": "leapmotor-b10"}, {"brand": "Dongfeng", "model": "Vigo", "id": "dongfeng-vigo"}, {"brand": "BYD", "model": "M6", "id": "byd-m6"}, {"brand": "MG", "model": "S5", "id": "mg-s5"}, {"brand": "iCaur", "model": "03", "id": "icaur-03"}, {"brand": "Neta", "model": "X", "id": "neta-x"}, {"brand": "Leapmotor", "model": "C10", "id": "leapmotor-c10"}, {"brand": "iCaur", "model": "V23", "id": "icaur-v23"}, {"brand": "Honda", "model": "e:N1", "id": "honda-e:n1"}, {"brand": "Zeekr", "model": "X", "id": "zeekr-x"}, {"brand": "BYD", "model": "Sealion 7", "id": "byd-sealion-7"}, {"brand": "Renault", "model": "Zoe", "id": "renault-zoe"}, {"brand": "Nissan", "model": "Leaf", "id": "nissan-leaf"}, {"brand": "smart", "model": "#1", "id": "smart-1"}, {"brand": "Dongfeng", "model": "007", "id": "dongfeng-007"}, {"brand": "Zeekr", "model": "7X", "id": "zeekr-7x"}, {"brand": "Suzuki", "model": "eVitara", "id": "suzuki-evitara"}, {"brand": "MINI", "model": "Electric", "id": "mini-electric"}, {"brand": "Toyota", "model": "Urban Cruiser", "id": "toyota-urban-cruiser"}, {"brand": "smart", "model": "#5", "id": "smart-5"}, {"brand": "MINI", "model": "Aceman", "id": "mini-aceman"}, {"brand": "Toyota", "model": "bZ4X", "id": "toyota-bz4x"}, {"brand": "Toyota", "model": "Hilux", "id": "toyota-hilux"}, {"brand": "Maxus", "model": "eTerron 9", "id": "maxus-eterron-9"}, {"brand": "Volvo", "model": "EC40", "id": "volvo-ec40"}, {"brand": "BMW", "model": "iX1", "id": "bmw-ix1"}, {"brand": "BMW", "model": "iX1 L", "id": "bmw-ix1-l"}, {"brand": "MINI", "model": "Countryman", "id": "mini-countryman"}, {"brand": "Maxus", "model": "MIFA 9", "id": "maxus-mifa-9"}, {"brand": "XPeng", "model": "X9", "id": "xpeng-x9"}, {"brand": "BMW", "model": "iX2", "id": "bmw-ix2"}, {"brand": "BMW", "model": "i4", "id": "bmw-i4"}, {"brand": "Mercedes-Benz", "model": "EQA", "id": "mercedes-benz-eqa"}, {"brand": "Denza", "model": "D9", "id": "denza-d9"}, {"brand": "Zeekr", "model": "009", "id": "zeekr-009"}, {"brand": "MG", "model": "Cyberster", "id": "mg-cyberster"}, {"brand": "Volvo", "model": "ES90", "id": "volvo-es90"}, {"brand": "Kia", "model": "EV9", "id": "kia-ev9"}, {"brand": "Denza", "model": "Z9 GT", "id": "denza-z9-gt"}, {"brand": "BMW", "model": "i5", "id": "bmw-i5"}, {"brand": "BMW", "model": "iX3", "id": "bmw-ix3"}, {"brand": "Mercedes-Benz", "model": "EQE", "id": "mercedes-benz-eqe"}, {"brand": "Mercedes-Benz", "model": "EQE SUV", "id": "mercedes-benz-eqe-suv"}, {"brand": "BMW", "model": "iX", "id": "bmw-ix"}, {"brand": "Lexus", "model": "RZ", "id": "lexus-rz"}, {"brand": "BMW", "model": "i4 M50", "id": "bmw-i4-m50"}, {"brand": "Volvo", "model": "EX90", "id": "volvo-ex90"}, {"brand": "Hyundai", "model": "Ioniq 5 N", "id": "hyundai-ioniq-5-n"}, {"brand": "Hyundai", "model": "Ioniq 6 N", "id": "hyundai-ioniq-6-n"}, {"brand": "Mercedes-Benz", "model": "EQV", "id": "mercedes-benz-eqv"}, {"brand": "Lotus", "model": "Emeya", "id": "lotus-emeya"}, {"brand": "Audi", "model": "Q8 e-tron", "id": "audi-q8-e-tron"}, {"brand": "Audi", "model": "Q8 e-tron Sportback", "id": "audi-q8-e-tron-sportback"}, {"brand": "Lotus", "model": "Eletre", "id": "lotus-eletre"}, {"brand": "Porsche", "model": "Macan Electric", "id": "porsche-macan-electric"}, {"brand": "Mercedes-Benz", "model": "EQS SUV", "id": "mercedes-benz-eqs-suv"}, {"brand": "Mercedes-Benz", "model": "EQS", "id": "mercedes-benz-eqs"}, {"brand": "Mercedes-Benz", "model": "AMG EQE", "id": "mercedes-benz-amg-eqe"}, {"brand": "BMW", "model": "i7", "id": "bmw-i7"}, {"brand": "Mercedes-Benz", "model": "AMG EQS", "id": "mercedes-benz-amg-eqs"}, {"brand": "Mercedes-Benz", "model": "G-Class", "id": "mercedes-benz-g-class"}, {"brand": "Mercedes-Benz", "model": "Maybach EQS SUV", "id": "mercedes-benz-maybach-eqs-suv"}, {"brand": "Chery", "model": "Tiggo Cross", "id": "chery-tiggo-cross"}, {"brand": "Toyota", "model": "Vios", "id": "toyota-vios"}, {"brand": "Proton", "model": "eMas 7 PHEV", "id": "proton-emas-7-phev"}, {"brand": "Toyota", "model": "Yaris Cross", "id": "toyota-yaris-cross"}, {"brand": "Honda", "model": "City", "id": "honda-city"}, {"brand": "Honda", "model": "City Hatchback", "id": "honda-city-hatchback"}, {"brand": "Nissan", "model": "Kicks e-Power", "id": "nissan-kicks-e-power"}, {"brand": "Foton", "model": "Tunland", "id": "foton-tunland"}, {"brand": "Chery", "model": "Tiggo 7", "id": "chery-tiggo-7"}, {"brand": "Suzuki", "model": "Fronx", "id": "suzuki-fronx"}, {"brand": "GWM", "model": "Haval H6", "id": "great-wall-haval-h6"}, {"brand": "Nissan", "model": "Serena e-Power", "id": "nissan-serena-e-power"}, {"brand": "Chery", "model": "Tiggo 8", "id": "chery-tiggo-8"}, {"brand": "Honda", "model": "CR-V", "id": "honda-cr-v"}, {"brand": "Volkswagen", "model": "Golf", "id": "volkswagen-golf"}, {"brand": "Volkswagen", "model": "Tayron", "id": "volkswagen-tayron"}, {"brand": "Hyundai", "model": "Tucson", "id": "hyundai-tucson"}, {"brand": "Toyota", "model": "Innova Zenix", "id": "toyota-innova-zenix"}, {"brand": "Hyundai", "model": "Santa Fe", "id": "hyundai-santa-fe"}, {"brand": "Lexus", "model": "LBX", "id": "lexus-lbx"}, {"brand": "Mazda", "model": "CX-60", "id": "mazda-cx-60"}, {"brand": "GWM", "model": "Tank 300", "id": "great-wall-tank-300"}, {"brand": "Mercedes-Benz", "model": "A-Class Sedan", "id": "mercedes-benz-a-class-sedan"}, {"brand": "Volvo", "model": "XC40", "id": "volvo-xc40"}, {"brand": "GWM", "model": "Wey G9", "id": "great-wall-wey-g9"}, {"brand": "Honda", "model": "Prelude", "id": "honda-prelude"}, {"brand": "Toyota", "model": "Harrier", "id": "toyota-harrier"}, {"brand": "Mercedes-Benz", "model": "C-Class", "id": "mercedes-benz-c-class"}, {"brand": "Mazda", "model": "CX-80", "id": "mazda-cx-80"}, {"brand": "BMW", "model": "X3", "id": "bmw-x3"}, {"brand": "Gac", "model": "M8", "id": "gac-m8"}, {"brand": "GWM", "model": "Tank 500", "id": "great-wall-tank-500"}, {"brand": "Volvo", "model": "XC60", "id": "volvo-xc60"}, {"brand": "Mercedes-Benz", "model": "GLC", "id": "mercedes-benz-glc"}, {"brand": "BMW", "model": "5 Series", "id": "bmw-5-series"}, {"brand": "Mercedes-Benz", "model": "AMG A-Class Sedan", "id": "mercedes-benz-amg-a-class-sedan"}, {"brand": "Mercedes-Benz", "model": "AMG GLA", "id": "mercedes-benz-amg-gla"}, {"brand": "Mercedes-Benz", "model": "E-Class", "id": "mercedes-benz-e-class"}, {"brand": "Lexus", "model": "NX", "id": "lexus-nx"}, {"brand": "Mercedes-Benz", "model": "AMG GLB", "id": "mercedes-benz-amg-glb"}, {"brand": "Volvo", "model": "XC90", "id": "volvo-xc90"}, {"brand": "Mercedes-Benz", "model": "GLC Coupe", "id": "mercedes-benz-glc-coupe"}, {"brand": "Audi", "model": "A5 Sportback", "id": "audi-a5-sportback"}, {"brand": "Mercedes-Benz", "model": "AMG C-Class", "id": "mercedes-benz-amg-c-class"}, {"brand": "Denza", "model": "B8", "id": "denza-b8"}, {"brand": "Audi", "model": "Q7", "id": "audi-q7"}, {"brand": "BMW", "model": "X5", "id": "bmw-x5"}, {"brand": "Lexus", "model": "RX", "id": "lexus-rx"}, {"brand": "Mercedes-Benz", "model": "GLE", "id": "mercedes-benz-gle"}, {"brand": "Mercedes-Benz", "model": "AMG GLC Coupe", "id": "mercedes-benz-amg-glc-coupe"}, {"brand": "Mercedes-Benz", "model": "CLE", "id": "mercedes-benz-cle"}, {"brand": "Toyota", "model": "Vellfire", "id": "toyota-vellfire"}, {"brand": "BMW", "model": "X7", "id": "bmw-x7"}, {"brand": "BMW", "model": "7 Series", "id": "bmw-7-series"}, {"brand": "Mercedes-Benz", "model": "AMG CLE", "id": "mercedes-benz-amg-cle"}, {"brand": "BMW", "model": "X6", "id": "bmw-x6"}, {"brand": "Mercedes-Benz", "model": "S-Class", "id": "mercedes-benz-s-class"}, {"brand": "Porsche", "model": "Cayenne Coupe", "id": "porsche-cayenne-coupe"}, {"brand": "Mercedes-Benz", "model": "AMG GLE Coupe", "id": "mercedes-benz-amg-gle-coupe"}, {"brand": "Mercedes-Benz", "model": "AMG SL", "id": "mercedes-benz-amg-sl"}, {"brand": "Mercedes-Benz", "model": "AMG GLE", "id": "mercedes-benz-amg-gle"}, {"brand": "BMW", "model": "M5", "id": "bmw-m5"}, {"brand": "Lexus", "model": "LM", "id": "lexus-lm"}, {"brand": "Lexus", "model": "LX", "id": "lexus-lx"}, {"brand": "Mercedes-Benz", "model": "Maybach S-Class", "id": "mercedes-benz-maybach-s-class"}, {"brand": "Mercedes-Benz", "model": "Maybach GLS", "id": "mercedes-benz-maybach-gls"}, {"brand": "Mercedes-Benz", "model": "AMG G-Class", "id": "mercedes-benz-amg-g-class"}, {"brand": "Mercedes-Benz", "model": "AMG S-Class", "id": "mercedes-benz-amg-s-class"}, {"brand": "Jaecoo", "model": "J7 PHEV", "id": "jaecoo-j7-phev"}, {"brand": "Omoda", "model": "C9 PHEV", "id": "omoda-c9-phev"}, {"brand": "Rolls-Royce", "model": "Spectre", "id": "rolls-royce-spectre"}, {"brand": "Higer", "model": "H5C (Ace E1)", "id": "higer-h5c-ace-e1"}, {"brand": "Higer", "model": "H7V", "id": "higer-h7v"}, {"brand": "Ford", "model": "Mustang Mach-E", "id": "ford-mustang-mach-e"}, {"brand": "Porsche", "model": "Taycan", "id": "porsche-taycan"}, {"brand": "Lexus", "model": "ES", "id": "lexus-es"}, {"brand": "MG", "model": "ZS Hybrid+", "id": "mg-zs"}, {"brand": "Wuling", "model": "Porta EV", "id": "wuling-porta-ev"}, {"brand": "Jaecoo", "model": "J5 EV", "id": "jaecoo-j5-ev"}, {"brand": "Porsche", "model": "Cayenne Electric", "id": "porsche-cayenne-electric"}, {"brand": "Porsche", "model": "Cayenne Coupe Electric", "id": "porsche-cayenne-coupe-electric"}, {"brand": "Mercedes-Benz", "model": "CLA Electric", "id": "mercedes-benz-cla-electric"}, {"brand": "Jetour", "model": "T2 i-DM", "id": "jetour-t2"}, {"brand": "JAC", "model": "T9 PHEV", "id": "jac-t9"}] \ No newline at end of file +[{"brand": "Proton", "model": "eMas 5", "id": "proton-emas-5"}, {"brand": "BYD", "model": "Atto 3", "id": "byd-atto-3"}, {"brand": "BYD", "model": "Seal", "id": "byd-seal"}, {"brand": "Tesla", "model": "Model 3", "id": "tesla-model-3"}, {"brand": "Tesla", "model": "Model Y", "id": "tesla-model-y"}, {"brand": "XPeng", "model": "G6", "id": "xpeng-g6"}, {"brand": "Volvo", "model": "EX30", "id": "volvo-ex30"}, {"brand": "MG", "model": "4", "id": "mg4"}, {"brand": "Aion", "model": "Y Plus", "id": "gac-aion-y-plus"}, {"brand": "GWM", "model": "Ora Good Cat", "id": "ora-good-cat"}, {"brand": "Chery", "model": "Omoda E5", "id": "chery-omoda-e5"}, {"brand": "smart", "model": "#3", "id": "smart-3"}, {"brand": "Toyota", "model": "Corolla Cross", "id": "toyota-corolla-cross-hybrid"}, {"brand": "Toyota", "model": "Camry", "id": "toyota-camry-hybrid"}, {"brand": "Honda", "model": "HR-V", "id": "honda-hrv-ehev"}, {"brand": "Honda", "model": "Civic", "id": "honda-civic-ehev"}, {"brand": "Wuling", "model": "Bingo", "id": "wuling-bingo"}, {"brand": "Perodua", "model": "QV-E", "id": "perodua-qv-e"}, {"brand": "Seres", "model": "3", "id": "seres-3"}, {"brand": "BYD", "model": "Atto 2", "id": "byd-atto-2"}, {"brand": "BYD", "model": "Seal 6", "id": "byd-seal-6"}, {"brand": "Dongfeng", "model": "Box", "id": "dongfeng-box"}, {"brand": "Proton", "model": "eMas 7", "id": "proton-emas-7"}, {"brand": "Aion", "model": "ES", "id": "aion-es"}, {"brand": "Leapmotor", "model": "B10", "id": "leapmotor-b10"}, {"brand": "Dongfeng", "model": "Vigo", "id": "dongfeng-vigo"}, {"brand": "BYD", "model": "M6", "id": "byd-m6"}, {"brand": "MG", "model": "S5", "id": "mg-s5"}, {"brand": "iCaur", "model": "03", "id": "icaur-03"}, {"brand": "Neta", "model": "X", "id": "neta-x"}, {"brand": "Leapmotor", "model": "C10", "id": "leapmotor-c10"}, {"brand": "iCaur", "model": "V23", "id": "icaur-v23"}, {"brand": "Honda", "model": "e:N1", "id": "honda-e:n1"}, {"brand": "Zeekr", "model": "X", "id": "zeekr-x"}, {"brand": "BYD", "model": "Sealion 7", "id": "byd-sealion-7"}, {"brand": "Renault", "model": "Zoe", "id": "renault-zoe"}, {"brand": "Nissan", "model": "Leaf", "id": "nissan-leaf"}, {"brand": "smart", "model": "#1", "id": "smart-1"}, {"brand": "Dongfeng", "model": "007", "id": "dongfeng-007"}, {"brand": "Zeekr", "model": "7X", "id": "zeekr-7x"}, {"brand": "Suzuki", "model": "eVitara", "id": "suzuki-evitara"}, {"brand": "MINI", "model": "Electric", "id": "mini-electric"}, {"brand": "Toyota", "model": "Urban Cruiser", "id": "toyota-urban-cruiser"}, {"brand": "smart", "model": "#5", "id": "smart-5"}, {"brand": "MINI", "model": "Aceman", "id": "mini-aceman"}, {"brand": "Toyota", "model": "bZ4X", "id": "toyota-bz4x"}, {"brand": "Toyota", "model": "Hilux", "id": "toyota-hilux"}, {"brand": "Maxus", "model": "eTerron 9", "id": "maxus-eterron-9"}, {"brand": "Volvo", "model": "EC40", "id": "volvo-ec40"}, {"brand": "BMW", "model": "iX1", "id": "bmw-ix1"}, {"brand": "BMW", "model": "iX1 L", "id": "bmw-ix1-l"}, {"brand": "MINI", "model": "Countryman", "id": "mini-countryman"}, {"brand": "Maxus", "model": "MIFA 9", "id": "maxus-mifa-9"}, {"brand": "XPeng", "model": "X9", "id": "xpeng-x9"}, {"brand": "BMW", "model": "iX2", "id": "bmw-ix2"}, {"brand": "BMW", "model": "i4", "id": "bmw-i4"}, {"brand": "Mercedes-Benz", "model": "EQA", "id": "mercedes-benz-eqa"}, {"brand": "Denza", "model": "D9", "id": "denza-d9"}, {"brand": "Zeekr", "model": "009", "id": "zeekr-009"}, {"brand": "MG", "model": "Cyberster", "id": "mg-cyberster"}, {"brand": "Volvo", "model": "ES90", "id": "volvo-es90"}, {"brand": "Kia", "model": "EV9", "id": "kia-ev9"}, {"brand": "Denza", "model": "Z9 GT", "id": "denza-z9-gt"}, {"brand": "BMW", "model": "i5", "id": "bmw-i5"}, {"brand": "BMW", "model": "iX3", "id": "bmw-ix3"}, {"brand": "Mercedes-Benz", "model": "EQE", "id": "mercedes-benz-eqe"}, {"brand": "Mercedes-Benz", "model": "EQE SUV", "id": "mercedes-benz-eqe-suv"}, {"brand": "BMW", "model": "iX", "id": "bmw-ix"}, {"brand": "Lexus", "model": "RZ", "id": "lexus-rz"}, {"brand": "BMW", "model": "i4 M50", "id": "bmw-i4-m50"}, {"brand": "Volvo", "model": "EX90", "id": "volvo-ex90"}, {"brand": "Hyundai", "model": "Ioniq 5 N", "id": "hyundai-ioniq-5-n"}, {"brand": "Hyundai", "model": "Ioniq 6 N", "id": "hyundai-ioniq-6-n"}, {"brand": "Mercedes-Benz", "model": "EQV", "id": "mercedes-benz-eqv"}, {"brand": "Lotus", "model": "Emeya", "id": "lotus-emeya"}, {"brand": "Audi", "model": "Q8 e-tron", "id": "audi-q8-e-tron"}, {"brand": "Audi", "model": "Q8 e-tron Sportback", "id": "audi-q8-e-tron-sportback"}, {"brand": "Lotus", "model": "Eletre", "id": "lotus-eletre"}, {"brand": "Porsche", "model": "Macan Electric", "id": "porsche-macan-electric"}, {"brand": "Mercedes-Benz", "model": "EQS SUV", "id": "mercedes-benz-eqs-suv"}, {"brand": "Mercedes-Benz", "model": "EQS", "id": "mercedes-benz-eqs"}, {"brand": "Mercedes-Benz", "model": "AMG EQE", "id": "mercedes-benz-amg-eqe"}, {"brand": "BMW", "model": "i7", "id": "bmw-i7"}, {"brand": "Mercedes-Benz", "model": "AMG EQS", "id": "mercedes-benz-amg-eqs"}, {"brand": "Mercedes-Benz", "model": "G-Class", "id": "mercedes-benz-g-class"}, {"brand": "Mercedes-Benz", "model": "Maybach EQS SUV", "id": "mercedes-benz-maybach-eqs-suv"}, {"brand": "Chery", "model": "Tiggo Cross", "id": "chery-tiggo-cross"}, {"brand": "Toyota", "model": "Vios", "id": "toyota-vios"}, {"brand": "Proton", "model": "eMas 7 PHEV", "id": "proton-emas-7-phev"}, {"brand": "Toyota", "model": "Yaris Cross", "id": "toyota-yaris-cross"}, {"brand": "Honda", "model": "City", "id": "honda-city"}, {"brand": "Honda", "model": "City Hatchback", "id": "honda-city-hatchback"}, {"brand": "Nissan", "model": "Kicks e-Power", "id": "nissan-kicks-e-power"}, {"brand": "Foton", "model": "Tunland", "id": "foton-tunland"}, {"brand": "Chery", "model": "Tiggo 7", "id": "chery-tiggo-7"}, {"brand": "Suzuki", "model": "Fronx", "id": "suzuki-fronx"}, {"brand": "GWM", "model": "Haval H6", "id": "great-wall-haval-h6"}, {"brand": "Nissan", "model": "Serena e-Power", "id": "nissan-serena-e-power"}, {"brand": "Chery", "model": "Tiggo 8", "id": "chery-tiggo-8"}, {"brand": "Honda", "model": "CR-V", "id": "honda-cr-v"}, {"brand": "Volkswagen", "model": "Golf", "id": "volkswagen-golf"}, {"brand": "Volkswagen", "model": "Tayron", "id": "volkswagen-tayron"}, {"brand": "Hyundai", "model": "Tucson", "id": "hyundai-tucson"}, {"brand": "Toyota", "model": "Innova Zenix", "id": "toyota-innova-zenix"}, {"brand": "Hyundai", "model": "Santa Fe", "id": "hyundai-santa-fe"}, {"brand": "Lexus", "model": "LBX", "id": "lexus-lbx"}, {"brand": "Mazda", "model": "CX-60", "id": "mazda-cx-60"}, {"brand": "GWM", "model": "Tank 300", "id": "great-wall-tank-300"}, {"brand": "Mercedes-Benz", "model": "A-Class Sedan", "id": "mercedes-benz-a-class-sedan"}, {"brand": "Volvo", "model": "XC40", "id": "volvo-xc40"}, {"brand": "GWM", "model": "Wey G9", "id": "great-wall-wey-g9"}, {"brand": "Honda", "model": "Prelude", "id": "honda-prelude"}, {"brand": "Toyota", "model": "Harrier", "id": "toyota-harrier"}, {"brand": "Mercedes-Benz", "model": "C-Class", "id": "mercedes-benz-c-class"}, {"brand": "Mazda", "model": "CX-80", "id": "mazda-cx-80"}, {"brand": "BMW", "model": "X3", "id": "bmw-x3"}, {"brand": "Gac", "model": "M8", "id": "gac-m8"}, {"brand": "GWM", "model": "Tank 500", "id": "great-wall-tank-500"}, {"brand": "Volvo", "model": "XC60", "id": "volvo-xc60"}, {"brand": "Mercedes-Benz", "model": "GLC", "id": "mercedes-benz-glc"}, {"brand": "BMW", "model": "5 Series", "id": "bmw-5-series"}, {"brand": "Mercedes-Benz", "model": "AMG A-Class Sedan", "id": "mercedes-benz-amg-a-class-sedan"}, {"brand": "Mercedes-Benz", "model": "AMG GLA", "id": "mercedes-benz-amg-gla"}, {"brand": "Mercedes-Benz", "model": "E-Class", "id": "mercedes-benz-e-class"}, {"brand": "Lexus", "model": "NX", "id": "lexus-nx"}, {"brand": "Mercedes-Benz", "model": "AMG GLB", "id": "mercedes-benz-amg-glb"}, {"brand": "Volvo", "model": "XC90", "id": "volvo-xc90"}, {"brand": "Mercedes-Benz", "model": "GLC Coupe", "id": "mercedes-benz-glc-coupe"}, {"brand": "Audi", "model": "A5 Sportback", "id": "audi-a5-sportback"}, {"brand": "Mercedes-Benz", "model": "AMG C-Class", "id": "mercedes-benz-amg-c-class"}, {"brand": "Denza", "model": "B8", "id": "denza-b8"}, {"brand": "Audi", "model": "Q7", "id": "audi-q7"}, {"brand": "BMW", "model": "X5", "id": "bmw-x5"}, {"brand": "Lexus", "model": "RX", "id": "lexus-rx"}, {"brand": "Mercedes-Benz", "model": "GLE", "id": "mercedes-benz-gle"}, {"brand": "Mercedes-Benz", "model": "AMG GLC Coupe", "id": "mercedes-benz-amg-glc-coupe"}, {"brand": "Mercedes-Benz", "model": "CLE", "id": "mercedes-benz-cle"}, {"brand": "Toyota", "model": "Vellfire", "id": "toyota-vellfire"}, {"brand": "BMW", "model": "X7", "id": "bmw-x7"}, {"brand": "BMW", "model": "7 Series", "id": "bmw-7-series"}, {"brand": "Mercedes-Benz", "model": "AMG CLE", "id": "mercedes-benz-amg-cle"}, {"brand": "BMW", "model": "X6", "id": "bmw-x6"}, {"brand": "Mercedes-Benz", "model": "S-Class", "id": "mercedes-benz-s-class"}, {"brand": "Porsche", "model": "Cayenne Coupe", "id": "porsche-cayenne-coupe"}, {"brand": "Mercedes-Benz", "model": "AMG GLE Coupe", "id": "mercedes-benz-amg-gle-coupe"}, {"brand": "Mercedes-Benz", "model": "AMG SL", "id": "mercedes-benz-amg-sl"}, {"brand": "Mercedes-Benz", "model": "AMG GLE", "id": "mercedes-benz-amg-gle"}, {"brand": "BMW", "model": "M5", "id": "bmw-m5"}, {"brand": "Lexus", "model": "LM", "id": "lexus-lm"}, {"brand": "Lexus", "model": "LX", "id": "lexus-lx"}, {"brand": "Mercedes-Benz", "model": "Maybach S-Class", "id": "mercedes-benz-maybach-s-class"}, {"brand": "Mercedes-Benz", "model": "Maybach GLS", "id": "mercedes-benz-maybach-gls"}, {"brand": "Mercedes-Benz", "model": "AMG G-Class", "id": "mercedes-benz-amg-g-class"}, {"brand": "Mercedes-Benz", "model": "AMG S-Class", "id": "mercedes-benz-amg-s-class"}, {"brand": "Jaecoo", "model": "J7 PHEV", "id": "jaecoo-j7-phev"}, {"brand": "Omoda", "model": "C9 PHEV", "id": "omoda-c9-phev"}, {"brand": "Rolls-Royce", "model": "Spectre", "id": "rolls-royce-spectre"}, {"brand": "Higer", "model": "H5C (Ace E1)", "id": "higer-h5c-ace-e1"}, {"brand": "Higer", "model": "H7V", "id": "higer-h7v"}, {"brand": "Ford", "model": "Mustang Mach-E", "id": "ford-mustang-mach-e"}, {"brand": "Porsche", "model": "Taycan", "id": "porsche-taycan"}, {"brand": "Lexus", "model": "ES", "id": "lexus-es"}, {"brand": "MG", "model": "ZS Hybrid+", "id": "mg-zs"}, {"brand": "Wuling", "model": "Porta EV", "id": "wuling-porta-ev"}, {"brand": "Jaecoo", "model": "J5 EV", "id": "jaecoo-j5-ev"}, {"brand": "Porsche", "model": "Cayenne Electric", "id": "porsche-cayenne-electric"}, {"brand": "Porsche", "model": "Cayenne Coupe Electric", "id": "porsche-cayenne-coupe-electric"}, {"brand": "Mercedes-Benz", "model": "CLA Electric", "id": "mercedes-benz-cla-electric"}, {"brand": "Jetour", "model": "T2 i-DM", "id": "jetour-t2"}, {"brand": "JAC", "model": "T9 PHEV", "id": "jac-t9"}, {"brand": "JAC", "model": "T9 EV", "id": "jac-t9-ev"}] \ No newline at end of file diff --git a/frontend/app/calculators/page.tsx b/frontend/app/calculators/page.tsx index d05c990..1b6a042 100644 --- a/frontend/app/calculators/page.tsx +++ b/frontend/app/calculators/page.tsx @@ -313,8 +313,10 @@ export default function CalculatorsPage() { {afford && (
+ {/* Scoped to the drivetrain chosen above: the count and the + cars below are that drivetrain's, so the label names it. */} {afford.examples.length > 0 && ( diff --git a/frontend/app/chat/[token]/page.tsx b/frontend/app/chat/[token]/page.tsx index 00665e6..1c2a95e 100644 --- a/frontend/app/chat/[token]/page.tsx +++ b/frontend/app/chat/[token]/page.tsx @@ -8,7 +8,8 @@ import Link from "next/link"; import { BatteryWarning, Send, Sparkles } from "lucide-react"; import { Button } from "@/components/ui"; import { apiService } from "@/lib/api"; -import { useT } from "@/lib/i18n"; +import { ASK_PROMPTS } from "@/lib/ask"; +import { getLang, makeT, useT } from "@/lib/i18n"; type Msg = { role: "user" | "ai"; text: string }; @@ -21,20 +22,50 @@ export default function ChatPage() { const [busy, setBusy] = useState(false); const [error, setError] = useState(""); const bottomRef = useRef(null); + // The question carried in from the results page is sent once. React runs this + // effect twice in development; the ref keeps that from asking twice. + const asked = useRef(false); + // Read once: the first run strips ?q= from the address bar, so a second run + // reading the URL again would find nothing and clear the question. + const carried = useRef(null); - // honor ?ask=battery deep link - const askDefault = useRef( - typeof window !== "undefined" && new URLSearchParams(window.location.search).get("ask") === "battery", - ); + // The network half of sending: the user's message is already on screen. + const ask = async (q: string) => { + setError(""); + setBusy(true); + try { + const r = await apiService.postChat(token, q, getLang()); + setMessages((m) => [...m, { role: "ai", text: r.reply || "" }]); + } catch { + setError(makeT(getLang())("ch.offline")); + } finally { + setBusy(false); + } + }; useEffect(() => { - const greeting = - "Hi! I'm your AI analyst. Ask me anything about your results — pricing, charging, battery degradation, or the roadmap. (Malay works too.)"; - const starter: Msg[] = [{ role: "ai", text: greeting }]; - if (askDefault.current) { - starter.push({ role: "user", text: "How much does battery degradation matter for my EV?" }); + // ?q= from a results-page chip; ?ask=battery is the older link + // from the battery card. The battery link used to put the question on + // screen without ever sending it, so it sat there unanswered. + // useT() still reads "en" on the first render, before useLang's effect + // has looked at the stored language, so read it directly here. + const tNow = makeT(getLang()); + if (carried.current === null) { + const params = new URLSearchParams(window.location.search); + carried.current = ( + params.get("q") || (params.get("ask") === "battery" ? tNow("ask.battery") : "") + ).trim(); } - setMessages(starter); + const q = carried.current; + const greeting: Msg = { role: "ai", text: tNow("ch.hello") }; + setMessages(q ? [greeting, { role: "user", text: q }] : [greeting]); + if (q && !asked.current) { + asked.current = true; + // Drop the query so a reload does not ask again. + window.history.replaceState(null, "", window.location.pathname); + ask(q); + } + // eslint-disable-next-line react-hooks/exhaustive-deps }, []); useEffect(() => { @@ -45,18 +76,8 @@ export default function ChatPage() { const q = (text ?? input).trim(); if (!q || busy) return; setInput(""); - setError(""); setMessages((m) => [...m, { role: "user", text: q }]); - setBusy(true); - try { - const r = await apiService.postChat(token, q, "en"); - setMessages((m) => [...m, { role: "ai", text: r.reply || "" }]); - } catch (e: any) { - setError("The analyst is offline right now — try again in a moment."); - setBusy(false); - } finally { - setBusy(false); - } + await ask(q); }; return ( @@ -93,7 +114,7 @@ export default function ChatPage() { {busy && (
- Thinking… + {t("ch.thinking")}
)} {error &&

{error}

} @@ -102,7 +123,7 @@ export default function ChatPage() { {/* quick chips */}
- {(["ch.q1", "ch.q2", "ch.q3", "ch.q4"] as const).map((k) => { + {ASK_PROMPTS.map((k) => { const chip = t(k); return ( + {/* Ready-made follow-ups: one tap opens the chat with the question + already sent, so a buyer who does not know what to ask still + gets somewhere. lib/ask.ts holds the list. */} +
+

{t("ask.label")}

+
+ {ASK_PROMPTS.slice(0, 4).map((k) => { + const q = t(k); + return ( + + {q} + + ); + })} +
+
@@ -460,39 +476,7 @@ export default function ResultsPage() { {/* ── Solar Bonus Banner ────────────────────────────────────────── */} {data.solar && ( -
-
-
- - - -
-

{t("r.solar")}

-

- {(() => { - // Split the translated template on its placeholders so each - // figure keeps its emphasis wherever the language puts it. - const values: Record = { - "{capex}": `RM${data.solar.capex_rm.toLocaleString()}`, - "{savings}": `~RM${data.solar.savings_rm_per_year.toLocaleString()}${t("r.perYear")}`, - "{payback}": t("r.solarPayback", { n: data.solar.payback_years }), - }; - return t("r.solarBody") - .split(/(\{capex\}|\{savings\}|\{payback\})/) - .map((part, i) => - values[part] ? ( - - {values[part]} - - ) : ( - part - ), - ); - })()} -

-
-
-
+ )} diff --git a/frontend/components/CostBreakdown.tsx b/frontend/components/CostBreakdown.tsx index 1bee66b..6d8ad2b 100644 --- a/frontend/components/CostBreakdown.tsx +++ b/frontend/components/CostBreakdown.tsx @@ -56,6 +56,8 @@ function Bar({ lines }: { lines: CostLine[] }) { function Car({ car }: { car: CarCosts }) { const [open, setOpen] = useState(false); const energy = car.lines.find((l) => l.key === "energy"); + const servicing = car.lines.find((l) => l.key === "maintenance"); + const published = car.maintenance_basis === "measured"; return (
@@ -74,6 +76,24 @@ function Car({ car }: { car: CarCosts }) {
+ {/* Servicing stays visible without opening the breakdown: it is the line + buyers ask about, and the one most often guessed. Published figures + name their source; the rest say they are an estimate. */} + {servicing && ( +

+ Servicing over {car.years} years{" "} + {rm(servicing.amount_rm)} + {published ? ( + + {" "} + · the brand's published schedule + + ) : ( + · estimated from the car's type and price + )} +

+ )} +
- {ranks[scenario]?.length > 0 && ( -
-

- Your shortlist {scenario === "market" ? "without the subsidy" : "today"} -

-
    - {ranks[scenario].slice(0, 3).map((r, i) => { - const other = ranks[scenario === "market" ? "subsidised" : "market"] ?? []; - const moved = other[i]?.slug !== r.slug; - return ( -
  1. - {i + 1} - - {r.model} - - - {r.type} - -
  2. - ); - })} -
-
+ {curve && names && ( + )} + {ranks.subsidised?.length && ranks.market?.length ? ( + <> +

{shiftSummary(ranks.subsidised, ranks.market)}

+ + + ) : null} + {scenario === "market" && (

diff --git a/frontend/components/RangeField.tsx b/frontend/components/RangeField.tsx index 24c869c..fe3413a 100644 --- a/frontend/components/RangeField.tsx +++ b/frontend/components/RangeField.tsx @@ -41,6 +41,7 @@ export function RangeField({ onChange, caption, zeroLabel, + snap, }: { id: string; label: string; @@ -52,6 +53,9 @@ export function RangeField({ onChange: (v: number) => void; caption: (v: number) => string; zeroLabel?: string; + /** Rounds a value from the slider only. Typed values pass through as typed: + * snapping them would rewrite the box mid-keystroke. */ + snap?: (v: number) => number; }) { /* The box hugs its value instead of sitting in a fixed 128px well. The face is mono with tabular-nums, so every digit is exactly 1ch and this is exact @@ -87,7 +91,10 @@ export function RangeField({ aria-label={label} // a value typed past the band pins the thumb at that end value={Math.min(max, Math.max(min, value))} - onChange={(e) => onChange(Number(e.target.value))} + onChange={(e) => { + const v = Number(e.target.value); + onChange(snap ? snap(v) : v); + }} className="mt-3" />

diff --git a/frontend/components/RulesAndSources.tsx b/frontend/components/RulesAndSources.tsx new file mode 100644 index 0000000..f321d5a --- /dev/null +++ b/frontend/components/RulesAndSources.tsx @@ -0,0 +1,121 @@ +"use client"; + +import { ArrowUpRight } from "lucide-react"; +import { Reveal, ScrubStagger } from "@/components/motion"; +import { useT } from "@/lib/i18n"; + +/* Malaysia's EV rules at a glance, and the official sources behind them. + + These sat in the site-wide footer, so every page ended on four regulatory + figures and a list of government links. They are reference material for the + method, so they now live on the Method & sources page (app/method), and the + footer keeps only navigation and disclaimers. + + The markup is the footer's, light-only. DESIGN.md §1: hairline rules, not card + soup. Amber is spent once, on the only figure with a deadline. The figures + deliberately do NOT use ScrubCount: a scrub-bound counter rests wherever the + scroll left it, and a road-tax figure caught mid-count reads as a wrong number. + Entrance motion is opacity and transform only, which cannot render a false + value, and every figure is in the DOM before JS runs. */ + +const FIGURES = [ + ["ft.s1v", "ft.s1l"], + ["ft.s2v", "ft.s2l"], + ["ft.s3v", "ft.s3l"], + ["ft.s4v", "ft.s4l"], +] as const; + +const RULES = [ + ["ft.reg1t", "ft.p1", "ft.reg1"], + ["ft.reg2t", "ft.p2", "ft.reg2"], + ["ft.reg3t", "ft.p3", "ft.reg3"], + ["ft.reg4t", "ft.p4", "ft.reg4"], +] as const; + +const OFFICIAL = [ + ["JPJ", "https://www.jpj.gov.my/", "ft.srcJpj"], + ["myTNB", "https://www.mytnb.com.my/tariff/index.html", "ft.srcTnb"], + ["MITI", "https://www.miti.gov.my/", "ft.srcMiti"], + [ + "Suruhanjaya Tenaga", + "https://www.st.gov.my/resources/guidelines-electric-vehicle-charging-system-evcs", + "ft.srcSt", + ], + ["PLANMalaysia MEVnet", "https://www.planmalaysia.gov.my/mevnet/", "ft.srcPlan"], +] as const; + +export function RulesAtAGlance() { + const t = useT(); + return ( +
+ + {FIGURES.map(([figure, label], i) => ( +
+

+ {t(figure)} +

+

{t(label)}

+
+ ))} +
+ + + {RULES.map(([title, prov, body]) => ( +
+

+ {t(title)} +

+

{t(prov)}

+

{t(body)}

+
+ ))} +
+ +

{t("ft.verified")}

+
+ ); +} + +/** A ruled index. The name column is sized by the longest name via subgrid + * rather than a fixed width behind a breakpoint, so all three columns stay + * aligned at any width. */ +export function OfficialSources() { + const t = useT(); + return ( + + ); +} diff --git a/frontend/components/SolarBanner.tsx b/frontend/components/SolarBanner.tsx new file mode 100644 index 0000000..ce9d99f --- /dev/null +++ b/frontend/components/SolarBanner.tsx @@ -0,0 +1,93 @@ +"use client"; + +import Link from "next/link"; +import { MessageCircle, Sun } from "lucide-react"; +import type { SolarEstimate } from "@/lib/api"; +import { askHref } from "@/lib/ask"; +import { useT, type StrKey } from "@/lib/i18n"; + +/** The solar banner on /results and /recommendation, shown only when the buyer + * is considering solar AND can charge at home. + * + * The figures are backend/app/services/solar.py: a reference household billed + * on TNB's arithmetic under Solar ATAP, with panels alone and with a battery. + * Whether the battery line says "worth it" or "for backup" is decided by its + * computed payback against the battery's own life, never assumed. */ + +// A home battery's warranty is about ten years; past fifteen it is not paying +// for itself on the bill within any life it will have. +const BATTERY_PAYS_YEARS = 15; + +const rm = (n: number) => `RM${Math.round(n).toLocaleString("en-MY")}`; + +/** Splits a translated template on its {placeholders} so each figure stays + * bold wherever the language puts it. */ +function Filled({ template, values }: { template: string; values: Record }) { + return ( + <> + {template.split(/(\{[a-z]+\})/).map((part, i) => + part in values ? ( + + {values[part]} + + ) : ( + part + ), + )} + + ); +} + +export function SolarBanner({ solar, token }: { solar: SolarEstimate; token: string }) { + const t = useT(); + if (!solar?.payback_years) return null; + + const b = solar.battery; + const batteryPays = b?.payback_years != null && b.payback_years <= BATTERY_PAYS_YEARS; + const batteryKey: StrKey = batteryPays ? "r.solarBatteryYes" : "r.solarBatteryNo"; + const perYear = t("r.perYear"); + + return ( +
+
+
+ + + +
+

{t("r.solar")}

+

+ +

+ {b && ( +

+ +

+ )} + + {t("r.solarAsk")} + +
+
+
+ ); +} diff --git a/frontend/components/SupportingInitiatives.tsx b/frontend/components/SupportingInitiatives.tsx index 903a886..141ddb9 100644 --- a/frontend/components/SupportingInitiatives.tsx +++ b/frontend/components/SupportingInitiatives.tsx @@ -16,7 +16,9 @@ const INITIATIVES: Initiative[] = [ }, { key: "nem", - href: "https://www.seda.gov.my/reportal/nem/", + // NEM 3.0 closed to new applications on 30 Jun 2025; Solar ATAP replaced it + // on 1 Jan 2026. The key stays "nem" so the i18n keys did not churn. + href: "https://www.mytnb.com.my/renewable-energy/solar-accelerated-transition-action-programme", logo: "/initiatives/seda_malaysia_logo.png", alt: "SEDA Malaysia logo", }, diff --git a/frontend/components/animated-hero.tsx b/frontend/components/animated-hero.tsx index cac9a6e..91526d4 100644 --- a/frontend/components/animated-hero.tsx +++ b/frontend/components/animated-hero.tsx @@ -36,7 +36,8 @@ export function Hero() { }, [annualKm]); const annualSavingsRm = annualPetrolRm - annualEvRm; - const tenYearSavingsRm = annualSavingsRm * 10; + // Five years: the ownership horizon the whole engine uses. + const fiveYearSavingsRm = annualSavingsRm * 5; const annualCo2Kg = Math.round((annualKm * 7.2 / 100) * 2.31 - (annualKm * 15.5 / 100) * 0.58); return ( @@ -154,7 +155,7 @@ export function Hero() {
- {t("calc.tenYearSave")}: RM + {t("calc.fiveYearSave")}: RM - kg CO₂/yr
diff --git a/frontend/components/charts/SubsidyCharts.tsx b/frontend/components/charts/SubsidyCharts.tsx new file mode 100644 index 0000000..9f2643e --- /dev/null +++ b/frontend/components/charts/SubsidyCharts.tsx @@ -0,0 +1,392 @@ +"use client"; + +import { useEffect, useRef, useState, type KeyboardEvent, type PointerEvent } from "react"; +import type { CostCurvePoint, FuelScenario } from "@/lib/api"; + +/* The fuel-subsidy panel's two figures (components/FuelScenario.tsx). + + CostByMileage: five-year cost of the best EV and the best hybrid at every + annual mileage, with the hybrid drawn twice, at RM1.99 (solid) and at the + unsubsidised price (dashed). The subsidy is the gap between the two hybrid + lines; the BUDI95 quota is the bend in the solid one; "You" marks the buyer. + + RankShift: a slope chart of the shortlist, today's rank on the left and the + no-subsidy rank on the right. It replaced a top-three list that stayed + identical whenever the top three were all EVs, which read as a broken toggle. + + Colours are validated (dataviz validate_palette.js, light, on the panel's + #fbf8ec, all pairs): worst CVD ΔE 9.4. They follow the drivetrain, never the + rank. Text stays in ink tokens; colour only marks lines and dots. */ + +export const SERIES = { + ev: "#0a8f5e", + hybrid: "#c45a0c", + phev: "#5a4fe0", +} as const; + +const SURFACE = "#fbf8ec"; +const GRID = "#e6e0cc"; +const INK = "#15221c"; +const MUTED = "#5c6b62"; + +const rmK = (n: number) => `RM${Math.round(n / 1000)}k`; +const rm = (n: number) => `RM${Math.round(n).toLocaleString("en-MY")}`; +const kmK = (n: number) => (n === 0 ? "0" : `${Math.round(n / 1000)}k`); + +/** Width of an element, tracked, so the SVG draws at its real pixel size and + * type stays the same size on a phone and a desktop. */ +function useWidth() { + const ref = useRef(null); + const [width, setWidth] = useState(0); + useEffect(() => { + const el = ref.current; + if (!el) return; + const ro = new ResizeObserver(([e]) => setWidth(Math.round(e.contentRect.width))); + ro.observe(el); + setWidth(Math.round(el.getBoundingClientRect().width)); + return () => ro.disconnect(); + }, []); + return [ref, width] as const; +} + +function niceStep(span: number) { + const raw = span / 4; + const pow = 10 ** Math.floor(Math.log10(raw)); + const unit = [1, 2, 2.5, 5, 10].find((m) => m * pow >= raw) ?? 10; + return unit * pow; +} + +type Series = { key: "ev_rm" | "hybrid_subsidised_rm" | "hybrid_market_rm"; label: string; name: string; color: string; dashed?: boolean }; + +export function CostByMileage({ + curve, + names, + yourKm, + scenario, + breakevenKm, +}: { + curve: CostCurvePoint[]; + names: { ev: string; hybrid: string }; + yourKm: number; + scenario: FuelScenario; + breakevenKm: number | null; +}) { + const [wrap, width] = useWidth(); + const [idx, setIdx] = useState(null); + + const series: Series[] = [ + { key: "ev_rm", label: "Electric", name: names.ev, color: SERIES.ev }, + { key: "hybrid_subsidised_rm", label: "Hybrid at RM1.99", name: names.hybrid, color: SERIES.hybrid }, + { key: "hybrid_market_rm", label: "Hybrid, no subsidy", name: names.hybrid, color: SERIES.hybrid, dashed: true }, + ]; + const active = scenario === "market" ? "hybrid_market_rm" : "hybrid_subsidised_rm"; + + const H = 220; + const m = { l: 48, r: 12, t: 16, b: 30 }; + const W = Math.max(width, 260); + const pw = W - m.l - m.r; + const ph = H - m.t - m.b; + + const maxKm = curve[curve.length - 1]?.km ?? 1; + const values = curve.flatMap((p) => series.map((s) => p[s.key])); + const step = niceStep(Math.max(...values) - Math.min(...values) || 1); + const lo = Math.floor(Math.min(...values) / step) * step; + const hi = Math.ceil(Math.max(...values) / step) * step; + const x = (km: number) => m.l + (km / maxKm) * pw; + const y = (v: number) => m.t + ph - ((v - lo) / (hi - lo || 1)) * ph; + const yTicks: number[] = []; + for (let v = lo; v <= hi + 1; v += step) yTicks.push(v); + const xStep = niceStep(maxKm); + const xTicks: number[] = []; + for (let k = 0; k <= maxKm + 1; k += xStep) xTicks.push(k); + + const path = (key: Series["key"]) => + curve.map((p, i) => `${i ? "L" : "M"}${x(p.km).toFixed(1)},${y(p[key]).toFixed(1)}`).join(""); + + const nearest = (px: number) => { + const km = ((px - m.l) / pw) * maxKm; + let best = 0; + curve.forEach((p, i) => { + if (Math.abs(p.km - km) < Math.abs(curve[best].km - km)) best = i; + }); + return best; + }; + const onMove = (e: PointerEvent) => { + const r = e.currentTarget.getBoundingClientRect(); + setIdx(nearest(e.clientX - r.left + m.l)); + }; + const onKey = (e: KeyboardEvent) => { + if (e.key !== "ArrowLeft" && e.key !== "ArrowRight") return; + e.preventDefault(); + const start = idx ?? nearest(x(yourKm)); + setIdx(Math.min(curve.length - 1, Math.max(0, start + (e.key === "ArrowRight" ? 1 : -1)))); + }; + + const hover = idx != null ? curve[idx] : null; + const yourInRange = yourKm > 0 && yourKm <= maxKm; + const crossing = breakevenKm != null && breakevenKm <= maxKm ? breakevenKm : null; + // y of the active hybrid line at the crossing, by interpolation + const crossingY = (() => { + if (crossing == null) return null; + const i = curve.findIndex((p) => p.km >= crossing); + if (i <= 0) return null; + const a = curve[i - 1], b = curve[i]; + const t = (crossing - a.km) / (b.km - a.km || 1); + return y(a[active] + t * (b[active] - a[active])); + })(); + + return ( +
+
+ Five-year cost at every mileage +
+ {/* legend: line keys, the active hybrid line first in weight */} +
    + {series.map((s) => ( +
  • + + {s.label} + · {s.name} +
  • + ))} +
+ +
setIdx(null)} + > + {width > 0 && ( + + )} + + {hover && ( +
W / 2 ? { right: W - x(hover.km) + 10 } : { left: x(hover.km) + 10 }} + > +

{Math.round(hover.km).toLocaleString("en-MY")} km a year

+ {series.map((s) => ( +

+ + {rm(hover[s.key])} + {s.label} +

+ ))} +
+ )} +
+ +

+ The gap between the two orange lines is what the subsidy is worth to you over five years + {crossing != null ? "; the dot is where the cheaper car changes" : ""}. +

+ +
+ Show the numbers + + + + + {series.map((s) => ( + + ))} + + + + {curve.filter((_, i) => i % 2 === 0).map((p) => ( + + + {series.map((s) => ( + + ))} + + ))} + +
km a year{s.label}
{Math.round(p.km).toLocaleString("en-MY")}{rm(p[s.key])}
+
+
+ ); +} + +export type RankedCar = { slug: string; brand: string; model: string; type: string; rank: number }; + +const shortName = (c: RankedCar) => { + const full = `${c.brand} ${c.model}`; + return full.length > 17 ? c.model : full; +}; + +const TYPE_LABEL: Record = { ev: "Electric", hybrid: "Hybrid", phev: "Plug-in hybrid" }; + +export function RankShift({ + today, + ended, + scenario, +}: { + today: RankedCar[]; + ended: RankedCar[]; + scenario: FuelScenario; +}) { + const [wrap, width] = useWidth(); + const [focus, setFocus] = useState(null); + + const endedRank = new Map(ended.map((c) => [c.slug, c.rank])); + const todayRank = new Map(today.map((c) => [c.slug, c.rank])); + // Cars in either top five, plus today's best hybrid wherever it lands: when + // the top five are all EVs, the hybrid is the car the subsidy moves. + const pick = new Map(); + for (const c of [...today.slice(0, 5), ...ended.slice(0, 5)]) pick.set(c.slug, c); + const bestHybrid = today.find((c) => c.type !== "ev"); + if (bestHybrid) pick.set(bestHybrid.slug, bestHybrid); + const rows = [...pick.values()] + .map((c) => ({ ...c, a: todayRank.get(c.slug) ?? 99, b: endedRank.get(c.slug) ?? 99 })) + .sort((p, q) => p.a - q.a) + .slice(0, 9); + const leftOrder = rows.map((r) => r.slug); + const rightOrder = [...rows].sort((p, q) => p.b - q.b).map((r) => r.slug); + + const rowH = 26; + const top = 30; + const H = top + rows.length * rowH + 4; + const W = Math.max(width, 280); + const gap = Math.min(110, Math.max(56, W * 0.22)); + const lx = (W - gap) / 2; // left line end + const rx = (W + gap) / 2; // right line end + const yAt = (i: number) => top + i * rowH + rowH / 2; + const types = [...new Set(rows.map((r) => r.type))]; + + return ( +
+
Where your cars rank
+
    + {types.map((t) => ( +
  • + + {TYPE_LABEL[t] ?? t} +
  • + ))} +
+
+ {width > 0 && ( + + + RON95 at RM1.99 + + + If the subsidy ends + + {rows.map((r) => { + const y1 = yAt(leftOrder.indexOf(r.slug)); + const y2 = yAt(rightOrder.indexOf(r.slug)); + const color = SERIES[r.type as keyof typeof SERIES] ?? MUTED; + const dim = focus != null && focus !== r.slug; + const moved = r.a !== r.b; + const label = `${shortName(r)}: number ${r.a} today, number ${r.b} if the subsidy ends`; + return ( + setFocus(r.slug)} + onPointerLeave={() => setFocus(null)} + onFocus={() => setFocus(r.slug)} + onBlur={() => setFocus(null)} + style={{ opacity: dim ? 0.25 : 1, outline: "none" }} + className="motion-safe:transition-opacity motion-safe:duration-200" + > + {/* generous hit area: the whole row on both sides */} + + + + + + #{r.a} + {shortName(r)} + + + #{r.b} + {shortName(r)} + + + ); + })} + + )} +
+
+ ); +} diff --git a/frontend/components/ui.tsx b/frontend/components/ui.tsx index c3b866d..345bc20 100644 --- a/frontend/components/ui.tsx +++ b/frontend/components/ui.tsx @@ -1,8 +1,7 @@ import * as React from "react"; import Link from "next/link"; import { setLang, useLang, useT, type Lang } from "@/lib/i18n"; -import { Sparkles, Globe, X, ArrowUpRight } from "lucide-react"; -import { Reveal, ScrubStagger } from "@/components/motion"; +import { Sparkles, Globe, X } from "lucide-react"; /* -------------------------------------------------------------------------- VoltPilot Malaysia UI Primitives @@ -295,7 +294,7 @@ export function Navbar({ dark = false }: { dark?: boolean }) { {t("nav.calcs")} {t("nav.method")} @@ -338,151 +337,10 @@ export function Footer({ dark = false }: { dark?: boolean }) { >
- {/* Regulatory detail. DESIGN.md §1: hairline rules, not card soup — the - figures are divided by rules, not boxed. Amber is the signal colour and is - spent once, on the only figure that is a closing deadline. Motion is - scrub-linked per §3, and every figure is in the DOM before JS runs. - The figures deliberately do NOT use ScrubCount: a scrub-bound counter rests - wherever the scroll left it, and a road-tax figure caught mid-count reads as - a wrong number rather than an unfinished animation. Entrance motion here is - opacity and transform only, which cannot render a false value. */} + {/* The regulatory figures and official sources that used to open the + footer now live on the Method & sources page (components/RulesAndSources). */}
-

{t("ft.glance")}

-

- {t("ft.regIntro")} -

- - - {( - [ - ["ft.s1v", "ft.s1l"], - ["ft.s2v", "ft.s2l"], - ["ft.s3v", "ft.s3l"], - ["ft.s4v", "ft.s4l"], - ] as const - ).map(([figure, label], i) => ( -
-

- {t(figure)} -

-

- {t(label)} -

-
- ))} -
- - - {( - [ - ["ft.reg1t", "ft.p1", "ft.reg1"], - ["ft.reg2t", "ft.p2", "ft.reg2"], - ["ft.reg3t", "ft.p3", "ft.reg3"], - ["ft.reg4t", "ft.p4", "ft.reg4"], - ] as const - ).map(([title, prov, body]) => ( -
-

- {t(title)} -

-

- {t(prov)} -

-

- {t(body)} -

-
- ))} -
- -

{t("ft.sources")}

- {/* A ruled index. The name column is sized by the longest name via subgrid - rather than a fixed width behind a breakpoint — below `sm` that fixed - column switched off and every description started at a different x. - Subgrid keeps all three columns aligned at any width. */} -
-
-
@@ -517,7 +375,7 @@ export function Footer({ dark = false }: { dark?: boolean }) {
  • - + {t("ft.how")}
  • @@ -557,7 +415,6 @@ export function Footer({ dark = false }: { dark?: boolean }) { }`} >
    -

    {t("ft.verified")}

    {t("ft.disc")}

    {t("ft.privacy")}

    diff --git a/frontend/lib/api.ts b/frontend/lib/api.ts index 0bb2553..da64fad 100644 --- a/frontend/lib/api.ts +++ b/frontend/lib/api.ts @@ -94,6 +94,10 @@ export type CarCosts = { resale_value_rm: number; retained_pct: number; retained_basis: "measured" | "type_curve" | "fallback"; + /** "measured" = the distributor's published schedule; "estimated" = fitted + * from drivetrain and price. maintenance_note names the source when measured. */ + maintenance_basis?: "measured" | "estimated"; + maintenance_note?: string | null; lines: CostLine[]; }; @@ -129,10 +133,28 @@ export type Breakeven = { your_km_per_year: number; breakeven_km_per_year: number | null; verdict: "crossover" | "ev_always" | "hybrid_always"; + /** On a crossover, which car is cheaper below the break-even mileage. */ + cheaper_below?: "ev" | "hybrid"; you_are_past_it?: boolean; note?: string; }; +/** One mileage on the fuel panel's chart: five-year totals in RM. */ +export type CostCurvePoint = { + km: number; + ev_rm: number; + hybrid_subsidised_rm: number; + hybrid_market_rm: number; +}; + +/** BUDI95 as it applies to this buyer's best hybrid, from /results/{token}/breakeven. */ +export type FuelFacts = { + ron95_rm_per_l: number; + ron95_market_rm_per_l: number; + quota_l_month: number | null; + hybrid_litres_month: number; +}; + export type ChargerMix = { radius_km: number; total: number; @@ -430,7 +452,14 @@ export const apiService = { /** Mileage at which the shortlist's best EV overtakes its best hybrid, under * both fuel scenarios. Often there is no crossing, which is the point. */ getBreakeven: (token: string) => - api<{ available: boolean; reason?: string; scenarios?: Record }>( + api<{ + available: boolean; + reason?: string; + scenarios?: Record; + fuel?: FuelFacts; + curve?: CostCurvePoint[]; + names?: { ev: string; hybrid: string }; + }>( `/results/${token}/breakeven`, ), /** Re-rank under a different fuel price. Does not persist: the stored result @@ -476,7 +505,7 @@ export const apiService = { method: "POST", body: JSON.stringify({ transcript, lang }), }), - getSolar: () => api<{ solar: any }>("/config/solar"), + getSolar: () => api<{ solar: SolarEstimate }>("/config/solar"), getSponsor: () => api<{ sponsor: any }>("/config/sponsor"), /** Whether voice is configured; mints nothing. 501 when it is not. */ checkLive: () => @@ -492,4 +521,22 @@ export const apiService = { if (!r.ok) throw new ApiError(r.status, await r.text().catch(() => ""), kindForStatus(r.status)); return r.json() as Promise<{ token: string; model: string; api_version: string }>; }), -}; \ No newline at end of file +}; + +/** backend/app/services/solar.py solar_estimate(): one reference household + * under Solar ATAP, with panels alone and with a battery added. */ +export type SolarEstimate = { + scheme: string; + system_kw_peak: number; + capex_rm: number; + savings_rm_per_year: number; + payback_years: number | null; + credit_years: number; + battery: { + kwh: number; + capex_rm: number; + extra_savings_rm_per_year: number; + payback_years: number | null; + combined_payback_years: number | null; + }; +}; diff --git a/frontend/lib/ask.ts b/frontend/lib/ask.ts new file mode 100644 index 0000000..dd77342 --- /dev/null +++ b/frontend/lib/ask.ts @@ -0,0 +1,18 @@ +import type { StrKey } from "./i18n"; + +/** Ready-made questions for the AI analyst. The results page shows the first + * four under "Ask AI"; the chat shows them all as chips. A chip on the results + * page links to the chat with the question in `?q=`, and the chat sends it as + * soon as it loads, so one tap gets an answer. */ +export const ASK_PROMPTS: readonly StrKey[] = [ + "ask.family", + "ask.cheaper", + "ask.service", + "ask.solar", + "ask.subsidy", + "ask.charge", + "ask.top2", +]; + +export const askHref = (token: string, question: string) => + `/chat/${token}?q=${encodeURIComponent(question)}`; diff --git a/frontend/lib/i18n.ts b/frontend/lib/i18n.ts index cbb1e9e..9419f6f 100644 --- a/frontend/lib/i18n.ts +++ b/frontend/lib/i18n.ts @@ -51,7 +51,7 @@ const S = { "nav.cta": ["Get your ranking", "Dapatkan kedudukan anda"], "nav.ctaShort": ["Start", "Mula"], "nav.voice": ["Voice Advisor", "Penasihat Suara"], - "nav.method": ["Methodology", "Kaedah"], + "nav.method": ["Method & sources", "Kaedah & sumber"], "nav.cars": ["Catalog", "Katalog"], "nav.calc": ["Live Commute Savings Calculator", "Kalkulator Ulang-Alik"], "cf.postcodeUnknown": ["Postcode not recognised", "Poskod tidak dikenali"], @@ -80,22 +80,22 @@ const S = { "hero.t1": ["EV or Hybrid?", "EV atau Hibrid?"], "hero.t2": ["Make the decision with numbers.", "Biar angka yang menentukan."], "hero.sub": [ - "Tell us how you drive. Our 5 decision engines rank 170 Malaysian models for your budget, routes, and electricity tariffs.", - "Beritahu gaya pemanduan anda. 5 enjin keputusan kami menyusun 170 model kereta Malaysia mengikut bajet, laluan dan tarif elektrik anda.", + "Tell us how you drive. Our 5 decision engines rank 171 Malaysian models for your budget, routes, and electricity tariffs.", + "Beritahu gaya pemanduan anda. 5 enjin keputusan kami menyusun 171 model kereta Malaysia mengikut bajet, laluan dan tarif elektrik anda.", ], "hero.cta": ["Start 2-min diagnostic", "Mula diagnostik 2 minit"], "hero.voiceCta": ["Talk to AI Voice Advisor", "Bercakap dengan Penasihat AI"], - "hero.trust": ["100% Free · No registration · 170 Malaysian models tested", "100% Percuma · Tanpa pendaftaran · 170 model Malaysia diuji"], + "hero.trust": ["100% Free · No registration · 171 Malaysian models tested", "100% Percuma · Tanpa pendaftaran · 171 model Malaysia diuji"], "calc.title": ["Live Commute Savings Calculator", "Kalkulator Penjimatan Ulang-Alik Langsung"], "calc.daily": ["Daily Commute", "Ulang-Alik Harian"], "calc.petrol": ["Petrol (RON95)", "Petrol (RON95)"], "calc.ev": ["TNB EV Off-Peak", "TNB EV Luar Puncak"], "calc.annualSave": ["Estimated Annual Savings", "Anggaran Penjimatan Tahunan"], - "calc.tenYearSave": ["10-Year Fuel Savings", "Penjimatan 10 Tahun"], + "calc.fiveYearSave": ["5-Year Fuel Savings", "Penjimatan 5 Tahun"], "ts.rm.sub": ["Complete OTR prices, JPJ road tax & TNB tariffs", "Harga OTR lengkap, cukai jalan JPJ & tarif TNB"], // scroll marquee band (DESIGN.md §3) — factual claims only, no brand noise - "mq.a": ["170 Malaysian trims", "170 varian Malaysia"], + "mq.a": ["171 Malaysian trims", "171 varian Malaysia"], "mq.b": ["5 decision engines", "5 enjin keputusan"], "mq.c": ["TOPSIS ranked", "Disusun secara TOPSIS"], "mq.d": ["Free, no sign-up", "Percuma, tanpa daftar"], @@ -116,12 +116,12 @@ const S = { ], "hw.s3t": ["Personalized TOPSIS Verdict", "Keputusan TOPSIS Diperibadikan"], "hw.s3b": [ - "Ranked leaderboard, 10-year cashflow roadmap, battery degradation simulator, and Gemini AI briefing.", - "Papan kedudukan, peta jalan aliran tunai 10 tahun, simulator bateri, dan taklimat AI Gemini.", + "Ranked leaderboard, 5-year cashflow roadmap, battery degradation simulator, and Gemini AI briefing.", + "Papan kedudukan, peta jalan aliran tunai 5 tahun, simulator bateri, dan taklimat AI Gemini.", ], - "eng.e1t": ["10-Year TCO Engine", "Enjin TCO 10 Tahun"], - "eng.e1d": ["OTR price, 10-year depreciation, TNB Time-of-Use tariffs vs RON95 subsidy, service schedules, and comprehensive insurance.", "Harga OTR, susut nilai 10 tahun, tarif TNB vs subsidi RON95, servis berjadual, dan insurans komprehensif."], + "eng.e1t": ["5-Year TCO Engine", "Enjin TCO 5 Tahun"], + "eng.e1d": ["OTR price, 5-year depreciation from real used-car listings, TNB Time-of-Use tariffs vs the RON95 subsidy and its monthly quota, published service schedules, and comprehensive insurance with no-claim discount.", "Harga OTR, susut nilai 5 tahun daripada iklan kereta terpakai sebenar, tarif Masa Penggunaan TNB berbanding subsidi RON95 dan kuota bulanannya, jadual servis yang diterbitkan, dan insurans komprehensif dengan diskaun tanpa tuntutan."], "eng.e2t": ["Range & Behavior Engine", "Enjin Jarak & Tingkah Laku"], "eng.e2d": ["Real-world WLTP derating for tropical heat, highway speeds, monsoon rain, and daily commute buffer requirements.", "Penurunan WLTP untuk cuaca panas tropika, kelajuan lebuh raya, hujan lebat, dan penimbal harian."], "eng.e3t": ["JPJ Road Tax Engine", "Enjin Cukai Jalan JPJ"], @@ -153,29 +153,27 @@ const S = { "eng.f3": ["JPJ Lampiran B Formula", "Formula JPJ Lampiran B"], "eng.f4": ["PLUS Expressway Corridors", "Koridor Lebuhraya PLUS"], "eng.f5": ["Used Market Telemetry", "Telemetri Pasaran Terpakai"], - "calc.ctaModels": ["Calculate with 170 exact models", "Kira dengan 170 model tepat"], + "calc.ctaModels": ["Calculate with 171 exact models", "Kira dengan 171 model tepat"], "calc.aria": ["Daily commute distance", "Jarak perjalanan harian"], "ui.closeDialog": ["Close dialog", "Tutup dialog"], - /* ---- /methodology — sourced from VOLT_PILOT_TECHNICAL_SPECIFICATION. + /* ---- /method (Method & sources) — sourced from VOLT_PILOT_TECHNICAL_SPECIFICATION. Equations, variable names and citations stay untranslated: they are universal notation, and nobody localises a DOI or CLCC_RM_per_km. ---- */ "me.c4": ["Emissions", "Pelepasan"], "me.c4d": ["Well-to-wheel CO₂, using your grid region's carbon intensity", "CO₂ well-to-wheel, mengikut keamatan karbon wilayah grid anda"], - "me.c5": ["Purchase price", "Harga belian"], - "me.c5d": ["What you pay on the road, before running costs", "Apa yang anda bayar atas jalan, sebelum kos operasi"], - "me.c6": ["Running cost", "Kos operasi"], - "me.c6d": ["Yearly electricity or fuel for how you actually drive", "Elektrik atau bahan api tahunan mengikut cara anda memandu"], + "me.c5": ["Resale value", "Nilai jual semula"], + "me.c5d": ["Share of the price that comes back after five years, fitted from real used listings where the model has them", "Bahagian harga yang kembali selepas lima tahun, dipadankan daripada iklan kereta terpakai sebenar jika model itu ada datanya"], "me.weight": ["base weight", "wajaran asas"], - "me.eyebrow": ["Decision methodology", "Kaedah keputusan"], + "me.eyebrow": ["Method & sources", "Kaedah & sumber"], "me.t1": ["No black box.", "Tiada kotak hitam."], "me.t2": ["Here is the whole method.", "Inilah keseluruhan kaedahnya."], - "me.sub": ["Every recommendation runs this pipeline, in this order, over 170 Malaysian trims. The maths is published so you — or anyone who knows the field — can check it.", "Setiap cadangan melalui saluran ini, mengikut susunan ini, ke atas 170 varian Malaysia. Matematiknya diterbitkan supaya anda — atau sesiapa yang arif dalam bidang ini — boleh menyemaknya."], + "me.sub": ["Every recommendation runs this pipeline, in this order, over 171 Malaysian trims. The maths is published so you — or anyone who knows the field — can check it.", "Setiap cadangan melalui saluran ini, mengikut susunan ini, ke atas 171 varian Malaysia. Matematiknya diterbitkan supaya anda — atau sesiapa yang arif dalam bidang ini — boleh menyemaknya."], - "me.critH": ["Six criteria decide the ranking", "Enam kriteria menentukan kedudukan"], - "me.critSub": ["Your four sliders set the weights; the engine spreads them across these six measures. Weights always sum to 1.", "Empat gelangsar anda menetapkan wajaran; enjin menyebarkannya merentasi enam ukuran ini. Wajaran sentiasa berjumlah 1."], - "me.c1": ["Lifetime cost", "Kos hayat"], - "me.c1d": ["Ten-year ownership cost — financing, insurance, servicing, road tax", "Kos pemilikan sepuluh tahun — pembiayaan, insurans, servis, cukai jalan"], + "me.critH": ["Five criteria decide the ranking", "Lima kriteria menentukan kedudukan"], + "me.critSub": ["Your four sliders set the weights; the engine spreads them across these five measures. The figures shown are the weights with every slider in the middle. Weights always sum to 1.", "Empat gelangsar anda menetapkan wajaran; enjin menyebarkannya merentasi lima ukuran ini. Angka yang ditunjukkan ialah wajaran apabila setiap gelangsar di tengah. Wajaran sentiasa berjumlah 1."], + "me.c1": ["Five-year holding cost", "Kos pegangan lima tahun"], + "me.c1d": ["Five years of loan interest, insurance, servicing, road tax, fuel or charging, and the deposit tied up", "Lima tahun faedah pinjaman, insurans, servis, cukai jalan, bahan api atau pengecasan, dan deposit yang terikat"], "me.c2": ["Range fit", "Kesesuaian jarak"], "me.c2d": ["How the car's range matches your commute and long trips", "Sejauh mana jarak kereta sepadan dengan perjalanan harian dan jauh anda"], "me.c3": ["Charging access", "Akses pengecasan"], @@ -191,15 +189,15 @@ const S = { "me.s3": ["Charging feasibility gate", "Get kebolehlaksanaan pengecasan"], "me.s3d": ["Every car with a plug — battery-electric and plug-in hybrid — is removed when you have neither home nor workplace charging. Public chargers nearby do not change that: they are not somewhere of your own to charge.", "Semua kereta berpalam — elektrik bateri dan hibrid plug-in — dibuang apabila anda tiada pengecasan di rumah mahupun di tempat kerja. Pengecas awam berdekatan tidak mengubahnya: ia bukan tempat mengecas milik anda sendiri."], "me.s4": ["Cost engine", "Enjin kos"], - "me.s4d": ["Ten years of financing interest, insurance, servicing, road tax and the opportunity cost of your deposit. Purchase price and running cost are scored separately so nothing is counted twice.", "Sepuluh tahun faedah pembiayaan, insurans, servis, cukai jalan dan kos peluang deposit anda. Harga belian dan kos operasi dimarkah berasingan supaya tiada pengiraan berganda."], + "me.s4d": ["Five years of loan interest, insurance on the no-claim-discount ladder, servicing, road tax, fuel or charging and the opportunity cost of your deposit. The value the car loses is scored separately, as resale value, so nothing is counted twice.", "Lima tahun faedah pinjaman, insurans mengikut tangga diskaun tanpa tuntutan, servis, cukai jalan, bahan api atau pengecasan dan kos peluang deposit anda. Nilai yang hilang dimarkah berasingan, sebagai nilai jual semula, supaya tiada pengiraan berganda."], "me.s5": ["Energy engine", "Enjin tenaga"], - "me.s5d": ["Yearly electricity or fuel for your actual mileage, priced on TNB tariffs and pump prices, plus well-to-wheel CO₂ at your grid region's carbon intensity.", "Elektrik atau bahan api tahunan untuk perbatuan sebenar anda, dinilai pada tarif TNB dan harga pam, serta CO₂ well-to-wheel pada keamatan karbon wilayah grid anda."], + "me.s5d": ["Yearly electricity or fuel for your actual mileage, priced on TNB tariffs and pump prices, with RON95 at the BUDI95 price only up to its 300-litre monthly quota and at the unsubsidised price beyond it, plus well-to-wheel CO₂ at your grid region's carbon intensity.", "Elektrik atau bahan api tahunan untuk perbatuan sebenar anda, dinilai pada tarif TNB dan harga pam, dengan RON95 pada harga BUDI95 hanya sehingga kuota 300 liter sebulan dan pada harga tanpa subsidi selepas itu, serta CO₂ well-to-wheel pada keamatan karbon wilayah grid anda."], "me.s6": ["Range engine", "Enjin jarak"], "me.s6d": ["Real-world range after tropical heat and highway speeds, checked against your daily distance and the long trips you actually make.", "Jarak sebenar selepas cuaca panas tropika dan kelajuan lebuh raya, disemak dengan jarak harian dan perjalanan jauh yang benar-benar anda lakukan."], "me.s7": ["Infrastructure engine", "Enjin infrastruktur"], "me.s7d": ["Operational public chargers around your postcode and the density and worst gap along your usual long-distance corridor.", "Pengecas awam beroperasi di sekitar poskod anda serta ketumpatan dan jurang terbesar di sepanjang koridor jauh biasa anda."], "me.s8": ["TOPSIS ranking", "Kedudukan TOPSIS"], - "me.s8d": ["Every surviving car is ranked by how close it sits to the best possible combination of all six criteria, and how far from the worst.", "Setiap kereta yang tinggal disusun mengikut kehampirannya dengan gabungan terbaik keenam-enam kriteria, dan jaraknya daripada yang terburuk."], + "me.s8d": ["Every surviving car is ranked by how close it sits to the best possible combination of all five criteria, and how far from the worst.", "Setiap kereta yang tinggal disusun mengikut kehampirannya dengan gabungan terbaik kelima-lima kriteria, dan jaraknya daripada yang terburuk."], "me.gridH": ["Grid emission factors", "Faktor pelepasan grid"], "me.gridSub": [ @@ -208,12 +206,14 @@ const S = { ], "me.topsisH": ["How the final score is computed", "Cara skor akhir dikira"], "me.topsisSub": [ - "Vector normalisation, then your weights, then distance to the best and worst possible outcome.", - "Penormalan vektor, kemudian wajaran anda, kemudian jarak ke hasil terbaik dan terburuk.", + "Each criterion is scaled between fixed bounds L and U, which come from your budget and mileage and never from the other cars, then weighted, then measured against the best and worst possible car.", + "Setiap kriteria diskalakan antara had tetap L dan U, yang datang daripada bajet dan perbatuan anda dan bukan daripada kereta lain, kemudian diberi wajaran, kemudian diukur dengan kereta terbaik dan terburuk yang mungkin.", ], - "me.n1": ["Your four sliders spread across six weights that sum to 1.", "Empat gelangsar anda merentasi enam wajaran yang berjumlah 1."], + "me.n1": ["Your four sliders spread across five weights that sum to 1.", "Empat gelangsar anda merentasi lima wajaran yang berjumlah 1."], "me.n2": ["Higher closeness ranks higher.", "Kehampiran lebih tinggi, kedudukan lebih tinggi."], "me.srcH": ["Sources", "Sumber"], + "me.glanceH": ["Malaysia's EV rules", "Peraturan EV Malaysia"], + "me.researchH": ["Research", "Penyelidikan"], "me.srcSub": [ "The framework is built on published work, not house opinion.", "Rangka kerja ini dibina atas kajian terbitan, bukan pendapat sendiri.", @@ -268,12 +268,12 @@ const S = { "Pelan Malaysia beralih ke tenaga rendah karbon \u2014 tulang belakang penyahkarbonan grid dan pertumbuhan EV.", ], "si.netr.cta": ["Explore NETR", "Terokai NETR"], - "si.nem.t": ["Net Energy Metering (NEM) 3.0", "Pemeteran Tenaga Bersih (NEM) 3.0"], + "si.nem.t": ["Solar ATAP", "Solar ATAP"], "si.nem.d": [ - "Export your rooftop solar surplus to the grid and earn credits \u2014 the basis for the solar payback shown in your report.", - "Eksport lebihan solar bumbung anda ke grid dan dapatkan kredit \u2014 asas kepada bayaran balik solar dalam laporan anda.", + "The rooftop solar programme that replaced NEM in 2026: use your own solar first, and earn bill credit for the surplus \u2014 the basis for the solar payback shown in your report.", + "Program solar bumbung yang menggantikan NEM pada 2026: gunakan tenaga solar sendiri dahulu, dan dapatkan kredit bil untuk lebihannya \u2014 asas kepada bayaran balik solar dalam laporan anda.", ], - "si.nem.cta": ["Learn about NEM", "Ketahui tentang NEM"], + "si.nem.cta": ["Learn about Solar ATAP", "Ketahui tentang Solar ATAP"], "si.tnb.t": ["TNB Electron Malaysia", "TNB Electron Malaysia"], "si.tnb.d": [ "Malaysia\u2019s nationwide public EV charging network, operated by the national utility Tenaga Nasional Berhad.", @@ -321,7 +321,7 @@ const S = { "Seni bina keputusan EV dan Hibrid berasaskan data untuk pemandu Malaysia, menggabungkan harga semasa, tarif nasional, dan telemetri pemanduan sebenar.", ], "ft.product": ["Navigation", "Navigasi"], - "ft.how": ["Methodology", "Kaedah"], + "ft.how": ["Method & sources", "Kaedah & sumber"], "ft.cars": ["Vehicle Catalog", "Katalog Kenderaan"], "ft.company": ["Regulatory Context", "Konteks Kawal Selia"], "ft.body2": [ @@ -401,6 +401,19 @@ const S = { "cf.days": ["Days you drive per week", "Hari memandu seminggu"], "cf.s2": ["Budget & context", "Bajet & konteks"], "cf.budget": ["Max budget (RM)", "Bajet maksimum (RM)"], + // Under the budget slider, from the live catalogue. + "cf.budgetFits": [ + "{n} cars fit. The dearest is the {car} at {price}.", + "{n} kereta dalam bajet. Yang termahal ialah {car} pada {price}.", + ], + "cf.budgetOne": [ + "One car fits: the {car} at {price}, the cheapest we rank.", + "Satu kereta dalam bajet: {car} pada {price}, yang termurah kami nilai.", + ], + "cf.budgetNone": [ + "No car costs that little. The cheapest is the {car} at {price}.", + "Tiada kereta semurah itu. Yang termurah ialah {car} pada {price}.", + ], "cf.bill": ["Monthly electricity bill (RM)", "Bil elektrik bulanan (RM)"], "cf.work": ["Workplace charging", "Pengecasan di tempat kerja"], "cf.home": ["Home charging", "Pengecasan di rumah"], @@ -452,8 +465,8 @@ const S = { "sl.money.t": ["Financial|Optimization", "Pengoptimuman|Kewangan"], "sl.money.low": ["Low Initial Price", "Harga Awal Rendah"], - "sl.money.high": ["10-Year Lowest TCO", "TCO 10 Tahun Terendah"], - "sl.money.hint": ["Balances upfront purchase price against total 10-year fuel, tax, and servicing expenses.", "Mengimbangi harga beli awal dengan jumlah kos petrol, cukai dan servis 10 tahun."], + "sl.money.high": ["5-Year Lowest TCO", "TCO 5 Tahun Terendah"], + "sl.money.hint": ["Balances what you pay upfront against five years of fuel or charging, insurance, road tax and servicing.", "Mengimbangi harga beli awal dengan lima tahun kos bahan api atau pengecasan, insurans, cukai jalan dan servis."], "sl.env.t": ["Carbon & Eco|Impact", "Impak Karbon|& Alam Sekitar"], "sl.env.low": ["Standard Emissions", "Pelepasan Biasa"], @@ -471,7 +484,7 @@ const S = { "sl.fut.hint": ["Favors brand equity, battery thermal management, and 5-year used market resale retention.", "Memilih jenama teguh, pengurusan haba bateri, dan nilai jualan semula 5 tahun."], "sl.cta": ["Calculate Ranked Recommendations", "Kira Cadangan Tersusun"], - "sl.running": ["Evaluating 170 models across 5 engines...", "Menilai 170 model merentasi 5 enjin..."], + "sl.running": ["Evaluating 171 models across 5 engines...", "Menilai 171 model merentasi 5 enjin..."], "sl.back": ["Back to diagnostic", "Kembali ke diagnostik"], "sl.err": ["Could not communicate with scoring engine. Please check backend connection.", "Gagal menghubungi enjin pengiraan. Sila semak sambungan backend."], @@ -481,7 +494,6 @@ const S = { "v.processing": ["Processing your answers", "Memproses jawapan anda"], "v.done": ["Diagnostic complete", "Diagnostik selesai"], "v.doneSub": ["Profile calibrated. Taking you to scoring…", "Profil dikalibrasi. Membawa anda ke pemarkahan…"], - "tc.sub": ["Amortized 10-year cumulative vehicle ownership expenditure", "Perbelanjaan pemilikan kenderaan terkumpul 10 tahun"], "tc.net": ["Net TCO:", "TCO bersih:"], "tc.otr": ["Purchase OTR", "Harga OTR"], "tc.tax10": ["Road Tax (10y)", "Cukai Jalan (10thn)"], @@ -498,7 +510,7 @@ const S = { "bd.warranty": ["Factory Warranty", "Waranti Kilang"], "bd.covered": ["Fully Covered", "Dilindungi Sepenuhnya"], "bd.post": ["Post-Warranty (70%+ SoH)", "Selepas Waranti (70%+ SoH)"], - "lr.needSub": ["Our 5 decision engines rank all 170 Malaysian models tailored to your daily route and charging access.", "5 enjin keputusan kami menyusun 170 model Malaysia mengikut laluan harian dan akses pengecasan anda."], + "lr.needSub": ["Our 5 decision engines rank all 171 Malaysian models tailored to your daily route and charging access.", "5 enjin keputusan kami menyusun 171 model Malaysia mengikut laluan harian dan akses pengecasan anda."], "hw.worksTitle": ["How VoltPilot works.", "Cara VoltPilot berfungsi."], "eng.n": ["Engine", "Enjin"], "eng.t1a": ["OTR Registration", "Pendaftaran OTR"], @@ -510,11 +522,11 @@ const S = { "lie.sponsor": ["Sponsor showcase", "Pameran penaja"], "lie.tagline": ["Three rows, 505 km of range, and a 10-year battery warranty.", "Tiga baris, jarak 505 km, dan waranti bateri 10 tahun."], "an.working": ["Working", "Sedang berjalan"], - "an.sub": ["Five engines are reading your answers against 170 Malaysian trims.", "Lima enjin sedang membaca jawapan anda terhadap 170 varian Malaysia."], + "an.sub": ["Five engines are reading your answers against 171 Malaysian trims.", "Lima enjin sedang membaca jawapan anda terhadap 171 varian Malaysia."], "an.l1": ["Screening", "Tapisan"], "an.l1d": ["Budget, and whether you can charge", "Bajet, dan sama ada anda boleh mengecas"], "an.l2": ["Cost", "Kos"], - "an.l2d": ["Ten years of financing, insurance, road tax", "Sepuluh tahun pembiayaan, insurans, cukai jalan"], + "an.l2d": ["Five years of financing, insurance, road tax", "Lima tahun pembiayaan, insurans, cukai jalan"], "an.l3": ["Energy", "Tenaga"], "an.l3d": ["Electricity or fuel, and well-to-wheel CO₂", "Elektrik atau bahan api, dan CO₂ well-to-wheel"], "an.l4": ["Range & charging", "Jarak & pengecasan"], @@ -522,7 +534,7 @@ const S = { "an.l5": ["Ranking", "Kedudukan"], "an.l5d": ["TOPSIS across six weighted criteria", "TOPSIS merentasi enam kriteria berwajaran"], "an.sponsor": ["Shown by", "Ditaja oleh"], - "an.s1": ["Matching your profile to 170 models…", "Memadankan profil anda dengan 170 model…"], + "an.s1": ["Matching your profile to 171 models…", "Memadankan profil anda dengan 171 model…"], "an.s2": ["Financial · behaviour · infrastructure engines…", "Enjin kewangan · tingkah laku · infrastruktur…"], "an.s3": ["Energy engine…", "Enjin tenaga…"], "an.s4": ["TOPSIS ranking…", "Kedudukan TOPSIS…"], @@ -542,13 +554,23 @@ const S = { render time rather than substituted into a flat string — Malay puts the numbers in different places and a fixed prefix/suffix pair would break. */ "r.solarBody": [ - "Add rooftop solar (average Malaysian install: capex {capex}, savings {savings}, payback {payback}). Daytime charging becomes near-free.", - "Tambah solar bumbung (purata pemasangan Malaysia: modal {capex}, penjimatan {savings}, bayar balik {payback}). Pengecasan waktu siang menjadi hampir percuma.", + "Under Solar ATAP, a {kw} rooftop system for a typical home with an EV charged overnight costs about {capex} and saves {savings}, paying back in {payback}. Power you export earns only the energy charge, so the panels pay most when you use the power yourself: charge the car in daylight when you can.", + "Di bawah Solar ATAP, sistem bumbung {kw} untuk rumah biasa dengan EV dicas waktu malam berharga kira-kira {capex} dan menjimatkan {savings}, bayar balik dalam {payback}. Tenaga yang dieksport hanya dikreditkan pada caj tenaga, jadi panel paling berbaloi apabila anda gunakan sendiri tenaganya: cas kereta pada waktu siang bila boleh.", + ], + // Which line shows is decided by the computed payback, not assumed. + "r.solarBatteryNo": [ + "A {kwh} battery adds about {bcapex} but only {bsavings} more: buy one for backup during outages, not to cut the bill.", + "Bateri {kwh} menambah kira-kira {bcapex} tetapi hanya {bsavings} lagi: belilah untuk sandaran ketika bekalan terputus, bukan untuk mengurangkan bil.", + ], + "r.solarBatteryYes": [ + "A {kwh} battery adds about {bcapex} and {bsavings} more, paying for itself in {bpayback}.", + "Bateri {kwh} menambah kira-kira {bcapex} dan {bsavings} lagi, bayar balik dalam {bpayback}.", ], + "r.solarAsk": ["Ask the AI about solar for your home", "Tanya AI tentang solar untuk rumah anda"], "r.energyNoteLabel": ["Energy/yr", "Tenaga/thn"], "r.energyNote": [ - "is the fuel and electricity cost of driving your stated mileage for a year — petrol for hybrids, charging for EVs, blended for PHEVs. It excludes servicing, insurance, road tax and depreciation, which are counted separately in the 10-year cost of ownership.", - "ialah kos bahan api dan elektrik untuk memandu jarak yang anda nyatakan selama setahun — petrol untuk hibrid, pengecasan untuk EV, gabungan untuk PHEV. Ia tidak termasuk servis, insurans, cukai jalan dan susut nilai, yang dikira berasingan dalam kos pemilikan 10 tahun.", + "is the fuel and electricity cost of driving your stated mileage for a year — petrol for hybrids, charging for EVs, blended for PHEVs. It excludes servicing, insurance, road tax and depreciation, which are counted separately in the 5-year cost of ownership.", + "ialah kos bahan api dan elektrik untuk memandu jarak yang anda nyatakan selama setahun — petrol untuk hibrid, pengecasan untuk EV, gabungan untuk PHEV. Ia tidak termasuk servis, insurans, cukai jalan dan susut nilai, yang dikira berasingan dalam kos pemilikan 5 tahun.", ], "r.solarPayback": ["{n} years", "{n} tahun"], "r.dash": ["Full dashboard", "Papan pemuka penuh"], @@ -602,7 +624,7 @@ const S = { "We evaluate every car through 5 specialized domain engines before synthesizing with TOPSIS multi-criteria optimization.", "Kami menilai setiap kereta melalui 5 enjin domain khusus sebelum menggabungkannya dengan pengoptimuman pelbagai kriteria TOPSIS.", ], - "eng.insurance10": ["10-Year Insurance", "Insurans 10 Tahun"], + "eng.insurance5": ["5-Year Insurance", "Insurans 5 Tahun"], "rc.backResults": ["← Back to results", "← Kembali ke keputusan"], "rc.annualRunning": ["annual running cost (top pick)", "kos operasi tahunan (pilihan utama)"], "ch.sohTitle": [ @@ -610,8 +632,7 @@ const S = { "Keadaan Kesihatan Bateri 15 Tahun (SoH)", ], "ch.warrantyStd": ["8-Year / 160,000 km standard", "Standard 8 Tahun / 160,000 km"], - "ch.tcoHorizon": ["10-Year Horizon", "Ufuk 10 Tahun"], - "nav.modelCount": ["170 Models", "170 Model"], + "nav.modelCount": ["171 Models", "171 Model"], "r.topsis": ["TOPSIS score", "Skor TOPSIS"], "r.filterBody": ["Filter by body type", "Tapis mengikut jenis badan"], "r.allBody": ["All body types", "Semua jenis badan"], @@ -745,10 +766,24 @@ const S = { "ch.title": ["AI analyst", "Penganalisis AI"], "ch.sub": ["Knows your results", "Tahu keputusan anda"], "ch.results": ["Results", "Keputusan"], - "ch.q1": ["Best EV for road trips?", "EV terbaik untuk perjalanan jauh?"], - "ch.q2": ["Charging cost per 100 km?", "Kos mengecas setiap 100 km?"], - "ch.q3": ["Compare my top 2", "Bandingkan 2 teratas saya"], - "ch.q4": ["Battery warranty coverage?", "Perlindungan waranti bateri?"], + "ch.hello": [ + "Hi! I'm your AI analyst. Ask me anything about your results: pricing, charging, servicing, solar, battery degradation or the roadmap. (Malay works too.)", + "Hai! Saya penganalisis AI anda. Tanya apa sahaja tentang keputusan anda: harga, pengecasan, servis, solar, degradasi bateri atau pelan tindakan. (Bahasa Inggeris pun boleh.)", + ], + "ch.offline": ["The analyst is offline right now. Try again in a moment.", "Penganalisis tidak dapat dihubungi sekarang. Cuba lagi sebentar lagi."], + "ch.thinking": ["Thinking…", "Sedang berfikir…"], + + // Ready-made questions: chips on the results page and in the chat. Each one + // opens /chat/?q= and is sent as soon as the chat loads. + "ask.label": ["Ask the AI", "Tanya AI"], + "ask.family": ["Which of my top picks suits a family best?", "Antara pilihan teratas saya, yang mana paling sesuai untuk keluarga?"], + "ask.cheaper": ["Is an EV or a hybrid cheaper for how I drive?", "EV atau hibrid, mana lebih jimat untuk cara saya memandu?"], + "ask.service": ["Which of my top picks costs least to service over five years?", "Antara pilihan teratas saya, yang mana paling murah diservis dalam lima tahun?"], + "ask.solar": ["Should I add solar at home, and is a battery worth it?", "Patutkah saya pasang solar di rumah, dan berbaloikah bateri?"], + "ask.subsidy": ["Does the BUDI95 petrol quota cover my driving?", "Adakah kuota petrol BUDI95 cukup untuk pemanduan saya?"], + "ask.charge": ["When is the cheapest time to charge at home?", "Bilakah masa paling murah untuk mengecas di rumah?"], + "ask.top2": ["Compare my top 2", "Bandingkan 2 teratas saya"], + "ask.battery": ["How much does battery degradation matter for my EV?", "Sejauh mana degradasi bateri penting untuk EV saya?"], "ch.placeholder": ["Ask about your results…", "Tanya tentang keputusan anda…"], "ch.note": ["Battery answers are education, not a change to your ranking.", "Jawapan bateri bersifat pendidikan, bukan perubahan pada kedudukan anda."], "ch.send": ["Send", "Hantar"], diff --git a/frontend/next.config.ts b/frontend/next.config.ts index 1f037de..7d358c4 100644 --- a/frontend/next.config.ts +++ b/frontend/next.config.ts @@ -29,6 +29,11 @@ const nextConfig: NextConfig = { reactStrictMode: true, // Lets a build run without clobbering the .next a dev server is holding open. distDir: process.env.NEXT_DIST_DIR || ".next", + // The methodology page became "Method & sources" at /method once it also held + // the regulatory figures and official sources; old links keep working. + async redirects() { + return [{ source: "/methodology", destination: "/method", permanent: true }]; + }, async rewrites() { return [ { diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 2e9f1d6..9136155 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -11,6 +11,7 @@ "@google/genai": "^1.0.0", "@react-three/fiber": "^9.0.0", "gsap": "^3.13.0", + "katex": "^0.19.1", "lucide-react": "^0.525.0", "next": "^15.3.0", "react": "^19.1.0", @@ -1394,6 +1395,15 @@ "integrity": "sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==", "license": "MIT" }, + "node_modules/commander": { + "version": "15.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-15.1.0.tgz", + "integrity": "sha512-cgnQ88TRrWcC7pVq46RzJVRMktu3W2RcbnoidnfBsl1bmDCBwJS/udcIZpKoCrbAYYaCqsz1yZCVIgbIaU3ddQ==", + "license": "MIT", + "engines": { + "node": ">=22.12.0" + } + }, "node_modules/csstype": { "version": "3.2.3", "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", @@ -1659,6 +1669,22 @@ "safe-buffer": "^5.0.1" } }, + "node_modules/katex": { + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/katex/-/katex-0.19.1.tgz", + "integrity": "sha512-jG8uKntjSEcm2EpQOh0XturpPuuC9r3Sq5HLHdsFdWZT27E672SF19QEi+of0/YeOy15lDgRhKvr5614uRrEfA==", + "funding": [ + "https://opencollective.com/katex", + "https://github.com/sponsors/katex" + ], + "license": "MIT", + "dependencies": { + "commander": "^15.0.0" + }, + "bin": { + "katex": "cli.js" + } + }, "node_modules/lightningcss": { "version": "1.32.0", "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz", diff --git a/frontend/package.json b/frontend/package.json index 782e6b1..43c208c 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -14,6 +14,7 @@ "@google/genai": "^1.0.0", "@react-three/fiber": "^9.0.0", "gsap": "^3.13.0", + "katex": "^0.19.1", "lucide-react": "^0.525.0", "next": "^15.3.0", "react": "^19.1.0", diff --git a/frontend/tests/guardrails.test.mjs b/frontend/tests/guardrails.test.mjs index f2c3660..7880a6b 100644 --- a/frontend/tests/guardrails.test.mjs +++ b/frontend/tests/guardrails.test.mjs @@ -263,7 +263,7 @@ describe("voice interview", () => { }); describe("routes", () => { - const ROUTES = ["/", "/methodology", "/analysis", "/sliders", "/interview/form"]; + const ROUTES = ["/", "/method", "/analysis", "/sliders", "/interview/form"]; let up = false; before(async () => { diff --git a/scripts/build_provenance.py b/scripts/build_provenance.py index fea560e..a960b6b 100644 --- a/scripts/build_provenance.py +++ b/scripts/build_provenance.py @@ -73,7 +73,12 @@ def provenance_for(v: dict) -> dict: # --- maintenance: measured on 22 rows; the rest fall back in code ------- if own.get("maintenance_rm_yr"): - out["maintenance_rm_yr"] = {"method": MEASURED, "basis": "published service schedule"} + # Rows filled from 14 Nov 2026 carry the five-year total and where it + # came from; older measured rows have only the annual figure. + out["maintenance_rm_yr"] = { + "method": MEASURED, + "basis": own.get("maintenance_note", "published service schedule"), + } # --- consumption -------------------------------------------------------- if specs.get("fuel_l_per_100km"):