feat(atlas): let a visited region be hidden, cascading to the country when none remain (server)

Countries already have a hide/tombstone mechanism (hidden_countries, #1490):
a zero-count derived country can be dismissed and stays gone across reloads.
Regions had no equivalent — unmarkRegionVisited only ever deleted a
manually-marked visited_regions row, a no-op for the common case of a region
derived fresh from place_regions on every request, so there was no way to
dismiss one at all (place-derived or otherwise).

Adds the region-level counterpart:
- New hidden_regions table (user_id, region_code, country_code), mirroring
  hidden_countries.
- getVisitedRegions() filters its result through it, the same way getStats()
  already filters through getHiddenCountries().
- unmarkRegionVisited() now tombstones unconditionally (not just for a
  manually-marked region — a region with a real place attached, e.g. one
  misassigned by a border-simplification gap, is exactly the case this
  exists for) and derives the country code from the region code's
  "<country>-<rest>" prefix when there's no visited_regions row to read it
  from.
- Cascade: after hiding a region, if the country has no other visible region
  left (checked against place_regions + visited_regions, minus hidden_regions),
  the country is hidden too via the existing unmarkCountryVisited.
- markRegionVisited() clears both tombstones on re-mark, so a region (and its
  cascade-hidden country) can come back.

Note the cascade only has a visible effect on a country with no real place
attached to it — getStats' places-derived country entries are never
suppressed by hidden_countries (#1490's deliberate "reappears with a real
place" rule), so hiding every region of a country that DOES have real places
leaves the country visible, by the same existing design. Test coverage
reflects this.

Server-side only — client wiring (a way to trigger this from the map) is a
separate commit.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Dieter Blomme
2026-07-14 01:46:37 +02:00
committed by Maurice
parent 3bd17ce1f9
commit dea5035fd9
3 changed files with 181 additions and 17 deletions
+22
View File
@@ -3679,6 +3679,28 @@ function runMigrations(db: Database.Database): void {
if (!(err instanceof Error) || !err.message.includes('no such table')) throw err;
}
},
// Tombstones for Atlas regions the user has explicitly removed — the region-level
// counterpart to hidden_countries above (#1490). A visited region is normally derived
// fresh from place_regions/visited_regions on every request, so "removing" it has
// nothing to delete; recording it here lets getVisitedRegions suppress a derived region
// the same way getStats already suppresses a derived country. Unlike the country-level
// tombstone (originally only reachable for a manually-marked or zero-count country),
// this also covers a region derived from real place data — e.g. one that ended up on
// the wrong side of a border-simplification gap and the user just wants gone.
() => {
db.exec(`
CREATE TABLE IF NOT EXISTS hidden_regions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
region_code TEXT NOT NULL,
country_code TEXT NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
UNIQUE (user_id, region_code)
);
`);
db.exec('CREATE INDEX IF NOT EXISTS idx_hidden_regions_user ON hidden_regions (user_id);');
},
];
if (currentVersion < migrations.length) {
+64 -16
View File
@@ -1190,28 +1190,65 @@ export function listManuallyVisitedRegions(
.all(userId) as { region_code: string; region_name: string; country_code: string }[];
}
/** Regions the user explicitly removed, which getVisitedRegions must not re-derive. */
export function getHiddenRegions(userId: number): Set<string> {
const rows = db.prepare('SELECT region_code FROM hidden_regions WHERE user_id = ?').all(userId) as { region_code: string }[];
return new Set(rows.map(r => r.region_code));
}
// Bundled/geocoded region codes are always "<countryCode>-<rest>" (ISO 3166-2 format, and
// buildRegionInfo's synthesized fallback follows the same convention) — used to recover a
// region's country when there's no visited_regions row to read it from (a place-derived
// region was never inserted there).
function countryCodeFromRegionCode(regionCode: string): string {
return (regionCode.split('-')[0] || '').toUpperCase();
}
export function markRegionVisited(userId: number, regionCode: string, regionName: string, countryCode: string): void {
db.prepare(
'INSERT OR IGNORE INTO visited_regions (user_id, region_code, region_name, country_code) VALUES (?, ?, ?, ?)',
).run(userId, regionCode, regionName, countryCode);
// Auto-mark parent country if not already visited
db.prepare('INSERT OR IGNORE INTO visited_regions (user_id, region_code, region_name, country_code) VALUES (?, ?, ?, ?)').run(userId, regionCode, regionName, countryCode);
// Re-marking lifts a previous removal of the region itself...
db.prepare('DELETE FROM hidden_regions WHERE user_id = ? AND region_code = ?').run(userId, regionCode);
// ...and of the parent country, which the "last region removed" cascade in
// unmarkRegionVisited below may have hidden — otherwise marking a region visited again
// would leave its country invisible.
db.prepare('INSERT OR IGNORE INTO visited_countries (user_id, country_code) VALUES (?, ?)').run(userId, countryCode);
db.prepare('DELETE FROM hidden_countries WHERE user_id = ? AND country_code = ?').run(userId, countryCode);
}
// True when the given country still has at least one region that would show as visited —
// derived from place_regions or manually marked — after excluding the given user's hidden
// regions. Used to decide whether removing a region should cascade into hiding the country.
function hasVisibleRegionForCountry(userId: number, countryCode: string, hidden: Set<string>): boolean {
const tripIds = getUserTrips(userId).map(t => t.id);
const placeIds = getPlacesForTrips(tripIds).filter(p => p.lat && p.lng).map(p => p.id);
const placeRegionCodes = placeIds.length > 0
? (db.prepare(
`SELECT DISTINCT region_code FROM place_regions WHERE country_code = ? AND place_id IN (${placeIds.map(() => '?').join(',')})`
).all(countryCode, ...placeIds) as { region_code: string }[]).map(r => r.region_code)
: [];
const manualRegionCodes = (db.prepare(
'SELECT region_code FROM visited_regions WHERE user_id = ? AND country_code = ?'
).all(userId, countryCode) as { region_code: string }[]).map(r => r.region_code);
return [...placeRegionCodes, ...manualRegionCodes].some(code => !hidden.has(code));
}
export function unmarkRegionVisited(userId: number, regionCode: string): void {
const region = db
.prepare('SELECT country_code FROM visited_regions WHERE user_id = ? AND region_code = ?')
.get(userId, regionCode) as { country_code: string } | undefined;
const region = db.prepare('SELECT country_code FROM visited_regions WHERE user_id = ? AND region_code = ?').get(userId, regionCode) as { country_code: string } | undefined;
const countryCode = region?.country_code || countryCodeFromRegionCode(regionCode);
db.prepare('DELETE FROM visited_regions WHERE user_id = ? AND region_code = ?').run(userId, regionCode);
if (region) {
const remaining = db
.prepare('SELECT COUNT(*) as count FROM visited_regions WHERE user_id = ? AND country_code = ?')
.get(userId, region.country_code) as { count: number };
if (remaining.count === 0) {
db.prepare('DELETE FROM visited_countries WHERE user_id = ? AND country_code = ?').run(
userId,
region.country_code,
);
// Tombstone unconditionally, not just for a manually-marked region — a region derived
// from real place data (the common case) needs to be dismissable too, mirroring
// unmarkCountryVisited's tombstone for a place-derived country (#1490).
if (countryCode) {
db.prepare('INSERT OR IGNORE INTO hidden_regions (user_id, region_code, country_code) VALUES (?, ?, ?)').run(userId, regionCode, countryCode);
// If that was the country's last visible region, hide the country too — otherwise it
// keeps showing "visited" on the world map with nothing left to drill into.
const hidden = getHiddenRegions(userId);
if (!hasVisibleRegionForCountry(userId, countryCode, hidden)) {
unmarkCountryVisited(userId, countryCode);
}
}
}
@@ -1480,6 +1517,17 @@ export async function getVisitedRegions(
}
}
// Suppress regions the user explicitly removed, same as getStats does for countries
// via getHiddenCountries (#1490) — otherwise a region derived fresh from place_regions
// (or a manual mark) on every request could never actually be dismissed.
const hidden = getHiddenRegions(userId);
if (hidden.size > 0) {
for (const country of Object.keys(result)) {
result[country] = result[country].filter(r => !hidden.has(r.code));
if (result[country].length === 0) delete result[country];
}
}
return { regions: result };
}
@@ -31,7 +31,7 @@ import { createTables } from '../../../src/db/schema';
import { runMigrations } from '../../../src/db/migrations';
import { resetTestDb } from '../../helpers/test-db';
import { createUser, createTrip, createReservation } from '../../helpers/factories';
import { getStats, getCached, setCache, getCountryFromCoords, getCountryFromAddress, isPointInCountryBox, reverseGeocodeCountry, getRegionGeo, getCountryGeo, getCountryPlaces, getVisitedRegions, markCountryVisited, unmarkCountryVisited } from '../../../src/services/atlasService';
import { getStats, getCached, setCache, getCountryFromCoords, getCountryFromAddress, isPointInCountryBox, reverseGeocodeCountry, getRegionGeo, getCountryGeo, getCountryPlaces, getVisitedRegions, markCountryVisited, unmarkCountryVisited, markRegionVisited, unmarkRegionVisited } from '../../../src/services/atlasService';
function insertReservationEndpoint(
db: any,
@@ -944,3 +944,97 @@ describe('getVisitedRegions', () => {
vi.useRealTimers();
});
});
// ── unmarkRegionVisited — tombstones + country cascade ──────────────────────
// Places are region-resolved by a fire-and-forget background task (see reverseGeocodeRegion
// callers); a single getVisitedRegions() call returns before it settles. Populate the cache
// deterministically before asserting against it or calling unmarkRegionVisited (which reads
// place_regions directly, not through this function).
async function primeRegionCache(userId: number): Promise<void> {
await getVisitedRegions(userId);
await new Promise(resolve => setTimeout(resolve, 10));
}
describe('unmarkRegionVisited — tombstones + country cascade', () => {
it('ATLAS-SVC-024: hides a region derived from a real place, not just a manually-marked one', async () => {
// Unlike unmarkCountryVisited (ATLAS-SVC-023), a region hide is NOT lifted just
// because it has a real place — that is exactly the case this feature exists for (a
// real place that resolved to a region the user doesn't want highlighted, e.g. a
// border-simplification misassignment), so it must stay hidden regardless of
// placeCount until explicitly re-marked.
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'SF Trip' });
insertPlaceWithCoords(testDb, trip.id, 'Golden Gate Park', 37.7694, -122.4862);
await primeRegionCache(user.id);
const before = await getVisitedRegions(user.id);
expect(before.regions['US']?.map((r: any) => r.code)).toContain('US-CA');
unmarkRegionVisited(user.id, 'US-CA');
const after = await getVisitedRegions(user.id);
expect(after.regions['US']?.map((r: any) => r.code) ?? []).not.toContain('US-CA');
});
it('ATLAS-SVC-025: re-marking a hidden region brings it back', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'SF Trip' });
insertPlaceWithCoords(testDb, trip.id, 'Golden Gate Park', 37.7694, -122.4862);
await primeRegionCache(user.id);
unmarkRegionVisited(user.id, 'US-CA');
expect((await getVisitedRegions(user.id)).regions['US']?.map((r: any) => r.code) ?? []).not.toContain('US-CA');
markRegionVisited(user.id, 'US-CA', 'California', 'US');
expect((await getVisitedRegions(user.id)).regions['US']?.map((r: any) => r.code)).toContain('US-CA');
});
it('ATLAS-SVC-026: hiding a country\'s only visible region also hides the country', async () => {
// Uses a manually-marked region rather than a real place: getStats' places-derived
// country entries are never suppressed by hidden_countries (#1490 — a country with a
// real place always reappears, see ATLAS-SVC-023), so the cascade can only ever have a
// visible effect on a country with no real place backing it, exactly like
// unmarkCountryVisited's own tombstone tests above use flight-endpoint-derived
// countries rather than real places for the same reason.
const { user } = createUser(testDb);
markRegionVisited(user.id, 'JP-13', 'Tokyo', 'JP'); // also auto-marks JP visited
const beforeStats = await getStats(user.id);
expect(beforeStats.countries.map((c: any) => c.code)).toContain('JP');
unmarkRegionVisited(user.id, 'JP-13');
const afterStats = await getStats(user.id);
expect(afterStats.countries.map((c: any) => c.code)).not.toContain('JP');
});
it('ATLAS-SVC-027: hiding one of a country\'s several regions does NOT cascade-hide the country', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'NY road trip' });
insertPlaceWithCoords(testDb, trip.id, 'Boston hotel', 42.3588336, -71.0578303); // MA
insertPlaceWithCoords(testDb, trip.id, 'Philly hotel', 39.9527237, -75.1635262); // PA
await primeRegionCache(user.id);
unmarkRegionVisited(user.id, 'US-MA');
const stats = await getStats(user.id);
expect(stats.countries.map((c: any) => c.code)).toContain('US');
const regions = (await getVisitedRegions(user.id)).regions['US'].map((r: any) => r.code);
expect(regions).not.toContain('US-MA');
expect(regions).toContain('US-PA');
});
it('ATLAS-SVC-028: re-marking a region whose country was cascade-hidden brings the country back too', async () => {
const { user } = createUser(testDb);
markRegionVisited(user.id, 'JP-13', 'Tokyo', 'JP');
unmarkRegionVisited(user.id, 'JP-13');
expect((await getStats(user.id)).countries.map((c: any) => c.code)).not.toContain('JP');
markRegionVisited(user.id, 'JP-13', 'Tokyo', 'JP');
const stats = await getStats(user.id);
expect(stats.countries.map((c: any) => c.code)).toContain('JP');
});
});