Compare commits

..

10 Commits

Author SHA1 Message Date
Deeman
c3847bb617 merge: Market Score v4 + Opportunity Score v5
All checks were successful
CI / test (push) Successful in 55s
CI / tag (push) Successful in 2s
2026-03-08 15:32:26 +01:00
Deeman
fcef47cb22 chore: update CHANGELOG + admin dependency graph for score v4/v5
- CHANGELOG.md: document Market Score v4 and Opportunity Score v5 changes
- pipeline_routes.py: add dim_countries to location_profiles dependency list

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 15:32:06 +01:00
Deeman
118c2c0fc7 feat(scoring): Opportunity Score v4 → v5 — fix correlated components
- Merge supply gap (30pts) + catchment gap (15pts) → supply deficit (35pts, GREATEST)
  Eliminates ~80% correlated double-count on a single signal.
- Add sports culture signal (10pts): tennis court density as racquet-sport adoption proxy.
  Ceiling 50 courts/25km. Harmless when tennis data is zero (contributes 0).
- Add construction affordability (5pts): income relative to PLI construction costs.
  Joins dim_countries.pli_construction. High income + low build cost = high score.
- Reduce economic power from 20 → 15pts to make room.

New weights: addressable market 25, economic power 15, supply deficit 35,
sports culture 10, construction affordability 5, market validation 10.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 15:30:04 +01:00
Deeman
cd6d950233 feat(scoring): Market Score v3 → v4 — fix Spain underscoring
- Lower count gate threshold: 5 → 3 venues (3 establishes a market pattern)
- Lower density ceiling: LN(21) → LN(11) (10/100k is reachable for mature markets)
- Better demand fallback: 0.4 → 0.65 multiplier + 0.3 floor (venues = demand evidence)
- Fix economic context: income/200 → income/25000 (actual discrimination vs free 10 pts)

Expected: Spain avg market score rises from ~54 to ~65-75.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 15:22:48 +01:00
Deeman
28e44384ef merge: opportunity map HTMX data islands + remove dead API endpoint
All checks were successful
CI / test (push) Successful in 1m0s
CI / tag (push) Successful in 3s
# Conflicts:
#	transform/sqlmesh_padelnomics/models/serving/location_opportunity_profile.sql
#	web/src/padelnomics/api.py
#	web/src/padelnomics/public/templates/opportunity_map.html
2026-03-07 21:05:52 +01:00
Deeman
b1e008a2a4 refactor(maps): opportunity map → HTMX data islands, remove dead API endpoint
- Delete opportunity() JSON endpoint from api.py (dead after this refactor)
- Add GET /opportunity-map/data route returning HTML partial with two JSON
  data islands (opp_points + ref_points from serving.location_profiles)
- Create partials/opportunity_map_data.html (2-line data island partial)
- Rewrite opportunity_map.html: HTMX attrs on <select>, invisible #map-data
  swap target, htmx:afterSwap listener replaces fetch()-based loadCountry()

city_venues endpoint stays public (article-maps.js calls it on public pages).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-07 20:56:45 +01:00
Deeman
d556ceecee fix(api): restore public access to country_cities + opportunity endpoints
opportunity_map.html (public page) still fetches these. Only countries.json
and city_venues.json are no longer called from any public page, so those two
keep @login_required.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-07 20:41:12 +01:00
Deeman
f215ea8e3a fix: supply gap inflation + inline map data + guard API endpoints
A. location_profiles.sql: supply gap now uses GREATEST(catchment_padel_courts,
   COALESCE(city_padel_venue_count, 0)) so Playtomic venues prevent cities like
   Murcia/Cordoba/Gijon from receiving a full 30-pt supply gap bonus when their
   OSM catchment count is zero. Expected ~10-15 pt drop for affected ES cities.

B. pseo_country_overview.sql: add population-weighted lat/lon centroid columns
   so the markets map can use accurate country positions from this table.

C/D. content/routes.py + markets.html: query pseo_country_overview in the route
   and pass as map_countries to the template, replacing the fetch('/api/...') call
   with inline JSON. Map scores now match pseo_country_overview (pop-weighted),
   and the page loads without an extra round-trip.

E. api.py: add @login_required to all 4 endpoints. Unauthenticated callers get
   a 302 redirect to login instead of data.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-07 20:33:31 +01:00
Deeman
b2ffad055b fix(supervisor): use file path for export_serving (not -m module syntax)
All checks were successful
CI / test (push) Successful in 1m0s
CI / tag (push) Successful in 3s
-m padelnomics.export_serving resolves to web package, not src/padelnomics.
src/padelnomics is not a uv workspace member so it's not importable by name.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-07 18:08:46 +01:00
Deeman
c30a7943aa feat(transform): opportunity score v4 — market validation + population-weighted aggregation
Two targeted fixes for inflated country scores (ES 83, SE 77):

1. pseo_country_overview: replace AVG() with population-weighted averages
   for avg_opportunity_score and avg_market_score. Madrid/Barcelona now
   dominate Spain's average instead of hundreds of 30K-town white-space
   towns. Expected ES drop from ~83 to ~55-65.

2. location_opportunity_profile: replace dead sports culture component
   (10 pts, tennis data all zeros) with market validation signal.
   New country_market CTE aggregates city_market_profile per country_code.
   ES (~60/100) → ~6 pts (proven demand). SE (~35/100) → ~3.5 pts
   (struggling market). NULL → 0.5 neutral → 5 pts (untested market).

Score budget unchanged: 25+20+30+15+10 = 100 pts.
New dependency: location_opportunity_profile → serving.city_market_profile (no cycle).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-07 15:36:51 +01:00
11 changed files with 180 additions and 119 deletions

View File

@@ -7,6 +7,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
## [Unreleased] ## [Unreleased]
### Changed ### Changed
- **Market Score v3 → v4** — fixes Spain averaging 54 (should be 65-80). Four calibration changes: count gate threshold lowered from 5 → 3 venues (3 establishes a market pattern), density ceiling lowered from LN(21) → LN(11) (10/100k is reachable for mature markets), demand evidence fallback raised from 0.4 → 0.65 multiplier with 0.3 floor (existence of venues IS evidence of demand), economic context ceiling changed from income/200 → income/25000 (actual discrimination instead of free 10 pts for everyone).
- **Opportunity Score v4 → v5** — fixes structural flaws: supply gap (30pts) + catchment gap (15pts) merged into single supply deficit (35pts, GREATEST of density gap and distance gap) eliminating ~80% correlated double-count. New sports culture signal (10pts) using tennis court density as racquet-sport adoption proxy. New construction affordability signal (5pts) using income relative to PLI construction costs from `dim_countries`. Economic power reduced from 20 → 15pts. New dependency on `foundation.dim_countries` for `pli_construction`.
- **Unified `location_profiles` serving model** — merged `city_market_profile` and `location_opportunity_profile` into a single `serving.location_profiles` table at `(country_code, geoname_id)` grain. Both Marktreife-Score (Market Score) and Marktpotenzial-Score (Opportunity Score) are now computed per location. City data enriched via LEFT JOIN `dim_cities` on `geoname_id`. Downstream models (`planner_defaults`, `pseo_city_costs_de`, `pseo_city_pricing`) updated to query `location_profiles` directly. `city_padel_venue_count` (exact from dim_cities) distinguished from `padel_venue_count` (spatial 5km from dim_locations). - **Unified `location_profiles` serving model** — merged `city_market_profile` and `location_opportunity_profile` into a single `serving.location_profiles` table at `(country_code, geoname_id)` grain. Both Marktreife-Score (Market Score) and Marktpotenzial-Score (Opportunity Score) are now computed per location. City data enriched via LEFT JOIN `dim_cities` on `geoname_id`. Downstream models (`planner_defaults`, `pseo_city_costs_de`, `pseo_city_pricing`) updated to query `location_profiles` directly. `city_padel_venue_count` (exact from dim_cities) distinguished from `padel_venue_count` (spatial 5km from dim_locations).
- **Both scores on all map tooltips** — country map shows avg Market Score + avg Opportunity Score; city map shows Market Score + Opportunity Score per city; opportunity map shows Opportunity Score + Market Score per location. All score labels use the trademarked "Padelnomics Market Score" / "Padelnomics Opportunity Score" names. - **Both scores on all map tooltips** — country map shows avg Market Score + avg Opportunity Score; city map shows Market Score + Opportunity Score per city; opportunity map shows Opportunity Score + Market Score per location. All score labels use the trademarked "Padelnomics Market Score" / "Padelnomics Opportunity Score" names.
- **API endpoints** — `/api/markets/countries.json` adds `avg_opportunity_score`; `/api/markets/<country>/cities.json` adds `opportunity_score`; `/api/opportunity/<country>.json` adds `market_score`. - **API endpoints** — `/api/markets/countries.json` adds `avg_opportunity_score`; `/api/markets/<country>/cities.json` adds `opportunity_score`; `/api/opportunity/<country>.json` adds `market_score`.

View File

@@ -42,7 +42,7 @@ do
# The web app detects the inode change on next query — no restart needed. # The web app detects the inode change on next query — no restart needed.
DUCKDB_PATH="${DUCKDB_PATH:-/data/padelnomics/lakehouse.duckdb}" \ DUCKDB_PATH="${DUCKDB_PATH:-/data/padelnomics/lakehouse.duckdb}" \
SERVING_DUCKDB_PATH="${SERVING_DUCKDB_PATH:-/data/padelnomics/analytics.duckdb}" \ SERVING_DUCKDB_PATH="${SERVING_DUCKDB_PATH:-/data/padelnomics/analytics.duckdb}" \
uv run python -m padelnomics.export_serving uv run python src/padelnomics/export_serving.py
) || { ) || {
if [ -n "${ALERT_WEBHOOK_URL:-}" ]; then if [ -n "${ALERT_WEBHOOK_URL:-}" ]; then

View File

@@ -5,30 +5,36 @@
-- --
-- Two scores per location: -- Two scores per location:
-- --
-- Padelnomics Market Score (Marktreife-Score v3, 0100): -- Padelnomics Market Score (Marktreife-Score v4, 0100):
-- "How mature/established is this padel market?" -- "How mature/established is this padel market?"
-- Only meaningful for locations matched to a dim_cities row (city_slug IS NOT NULL) -- Only meaningful for locations matched to a dim_cities row (city_slug IS NOT NULL)
-- with padel venues. 0 for all other locations. -- with padel venues. 0 for all other locations.
-- --
-- 40 pts supply development — log-scaled density (LN ceiling 20/100k) × count gate -- v4 changes: lower count gate (5→3), lower density ceiling (LN(21)→LN(11)),
-- 25 pts demand evidence — occupancy when available; 40% density proxy otherwise -- better demand fallback (0.4→0.65 with 0.3 floor), economic context discrimination (200→25K).
--
-- 40 pts supply development — log-scaled density (LN ceiling 10/100k) × count gate (3)
-- 25 pts demand evidence — occupancy when available; 65% density proxy + 0.3 floor otherwise
-- 15 pts addressable market — log-scaled population, ceiling 1M -- 15 pts addressable market — log-scaled population, ceiling 1M
-- 10 pts economic context — income PPS normalised to 200 ceiling -- 10 pts economic context — income PPS normalised to 25,000 ceiling
-- 10 pts data quality — completeness discount -- 10 pts data quality — completeness discount
-- --
-- Padelnomics Opportunity Score (Marktpotenzial-Score v4, 0100): -- Padelnomics Opportunity Score (Marktpotenzial-Score v5, 0100):
-- "Where should I build a padel court?" -- "Where should I build a padel court?"
-- Computed for ALL locations — zero-court locations score highest on supply gap. -- Computed for ALL locations — zero-court locations score highest on supply deficit.
-- H3 catchment methodology: addressable market and supply gap use a regional -- H3 catchment methodology: addressable market and supply deficit use a regional
-- H3 catchment (res-5 cell + 6 neighbours, ~24km radius). -- H3 catchment (res-5 cell + 6 neighbours, ~24km radius).
-- --
-- 25 pts addressable market — log-scaled catchment population, ceiling 500K -- v5 changes: merge supply gap + catchment gap → single supply deficit (35 pts),
-- 20 pts economic power — income PPS, normalised to 35,000 -- add sports culture proxy (10 pts, tennis density), add construction affordability (5 pts),
-- 30 pts supply gap — inverted catchment venue density; 0 courts = full marks -- reduce economic power from 20 → 15 pts.
-- 15 pts catchment gap — distance to nearest padel court --
-- 10 pts market validation — country-level avg market maturity (from market_scored CTE). -- 25 pts addressable market — log-scaled catchment population, ceiling 500K
-- Replaces sports culture proxy (v3: tennis data was all zeros). -- 15 pts economic power — income PPS, normalised to 35,000
-- ES (~60/100) → ~6 pts, SE (~35/100) → ~3.5 pts, unknown → 5 pts. -- 35 pts supply deficit — max(density gap, distance gap); eliminates double-count
-- 10 pts sports culture — tennis court density as racquet-sport adoption proxy
-- 5 pts construction affordability — income relative to construction costs (PLI)
-- 10 pts market validation — country-level avg market maturity (from market_scored CTE)
-- --
-- Consumers query directly with WHERE filters: -- Consumers query directly with WHERE filters:
-- cities API: WHERE country_slug = ? AND city_slug IS NOT NULL -- cities API: WHERE country_slug = ? AND city_slug IS NOT NULL
@@ -107,7 +113,7 @@ city_match AS (
ORDER BY c.padel_venue_count DESC ORDER BY c.padel_venue_count DESC
) = 1 ) = 1
), ),
-- Pricing / occupancy from Playtomic (via city_slug) + H3 catchment -- Pricing / occupancy from Playtomic (via city_slug) + H3 catchment + country PLI
with_pricing AS ( with_pricing AS (
SELECT SELECT
b.*, b.*,
@@ -120,6 +126,7 @@ with_pricing AS (
vpb.median_occupancy_rate, vpb.median_occupancy_rate,
vpb.median_daily_revenue_per_venue, vpb.median_daily_revenue_per_venue,
vpb.price_currency, vpb.price_currency,
dc.pli_construction,
COALESCE(ct.catchment_population, b.population)::BIGINT AS catchment_population, COALESCE(ct.catchment_population, b.population)::BIGINT AS catchment_population,
COALESCE(ct.catchment_padel_courts, b.padel_venue_count)::INTEGER AS catchment_padel_courts COALESCE(ct.catchment_padel_courts, b.padel_venue_count)::INTEGER AS catchment_padel_courts
FROM base b FROM base b
@@ -131,6 +138,8 @@ with_pricing AS (
AND cm.city_slug = vpb.city_slug AND cm.city_slug = vpb.city_slug
LEFT JOIN catchment ct LEFT JOIN catchment ct
ON b.geoname_id = ct.geoname_id ON b.geoname_id = ct.geoname_id
LEFT JOIN foundation.dim_countries dc
ON b.country_code = dc.country_code
), ),
-- Step 1: market score only — needed first so we can aggregate country averages. -- Step 1: market score only — needed first so we can aggregate country averages.
market_scored AS ( market_scored AS (
@@ -146,34 +155,38 @@ market_scored AS (
WHEN population > 0 OR COALESCE(city_padel_venue_count, 0) > 0 THEN 0.5 WHEN population > 0 OR COALESCE(city_padel_venue_count, 0) > 0 THEN 0.5
ELSE 0.0 ELSE 0.0
END AS data_confidence, END AS data_confidence,
-- ── Market Score (Marktreife-Score v3) ────────────────────────────────── -- ── Market Score (Marktreife-Score v4) ──────────────────────────────────
-- 0 when no city match or no venues (city_padel_venue_count NULL or 0) -- 0 when no city match or no venues (city_padel_venue_count NULL or 0)
CASE WHEN COALESCE(city_padel_venue_count, 0) > 0 THEN CASE WHEN COALESCE(city_padel_venue_count, 0) > 0 THEN
ROUND( ROUND(
-- Supply development (40 pts) -- Supply development (40 pts)
-- density ceiling 10/100k (LN(11)), count gate 3 venues
40.0 * LEAST(1.0, LN( 40.0 * LEAST(1.0, LN(
COALESCE( COALESCE(
CASE WHEN population > 0 CASE WHEN population > 0
THEN COALESCE(city_padel_venue_count, 0)::DOUBLE / population * 100000 THEN COALESCE(city_padel_venue_count, 0)::DOUBLE / population * 100000
ELSE 0 END ELSE 0 END
, 0) + 1) / LN(21)) , 0) + 1) / LN(11))
* LEAST(1.0, COALESCE(city_padel_venue_count, 0) / 5.0) * LEAST(1.0, COALESCE(city_padel_venue_count, 0) / 3.0)
-- Demand evidence (25 pts) -- Demand evidence (25 pts)
-- with occupancy: scale to 65% target. Without: 65% of supply proxy + 0.3 floor
-- (existence of venues IS evidence of demand)
+ 25.0 * CASE + 25.0 * CASE
WHEN median_occupancy_rate IS NOT NULL WHEN median_occupancy_rate IS NOT NULL
THEN LEAST(1.0, median_occupancy_rate / 0.65) THEN LEAST(1.0, median_occupancy_rate / 0.65)
ELSE 0.4 * LEAST(1.0, LN( ELSE GREATEST(0.3, 0.65 * LEAST(1.0, LN(
COALESCE( COALESCE(
CASE WHEN population > 0 CASE WHEN population > 0
THEN COALESCE(city_padel_venue_count, 0)::DOUBLE / population * 100000 THEN COALESCE(city_padel_venue_count, 0)::DOUBLE / population * 100000
ELSE 0 END ELSE 0 END
, 0) + 1) / LN(21)) , 0) + 1) / LN(11))
* LEAST(1.0, COALESCE(city_padel_venue_count, 0) / 5.0) * LEAST(1.0, COALESCE(city_padel_venue_count, 0) / 3.0))
END END
-- Addressable market (15 pts) -- Addressable market (15 pts)
+ 15.0 * LEAST(1.0, LN(GREATEST(population, 1)) / LN(1000000)) + 15.0 * LEAST(1.0, LN(GREATEST(population, 1)) / LN(1000000))
-- Economic context (10 pts) -- Economic context (10 pts)
+ 10.0 * LEAST(1.0, COALESCE(median_income_pps, 100) / 200.0) -- ceiling 25,000 PPS discriminates between wealthy and poorer markets
+ 10.0 * LEAST(1.0, COALESCE(median_income_pps, 15000) / 25000.0)
-- Data quality (10 pts) -- Data quality (10 pts)
+ 10.0 * CASE + 10.0 * CASE
WHEN population > 0 AND COALESCE(city_padel_venue_count, 0) > 0 THEN 1.0 WHEN population > 0 AND COALESCE(city_padel_venue_count, 0) > 0 THEN 1.0
@@ -199,23 +212,35 @@ country_market AS (
-- Step 3: add opportunity_score using country market validation signal. -- Step 3: add opportunity_score using country market validation signal.
scored AS ( scored AS (
SELECT ms.*, SELECT ms.*,
-- ── Opportunity Score (Marktpotenzial-Score v4, H3 catchment) ────────── -- ── Opportunity Score (Marktpotenzial-Score v5, H3 catchment) ──────────
ROUND( ROUND(
-- Addressable market (25 pts): log-scaled catchment population, ceiling 500K -- Addressable market (25 pts): log-scaled catchment population, ceiling 500K
25.0 * LEAST(1.0, LN(GREATEST(catchment_population, 1)) / LN(500000)) 25.0 * LEAST(1.0, LN(GREATEST(catchment_population, 1)) / LN(500000))
-- Economic power (20 pts): income PPS normalised to 35,000 -- Economic power (15 pts): income PPS normalised to 35,000
+ 20.0 * LEAST(1.0, COALESCE(median_income_pps, 15000) / 35000.0) + 15.0 * LEAST(1.0, COALESCE(median_income_pps, 15000) / 35000.0)
-- Supply gap (30 pts): inverted catchment venue density -- Supply deficit (35 pts): max of density gap and distance gap.
+ 30.0 * GREATEST(0.0, 1.0 - COALESCE( -- Merges old supply gap (30) + catchment gap (15) which were ~80% correlated.
CASE WHEN catchment_population > 0 + 35.0 * GREATEST(
THEN catchment_padel_courts::DOUBLE / catchment_population * 100000 -- density-based gap (H3 catchment): 0 courts = 1.0, 8/100k = 0.0
ELSE 0.0 GREATEST(0.0, 1.0 - COALESCE(
END, 0.0) / 8.0) CASE WHEN catchment_population > 0
-- Catchment gap (15 pts): distance to nearest court THEN GREATEST(catchment_padel_courts, COALESCE(city_padel_venue_count, 0))::DOUBLE / catchment_population * 100000
+ 15.0 * COALESCE(LEAST(1.0, nearest_padel_court_km / 30.0), 0.5) ELSE 0.0
END, 0.0) / 8.0),
-- distance-based gap: 30km+ = 1.0, 0km = 0.0; NULL = 0.5
COALESCE(LEAST(1.0, nearest_padel_court_km / 30.0), 0.5)
)
-- Sports culture (10 pts): tennis density as racquet-sport adoption proxy.
-- Ceiling 50 courts within 25km. Harmless when tennis data is zero (contributes 0).
+ 10.0 * LEAST(1.0, COALESCE(tennis_courts_within_25km, 0) / 50.0)
-- Construction affordability (5 pts): income purchasing power relative to build costs.
-- PLI construction is EU27=100 index. High income + low construction cost = high score.
+ 5.0 * LEAST(1.0,
COALESCE(median_income_pps, 15000) / 35000.0
/ GREATEST(0.5, COALESCE(pli_construction, 100.0) / 100.0)
)
-- Market validation (10 pts): country-level avg market maturity. -- Market validation (10 pts): country-level avg market maturity.
-- Replaces sports culture (v3 tennis data was all zeros = dead code). -- ES (~70/100): proven demand → ~7 pts. SE (~35/100): emerging → ~3.5 pts.
-- ES (~60/100): proven demand → ~6 pts. SE (~35/100): struggling → ~3.5 pts.
-- NULL (no courts in country yet): 0.5 neutral → 5 pts (untested, not penalised). -- NULL (no courts in country yet): 0.5 neutral → 5 pts (untested, not penalised).
+ 10.0 * COALESCE(cm.country_avg_market_score / 100.0, 0.5) + 10.0 * COALESCE(cm.country_avg_market_score / 100.0, 0.5)
, 1) AS opportunity_score , 1) AS opportunity_score

View File

@@ -37,6 +37,8 @@ SELECT
-- Use the most common currency in the country (MIN is deterministic for single-currency countries) -- Use the most common currency in the country (MIN is deterministic for single-currency countries)
MIN(price_currency) AS price_currency, MIN(price_currency) AS price_currency,
SUM(population) AS total_population, SUM(population) AS total_population,
ROUND(SUM(lat * population) / NULLIF(SUM(population), 0), 4) AS lat,
ROUND(SUM(lon * population) / NULLIF(SUM(population), 0), 4) AS lon,
CURRENT_DATE AS refreshed_date CURRENT_DATE AS refreshed_date
FROM serving.pseo_city_costs_de FROM serving.pseo_city_costs_de
GROUP BY country_code, country_name_en, country_slug GROUP BY country_code, country_name_en, country_slug

View File

@@ -111,7 +111,7 @@ _DAG: dict[str, list[str]] = {
"fct_daily_availability": ["fct_availability_slot", "dim_venue_capacity"], "fct_daily_availability": ["fct_availability_slot", "dim_venue_capacity"],
# Serving # Serving
"venue_pricing_benchmarks": ["fct_daily_availability"], "venue_pricing_benchmarks": ["fct_daily_availability"],
"location_profiles": ["dim_locations", "dim_cities", "venue_pricing_benchmarks"], "location_profiles": ["dim_locations", "dim_cities", "dim_countries", "venue_pricing_benchmarks"],
"planner_defaults": ["venue_pricing_benchmarks", "location_profiles"], "planner_defaults": ["venue_pricing_benchmarks", "location_profiles"],
"pseo_city_costs_de": [ "pseo_city_costs_de": [
"location_profiles", "planner_defaults", "location_profiles", "planner_defaults",

View File

@@ -8,6 +8,7 @@ daily when the pipeline runs).
from quart import Blueprint, abort, jsonify from quart import Blueprint, abort, jsonify
from .analytics import fetch_analytics from .analytics import fetch_analytics
from .auth.routes import login_required
from .core import fetch_all, is_flag_enabled from .core import fetch_all, is_flag_enabled
bp = Blueprint("api", __name__) bp = Blueprint("api", __name__)
@@ -26,6 +27,7 @@ async def _require_maps_flag() -> None:
@bp.route("/markets/countries.json") @bp.route("/markets/countries.json")
@login_required
async def countries(): async def countries():
"""Country-level aggregates for the markets hub map.""" """Country-level aggregates for the markets hub map."""
await _require_maps_flag() await _require_maps_flag()
@@ -96,23 +98,3 @@ async def city_venues(country_slug: str, city_slug: str):
) )
return jsonify(rows), 200, _CACHE_HEADERS return jsonify(rows), 200, _CACHE_HEADERS
@bp.route("/opportunity/<country_slug>.json")
async def opportunity(country_slug: str):
"""Location-level opportunity scores for the opportunity map."""
await _require_maps_flag()
assert country_slug, "country_slug required"
rows = await fetch_analytics(
"""
SELECT location_name, location_slug, lat, lon,
opportunity_score, market_score,
nearest_padel_court_km,
padel_venue_count, population
FROM serving.location_profiles
WHERE country_slug = ? AND opportunity_score > 0
ORDER BY opportunity_score DESC
LIMIT 500
""",
[country_slug],
)
return jsonify(rows), 200, _CACHE_HEADERS

View File

@@ -9,6 +9,7 @@ from jinja2 import Environment, FileSystemLoader
from markupsafe import Markup from markupsafe import Markup
from quart import Blueprint, abort, g, redirect, render_template, request from quart import Blueprint, abort, g, redirect, render_template, request
from ..analytics import fetch_analytics
from ..core import ( from ..core import (
REPO_ROOT, REPO_ROOT,
capture_waitlist_email, capture_waitlist_email,
@@ -203,6 +204,14 @@ async def markets():
) )
articles = await _filter_articles(q, country, region) articles = await _filter_articles(q, country, region)
map_countries = await fetch_analytics("""
SELECT country_code, country_name_en, country_slug,
city_count, total_venues,
avg_market_score, avg_opportunity_score,
lat, lon
FROM serving.pseo_country_overview
ORDER BY total_venues DESC
""")
return await render_template( return await render_template(
"markets.html", "markets.html",
@@ -212,6 +221,7 @@ async def markets():
current_q=q, current_q=q,
current_country=country, current_country=country,
current_region=region, current_region=region,
map_countries=map_countries,
) )

View File

@@ -92,27 +92,25 @@
}); });
} }
fetch('/api/markets/countries.json') var data = {{ map_countries | tojson }};
.then(function(r) { return r.json(); }) if (data.length) {
.then(function(data) { var maxV = Math.max.apply(null, data.map(function(d) { return d.total_venues; }));
if (!data.length) return; var lang = document.documentElement.lang || 'en';
var maxV = Math.max.apply(null, data.map(function(d) { return d.total_venues; })); data.forEach(function(c) {
var lang = document.documentElement.lang || 'en'; if (!c.lat || !c.lon) return;
data.forEach(function(c) { var size = 12 + 44 * Math.sqrt(c.total_venues / maxV);
if (!c.lat || !c.lon) return; var color = scoreColor(c.avg_market_score);
var size = 12 + 44 * Math.sqrt(c.total_venues / maxV); var oppColor = c.avg_opportunity_score >= 60 ? '#16A34A' : (c.avg_opportunity_score >= 30 ? '#D97706' : '#3B82F6');
var color = scoreColor(c.avg_market_score); var tip = '<strong>' + c.country_name_en + '</strong><br>'
var oppColor = c.avg_opportunity_score >= 60 ? '#16A34A' : (c.avg_opportunity_score >= 30 ? '#D97706' : '#3B82F6'); + c.total_venues + ' venues · ' + c.city_count + ' cities<br>'
var tip = '<strong>' + c.country_name_en + '</strong><br>' + '<span style="color:' + color + ';font-weight:600;">Padelnomics Market Score: ' + c.avg_market_score + '/100</span><br>'
+ c.total_venues + ' venues · ' + c.city_count + ' cities<br>' + '<span style="color:' + oppColor + ';font-weight:600;">Padelnomics Opportunity Score: ' + (c.avg_opportunity_score || 0) + '/100</span>';
+ '<span style="color:' + color + ';font-weight:600;">Padelnomics Market Score: ' + c.avg_market_score + '/100</span><br>' L.marker([c.lat, c.lon], { icon: makeIcon(size, color) })
+ '<span style="color:' + oppColor + ';font-weight:600;">Padelnomics Opportunity Score: ' + (c.avg_opportunity_score || 0) + '/100</span>'; .bindTooltip(tip, { className: 'map-tooltip', direction: 'top', offset: [0, -Math.round(size / 2)] })
L.marker([c.lat, c.lon], { icon: makeIcon(size, color) }) .on('click', function() { window.location = '/' + lang + '/markets/' + c.country_slug; })
.bindTooltip(tip, { className: 'map-tooltip', direction: 'top', offset: [0, -Math.round(size / 2)] }) .addTo(map);
.on('click', function() { window.location = '/' + lang + '/markets/' + c.country_slug; })
.addTo(map);
});
}); });
}
})(); })();
</script> </script>
{% endblock %} {% endblock %}

View File

@@ -87,6 +87,46 @@ async def opportunity_map():
return await render_template("opportunity_map.html", countries=countries) return await render_template("opportunity_map.html", countries=countries)
@bp.route("/opportunity-map/data")
async def opportunity_map_data():
"""HTMX partial: opportunity + reference data islands for Leaflet map."""
from ..core import is_flag_enabled
if not await is_flag_enabled("maps", default=True):
abort(404)
country_slug = request.args.get("country", "")
if not country_slug:
return ""
opp_points = await fetch_analytics(
"""
SELECT location_name, location_slug, lat, lon,
opportunity_score, market_score,
nearest_padel_court_km, padel_venue_count, population
FROM serving.location_profiles
WHERE country_slug = ? AND opportunity_score > 0
ORDER BY opportunity_score DESC
LIMIT 500
""",
[country_slug],
)
ref_points = await fetch_analytics(
"""
SELECT city_name, city_slug, lat, lon,
city_padel_venue_count AS padel_venue_count,
market_score, population
FROM serving.location_profiles
WHERE country_slug = ? AND city_slug IS NOT NULL
ORDER BY city_padel_venue_count DESC
LIMIT 200
""",
[country_slug],
)
return await render_template(
"partials/opportunity_map_data.html",
opp_points=opp_points,
ref_points=ref_points,
)
@bp.route("/imprint") @bp.route("/imprint")
async def imprint(): async def imprint():
lang = g.get("lang", "en") lang = g.get("lang", "en")

View File

@@ -24,7 +24,10 @@
<div class="card mb-4" style="padding: 1rem 1.25rem;"> <div class="card mb-4" style="padding: 1rem 1.25rem;">
<label class="form-label" for="opp-country-select" style="margin-bottom: 0.5rem; display:block;">Select a country</label> <label class="form-label" for="opp-country-select" style="margin-bottom: 0.5rem; display:block;">Select a country</label>
<select id="opp-country-select" class="form-input" style="max-width: 280px;"> <select id="opp-country-select" name="country" class="form-input" style="max-width:280px;"
hx-get="{{ url_for('public.opportunity_map_data') }}"
hx-target="#map-data"
hx-trigger="change">
<option value="">— choose country —</option> <option value="">— choose country —</option>
{% for c in countries %} {% for c in countries %}
<option value="{{ c.country_slug }}">{{ c.country_name_en }}</option> <option value="{{ c.country_slug }}">{{ c.country_name_en }}</option>
@@ -33,6 +36,7 @@
</div> </div>
<div id="opportunity-map"></div> <div id="opportunity-map"></div>
<div id="map-data" style="display:none;"></div>
<div class="mt-4 text-sm text-slate"> <div class="mt-4 text-sm text-slate">
<strong>Circle size:</strong> population &nbsp;|&nbsp; <strong>Circle size:</strong> population &nbsp;|&nbsp;
@@ -86,53 +90,48 @@
: (p || ''); : (p || '');
} }
function loadCountry(slug) { function renderMap() {
oppLayer.clearLayers(); oppLayer.clearLayers();
refLayer.clearLayers(); refLayer.clearLayers();
if (!slug) return; var oppEl = document.getElementById('opp-data');
var refEl = document.getElementById('ref-data');
if (!oppEl) return;
var oppData = JSON.parse(oppEl.textContent);
var refData = JSON.parse(refEl.textContent);
fetch('/api/opportunity/' + slug + '.json') refData.forEach(function(c) {
.then(function(r) { return r.json(); }) if (!c.lat || !c.lon || !c.padel_venue_count) return;
.then(function(data) { L.marker([c.lat, c.lon], { icon: REF_ICON })
if (!data.length) return; .bindTooltip(c.city_name + ' — ' + c.padel_venue_count + ' existing venues',
var maxPop = Math.max.apply(null, data.map(function(d) { return d.population || 1; })); { className: 'map-tooltip', direction: 'top', offset: [0, -7] })
var bounds = []; .addTo(refLayer);
data.forEach(function(loc) { });
if (!loc.lat || !loc.lon) return;
var size = 8 + 40 * Math.sqrt((loc.population || 1) / maxPop);
var color = oppColor(loc.opportunity_score);
var dist = loc.nearest_padel_court_km != null
? loc.nearest_padel_court_km.toFixed(1) + ' km to nearest court'
: 'No nearby courts';
var mktColor = loc.market_score >= 60 ? '#16A34A' : (loc.market_score >= 30 ? '#D97706' : '#DC2626');
var tip = '<strong>' + loc.location_name + '</strong><br>'
+ '<span style="color:' + color + ';font-weight:600;">Padelnomics Opportunity Score: ' + loc.opportunity_score + '/100</span><br>'
+ '<span style="color:' + mktColor + ';font-weight:600;">Padelnomics Market Score: ' + (loc.market_score || 0) + '/100</span><br>'
+ dist + ' · Pop. ' + fmtPop(loc.population);
L.marker([loc.lat, loc.lon], { icon: makeIcon(size, color) })
.bindTooltip(tip, { className: 'map-tooltip', direction: 'top', offset: [0, -Math.round(size / 2)] })
.addTo(oppLayer);
bounds.push([loc.lat, loc.lon]);
});
if (bounds.length) map.fitBounds(bounds, { padding: [30, 30] });
});
// Existing venues as small gray reference dots (drawn first = behind opp dots) if (!oppData.length) return;
fetch('/api/markets/' + slug + '/cities.json') var maxPop = Math.max.apply(null, oppData.map(function(d) { return d.population || 1; }));
.then(function(r) { return r.json(); }) var bounds = [];
.then(function(data) { oppData.forEach(function(loc) {
data.forEach(function(c) { if (!loc.lat || !loc.lon) return;
if (!c.lat || !c.lon || !c.padel_venue_count) return; var size = 8 + 40 * Math.sqrt((loc.population || 1) / maxPop);
L.marker([c.lat, c.lon], { icon: REF_ICON }) var color = oppColor(loc.opportunity_score);
.bindTooltip(c.city_name + ' — ' + c.padel_venue_count + ' existing venues', var dist = loc.nearest_padel_court_km != null
{ className: 'map-tooltip', direction: 'top', offset: [0, -7] }) ? loc.nearest_padel_court_km.toFixed(1) + ' km to nearest court'
.addTo(refLayer); : 'No nearby courts';
}); var mktColor = loc.market_score >= 60 ? '#16A34A' : (loc.market_score >= 30 ? '#D97706' : '#DC2626');
}); var tip = '<strong>' + loc.location_name + '</strong><br>'
+ '<span style="color:' + color + ';font-weight:600;">Padelnomics Opportunity Score: ' + loc.opportunity_score + '/100</span><br>'
+ '<span style="color:' + mktColor + ';font-weight:600;">Padelnomics Market Score: ' + (loc.market_score || 0) + '/100</span><br>'
+ dist + ' · Pop. ' + fmtPop(loc.population);
L.marker([loc.lat, loc.lon], { icon: makeIcon(size, color) })
.bindTooltip(tip, { className: 'map-tooltip', direction: 'top', offset: [0, -Math.round(size / 2)] })
.addTo(oppLayer);
bounds.push([loc.lat, loc.lon]);
});
if (bounds.length) map.fitBounds(bounds, { padding: [30, 30] });
} }
document.getElementById('opp-country-select').addEventListener('change', function() { document.body.addEventListener('htmx:afterSwap', function(e) {
loadCountry(this.value); if (e.detail.target.id === 'map-data') renderMap();
}); });
})(); })();
</script> </script>

View File

@@ -0,0 +1,2 @@
<script id="opp-data" type="application/json">{{ opp_points | tojson }}</script>
<script id="ref-data" type="application/json">{{ ref_points | tojson }}</script>