Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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/<id> 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.
Expand Down
47 changes: 43 additions & 4 deletions backend/app/engines/engines.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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"]
Expand Down Expand Up @@ -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 {
Expand Down
5 changes: 3 additions & 2 deletions backend/app/routers/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"])
Expand All @@ -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")
Expand Down
5 changes: 3 additions & 2 deletions backend/app/routers/report.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down
40 changes: 36 additions & 4 deletions backend/app/routers/results.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,16 @@

import asyncio
import logging
import math
import time
from datetime import datetime

from fastapi import APIRouter, Depends, HTTPException
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,
)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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")
Expand Down
7 changes: 7 additions & 0 deletions backend/app/services/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"):
Expand Down
Loading
Loading