Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

fix(atlas): count places and cities the same way on the Atlas page and in the stats API

Mauricec5e2afc21b93
diff --git a/server/scripts/size-baseline.json b/server/scripts/size-baseline.json
index 12c527e90..4edfa2ef0 100644
--- a/server/scripts/size-baseline.json
+++ b/server/scripts/size-baseline.json
@@ -1,11 +1,11 @@
{
"scripts/db-call-graph.mjs": 1036,
"scripts/generate-entities.ts": 2259,
- "src/db/repositories/Places.repository.ts": 1435,
+ "src/db/repositories/Places.repository.ts": 1432,
"src/db/repositories/Reservations.repository.ts": 1550,
"src/db/repositories/Trips.repository.ts": 1120,
"src/db/repositories/Users.repository.ts": 1421,
- "src/nest/atlas/atlas.service.ts": 1174,
+ "src/nest/atlas/atlas.service.ts": 1166,
"src/nest/auth/auth.service.ts": 1141,
"src/nest/budget/budget.service.ts": 1607,
"src/nest/collections/collections.service.ts": 1414,
diff --git a/server/src/db/repositories/Places.repository.ts b/server/src/db/repositories/Places.repository.ts
index 98257e2d8..1ef99d6d5 100644
--- a/server/src/db/repositories/Places.repository.ts
+++ b/server/src/db/repositories/Places.repository.ts
@@ -1108,21 +1108,18 @@ export class PlacesRepository extends TrekRepository<Places> {
}
/**
- * AT41 (`AtlasService#getTravelStats`) — `SELECT DISTINCT p.address,
- * p.lat, p.lng, pr.region_name FROM places p JOIN trips t ON p.trip_id =
- * t.id LEFT JOIN trip_members tm ON t.id = tm.trip_id LEFT JOIN
- * place_regions pr ON pr.place_id = p.id WHERE t.user_id = ? OR tm.user_id
- * = ?`. The resolved region rides along so `cityFromAddress` can tell the
- * city apart from the region sitting right above it in the same address
- * (#1115) — unchanged from the legacy projection.
+ * AT41 (`AtlasService#placeFootprint`): one row per place on a trip the user owns
+ * or is a member of. `p.id` keeps the DISTINCT to undoing the trip_members fan-out,
+ * so places sharing an address and coordinates stay apart (#3137). The resolved
+ * region rides along so `cityFromAddress` can skip it (#1115).
*/
- async listAddressesForUser(user_id: number): Promise<{ address: string | null; lat: number | null; lng: number | null; region_name: string | null }[]> {
+ async listAddressesForUser(user_id: number): Promise<{ id: number; address: string | null; lat: number | null; lng: number | null; region_name: string | null }[]> {
return await this.kysely<PlacesAddressesForUserKyselyDB>()
.selectFrom('places as p')
.innerJoin('trips as t', 't.id', 'p.trip_id')
.leftJoin('trip_members as tm', 'tm.trip_id', 't.id')
.leftJoin('place_regions as pr', 'pr.place_id', 'p.id')
- .select(['p.address', 'p.lat', 'p.lng', 'pr.region_name'])
+ .select(['p.id', 'p.address', 'p.lat', 'p.lng', 'pr.region_name'])
.distinct()
.where((eb) => eb.or([eb('t.user_id', '=', user_id), eb('tm.user_id', '=', user_id)]))
.execute();
diff --git a/server/src/nest/atlas/atlas.service.ts b/server/src/nest/atlas/atlas.service.ts
index 2a3911646..b56f8b56b 100644
--- a/server/src/nest/atlas/atlas.service.ts
+++ b/server/src/nest/atlas/atlas.service.ts
@@ -394,30 +394,10 @@ export class AtlasService {
status: c.status,
}));
- const citySet = new Set<string>();
- for (const place of places) {
- if (place.address) {
- const parts = place.address
- .split(',')
- .map((s: string) => s.trim())
- .filter(Boolean);
- // The last part is the country; the city is usually right before it, but a
- // full formatted address can have a postal code sitting between them
- // (e.g. "Bucharest, 010071, Romania"). Walk back from the country and take
- // the first part that still has letters once digits/postal noise is stripped.
- const candidates = parts.length >= 2 ? parts.slice(0, -1) : parts;
- let city = '';
- for (let i = candidates.length - 1; i >= 0; i--) {
- const cleaned = candidates[i].replace(/[\d\-−〒]+/g, '').trim();
- if (cleaned) {
- city = cleaned.toLowerCase();
- break;
- }
- }
- if (city) citySet.add(city);
- }
- }
- const totalCities = citySet.size;
+ // Places and cities come from the same count as the dashboard card and
+ // GET /api/v1/stats, so the three never show different totals (#3137).
+ const footprint = await this.placeFootprint(userId);
+ const totalCities = footprint.cities.length;
// Countries the user explicitly removed. Only the zero-count passes below are
// suppressed — a country with real places isn't removable in the UI anyway, and once
@@ -570,7 +550,7 @@ export class AtlasService {
countries,
stats: {
totalTrips: trips.length,
- totalPlaces: places.length,
+ totalPlaces: footprint.totalPlaces,
totalCountries: visited.length,
totalCountriesPlanned: planned.length,
totalCountriesIdea: countries.length - visited.length - planned.length,
@@ -1046,29 +1026,41 @@ export class AtlasService {
.map(([code]) => code);
}
+ /**
+ * The places on every trip the user owns or is a member of, archived ones included,
+ * with the cities and coordinates derived from them. The one count behind the Atlas
+ * page, the dashboard card, GET /api/v1/stats and the MCP atlas tool (#3137).
+ *
+ * Every place counts once, even when two share an address and coordinates (the same
+ * hotel saved on two trips). A city is read with cityFromAddress, which skips the
+ * region named in the same address (#1115), and two spellings that differ only in
+ * case are one city; the first spelling seen is the one listed.
+ */
+ private async placeFootprint(
+ userId: number,
+ ): Promise<{ totalPlaces: number; cities: string[]; coords: { lat: number; lng: number }[] }> {
+ const places = await this.places.listAddressesForUser(userId); // AT41
+ const cities = new Map<string, string>();
+ const coords: { lat: number; lng: number }[] = [];
+ for (const p of places) {
+ // Explicit null checks: lat/lng of exactly 0 (equator / prime meridian)
+ // are valid coordinates a falsy check would drop.
+ if (p.lat != null && p.lng != null) coords.push({ lat: p.lat, lng: p.lng });
+ const city = cityFromAddress(p.address, (part) => KNOWN_COUNTRIES.has(part), p.region_name);
+ if (city && !cities.has(city.toLowerCase())) cities.set(city.toLowerCase(), city);
+ }
+ return { totalPlaces: places.length, cities: [...cities.values()], coords };
+ }
+
async getTravelStats(userId: number) {
const today = todayUtc();
-
- // The resolved region rides along so cityFromAddress can tell the city apart from
- // the region sitting right above it in the same address (#1115).
- const places = await this.places.listAddressesForUser(userId); // AT41
+ const { totalPlaces, cities, coords } = await this.placeFootprint(userId);
// Archived trips still count here, matching the places, countries and flight
// distance widgets (which never filtered on is_archived) so the dashboard stats
// stay consistent — archiving a trip no longer zeroes out trips/days.
const tripStats = await this.trips.countTripsAndDaysForUser(userId); // AT42
- const cities = new Set<string>();
- const coords: { lat: number; lng: number }[] = [];
-
- places.forEach(p => {
- // Explicit null checks: lat/lng of exactly 0 (equator / prime meridian)
- // are valid coordinates the former falsy check silently dropped.
- if (p.lat != null && p.lng != null) coords.push({ lat: p.lat, lng: p.lng });
- const cityPart = cityFromAddress(p.address, part => KNOWN_COUNTRIES.has(part), p.region_name);
- if (cityPart) cities.add(cityPart);
- });
-
// Visited countries: the ones the user marked by hand, plus the countries of
// their places, resolved the way the Atlas map resolves them (#2875). Each
// reached country keeps the last day of its latest trip, for the order.
@@ -1111,11 +1103,11 @@ export class AtlasService {
return {
countries: visits.ordered(manualCountries).filter(code => !hidden.has(code)),
- cities: [...cities],
+ cities,
coords,
totalTrips: tripStats.trips || 0,
totalDays: tripStats.days || 0,
- totalPlaces: places.length,
+ totalPlaces,
totalDistanceKm: await this.flightDistanceKm(userId),
};
}
diff --git a/server/src/nest/atlas/city-from-address.ts b/server/src/nest/atlas/city-from-address.ts
index 789231dce..324a3a74d 100644
--- a/server/src/nest/atlas/city-from-address.ts
+++ b/server/src/nest/atlas/city-from-address.ts
@@ -13,6 +13,7 @@
* know the region: `place_regions.region_name` is filled by the geocoder, so it can
* simply be skipped. For the address above, with the region resolved as Tokyo, walking
* back past Japan (country), 150-0002 (digits) and Tokyo (the region) lands on Shibuya.
+ * A city written beside its postcode ("10178 Berlin") counts without the postcode (#3137).
*
* This is still a heuristic over a formatted string. Structured `address.city` from the
* geocoder would be exact, but the fast path for region resolution runs against bundled
@@ -25,6 +26,36 @@ function hasDigits(part: string): boolean {
return /\d/.test(part);
}
+/**
+ * The postcodes geocoders write into the same part as the city: German, French or US
+ * five digits ("10178 Berlin", "NY 10118"), Japanese "150-0002", Dutch "1012 LG", British
+ * "SW1A 2AA" and Canadian "M5V 3L9". A house number ("Unter den Linden 77") or a numbered
+ * district ("Shibuya 2") is none of these and keeps its part out of the running.
+ */
+const POSTCODES = [
+ /\b\d{4}\s?[A-Z]{2}\b/g,
+ /\b[A-Z]{1,2}\d[A-Z\d]?\s?\d[A-Z]{2}\b/g,
+ /\b[A-Z]\d[A-Z]\s?\d[A-Z]\d\b/g,
+ /\b\d{3}-\d{4}\b/g,
+ /\b\d{4,}(?:-\d{4})?\b/g,
+];
+
+/**
+ * The name left in a part once its postcode is taken out, or null when the part holds
+ * no postcode or nothing but one. The short state or province code that stands beside
+ * a postcode ("NY 10118", "Roma RM", "ON M5V 3L9") goes with it.
+ */
+function besidePostcode(part: string): string | null {
+ let rest = part;
+ for (const pattern of POSTCODES) rest = rest.replace(pattern, ' ');
+ if (rest === part) return null;
+ rest = rest
+ .split(/\s+/)
+ .filter((word) => word && !/^[A-Z]{2}$/.test(word))
+ .join(' ');
+ return rest && !hasDigits(rest) && /\p{L}/u.test(rest) ? rest : null;
+}
+
function normalize(value: string): string {
return value.trim().toLowerCase();
}
@@ -53,8 +84,8 @@ export function cityFromAddress(
// Index 0 stays out of the running: geocoders lead with the place itself.
for (let i = last; i >= 1; i--) {
- const part = parts[i];
- if (hasDigits(part)) continue;
+ const part = hasDigits(parts[i]) ? besidePostcode(parts[i]) : parts[i];
+ if (!part) continue;
if (isKnownCountry(part)) continue;
if (region && normalize(part) === region) continue;
// Anything with no letter at all (stray punctuation, a lone dash) is not a name.
diff --git a/server/tests/unit/db/repositories/Places.repository.test.ts b/server/tests/unit/db/repositories/Places.repository.test.ts
index 363e1f964..577e4b806 100644
--- a/server/tests/unit/db/repositories/Places.repository.test.ts
+++ b/server/tests/unit/db/repositories/Places.repository.test.ts
@@ -1402,7 +1402,7 @@ describe('PlacesRepository.listForTripIds (AT2, AtlasService#getPlacesForTrips)'
});
describe('PlacesRepository.listAddressesForUser (AT41, AtlasService#getTravelStats)', () => {
- it('PLACEREPO-061: matches the legacy DISTINCT statement, owner and member trips, region_name joined from place_regions', async () => {
+ it('PLACEREPO-061: one row per place, owner and member trips, region_name joined from place_regions', async () => {
const { user: owner } = createUser(testDb);
const { user: member } = createUser(testDb);
const { user: stranger } = createUser(testDb);
@@ -1416,7 +1416,7 @@ describe('PlacesRepository.listAddressesForUser (AT41, AtlasService#getTravelSta
// test-sql-allow: the legacy statement is the oracle the repository read is held to.
const legacy = testDb.prepare(`
- SELECT DISTINCT p.address, p.lat, p.lng, pr.region_name
+ SELECT DISTINCT p.id, p.address, p.lat, p.lng, pr.region_name
FROM places p JOIN trips t ON p.trip_id = t.id
LEFT JOIN trip_members tm ON t.id = tm.trip_id
LEFT JOIN place_regions pr ON pr.place_id = p.id
@@ -1425,8 +1425,8 @@ describe('PlacesRepository.listAddressesForUser (AT41, AtlasService#getTravelSta
const typedOwner = await places.listAddressesForUser(owner.id);
expect(typedOwner).toEqual(legacy);
expect(typedOwner).toEqual([
- { address: '5 Avenue Anatole France', lat: 48.85, lng: 2.35, region_name: 'Île-de-France' },
- { address: null, lat: null, lng: null, region_name: null },
+ { id: place.id, address: '5 Avenue Anatole France', lat: 48.85, lng: 2.35, region_name: 'Île-de-France' },
+ { id: noAddress.id, address: null, lat: null, lng: null, region_name: null },
]);
const typedMember = await places.listAddressesForUser(member.id);
diff --git a/server/tests/unit/nest/city-from-address.test.ts b/server/tests/unit/nest/city-from-address.test.ts
index f6052d884..c66baba79 100644
--- a/server/tests/unit/nest/city-from-address.test.ts
+++ b/server/tests/unit/nest/city-from-address.test.ts
@@ -61,3 +61,21 @@ describe('cityFromAddress', () => {
expect(city('Place, -, Lyon, France')).toBe('Lyon');
});
});
+
+describe('cityFromAddress with the postcode in the same part as the city (#3137)', () => {
+ it('reads the city beside a postcode, the way a Google-style address writes it', () => {
+ expect(city('Alexanderplatz 1, 10178 Berlin, Germany')).toBe('Berlin');
+ expect(city('Rue de Rivoli 99, 75001 Paris, France')).toBe('Paris');
+ expect(city('Via del Corso 12, 00186 Roma RM, Italy')).toBe('Roma');
+ expect(city('Damrak 1, 1012 LG Amsterdam, Nederland')).toBe('Amsterdam');
+ expect(city('10 Downing St, London SW1A 2AA, United Kingdom')).toBe('London');
+ expect(city('Shibuya Crossing, Shibuya City, Tokyo 150-0002, Japan', 'Tokyo')).toBe('Shibuya City');
+ });
+
+ it('never takes a street with its house number, a numbered district or a state code for a city', () => {
+ expect(city('Hotel Adlon, Unter den Linden 77, Germany')).toBeNull();
+ expect(city('Shibuya Sky, 12, Shibuya 2, Japan')).toBeNull();
+ expect(city('350 5th Ave, New York, NY 10118, USA')).toBe('New York');
+ expect(city('CN Tower, Toronto, ON M5V 3L9, Canada')).toBe('Toronto');
+ });
+});
diff --git a/server/tests/unit/nest/travel-stats.service.test.ts b/server/tests/unit/nest/travel-stats.service.test.ts
index 38678ede6..94524a333 100644
--- a/server/tests/unit/nest/travel-stats.service.test.ts
+++ b/server/tests/unit/nest/travel-stats.service.test.ts
@@ -577,3 +577,88 @@ describe('getTravelStats country order (#2648)', () => {
expect((await atlas.getTravelStats(user.id)).countries).toEqual(['AT', 'FR']);
});
});
+
+/**
+ * The Atlas page, the dashboard card and GET /api/v1/stats showed different place and
+ * city totals for the same user (#3137). The Atlas page counted one place per row and
+ * cut cities with its own address split, while the dashboard collapsed places sharing
+ * an address and coordinates and read cities with cityFromAddress. Both now share one
+ * count, so every surface agrees with the others.
+ */
+describe('Atlas page and passport card count the same places and cities (#3137)', () => {
+ const MUNICH = { lat: 48.1374, lng: 11.5755 };
+ const NUREMBERG = { lat: 49.4521, lng: 11.0767 };
+
+ async function addPlace(
+ tripId: number,
+ name: string,
+ values: { lat?: number | null; lng?: number | null; address?: string | null },
+ ) {
+ return insertRow(await sharedTestOrm(testDb), Places, { trip: tripId, name }, { lat: null, lng: null, ...values });
+ }
+
+ async function cacheRegion(placeId: number, regionName: string) {
+ await upsertRow(await sharedTestOrm(testDb), PlaceRegions, {
+ place: placeId,
+ country_code: 'DE',
+ region_code: 'DE-BY',
+ region_name: regionName,
+ });
+ }
+
+ async function seedFootprint() {
+ const { user } = createUser(testDb);
+ const { user: friend } = createUser(testDb);
+ const first = createTrip(testDb, user.id, { title: 'Bavaria', start_date: '2023-05-01', end_date: '2023-05-10' });
+ const second = createTrip(testDb, friend.id, {
+ title: 'Bavaria again',
+ start_date: '2024-05-01',
+ end_date: '2024-05-03',
+ });
+ // Members on both trips, so a join over trip_members fans every place out.
+ addTripMember(testDb, first.id, friend.id);
+ addTripMember(testDb, second.id, user.id);
+
+ // The same hotel saved on both trips is two places, not one.
+ const hotelA = await addPlace(first.id, 'Hotel', { ...MUNICH, address: 'Hotel Bayern, Munich, Bavaria, Germany' });
+ const hotelB = await addPlace(second.id, 'Hotel', { ...MUNICH, address: 'Hotel Bayern, Munich, Bavaria, Germany' });
+ // Same city in another case: still one city.
+ const square = await addPlace(first.id, 'Square', { ...MUNICH, address: 'Marienplatz, MUNICH, Bavaria, Germany' });
+ // The part before the country is the region, the city sits above it.
+ const castle = await addPlace(first.id, 'Castle', {
+ ...NUREMBERG,
+ address: 'Kaiserburg, Nuremberg, Bavaria, Germany',
+ });
+ const bridge = await addPlace(second.id, 'Bridge', {
+ lat: 49.0222,
+ lng: 12.0972,
+ address: 'Steinerne Bruecke, Regensburg, Bavaria, Germany',
+ });
+ for (const id of [hotelA, hotelB, square, castle, bridge]) await cacheRegion(id, 'Bavaria');
+ // A bare name holds no city, and two places without address or coordinates are two places.
+ await addPlace(first.id, 'Beer garden', { address: 'Augustiner Keller' });
+ await addPlace(second.id, 'Beer hall', { address: 'Hofbraeuhaus' });
+ await addPlace(first.id, 'Idea one', {});
+ await addPlace(second.id, 'Idea two', {});
+ return user;
+ }
+
+ it('AUTH-DB-130: totalPlaces and the city count agree between stats() and getTravelStats()', async () => {
+ const user = await seedFootprint();
+
+ const atlasTotals = (await atlas.stats(user.id)).stats;
+ const travel = await atlas.getTravelStats(user.id);
+
+ expect(atlasTotals.totalPlaces).toBe(travel.totalPlaces);
+ expect(atlasTotals.totalCities).toBe(travel.cities.length);
+ });
+
+ it('AUTH-DB-131: every place row counts once and cities come from cityFromAddress, case-insensitively', async () => {
+ const user = await seedFootprint();
+
+ const travel = await atlas.getTravelStats(user.id);
+ expect(travel.totalPlaces).toBe(9);
+ expect(travel.cities.map((c) => c.toLowerCase()).sort()).toEqual(['munich', 'nuremberg', 'regensburg']);
+ expect((await atlas.stats(user.id)).stats.totalCities).toBe(3);
+ });
+});