mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-02 17:26:24 +00:00
Use Google Maps feature IDs for place map links
This commit is contained in:
@@ -9,7 +9,7 @@ export function getAssignmentWithPlace(assignmentId: number | bigint) {
|
||||
COALESCE(da.assignment_time, p.place_time) as place_time,
|
||||
COALESCE(da.assignment_end_time, p.end_time) as end_time,
|
||||
p.duration_minutes, p.notes as place_notes,
|
||||
p.image_url, p.transport_mode, p.google_place_id, p.website, p.phone,
|
||||
p.image_url, p.transport_mode, p.google_place_id, p.google_ftid, p.website, p.phone,
|
||||
c.name as category_name, c.color as category_color, c.icon as category_icon
|
||||
FROM day_assignments da
|
||||
JOIN places p ON da.place_id = p.id
|
||||
@@ -59,6 +59,7 @@ export function getAssignmentWithPlace(assignmentId: number | bigint) {
|
||||
image_url: a.image_url,
|
||||
transport_mode: a.transport_mode,
|
||||
google_place_id: a.google_place_id,
|
||||
google_ftid: a.google_ftid,
|
||||
website: a.website,
|
||||
phone: a.phone,
|
||||
category: a.category_id ? {
|
||||
@@ -79,7 +80,7 @@ export function listDayAssignments(dayId: string | number) {
|
||||
COALESCE(da.assignment_time, p.place_time) as place_time,
|
||||
COALESCE(da.assignment_end_time, p.end_time) as end_time,
|
||||
p.duration_minutes, p.notes as place_notes,
|
||||
p.image_url, p.transport_mode, p.google_place_id, p.website, p.phone,
|
||||
p.image_url, p.transport_mode, p.google_place_id, p.google_ftid, p.website, p.phone,
|
||||
c.name as category_name, c.color as category_color, c.icon as category_icon
|
||||
FROM day_assignments da
|
||||
JOIN places p ON da.place_id = p.id
|
||||
|
||||
@@ -15,7 +15,7 @@ export function getAssignmentsForDay(dayId: number | string) {
|
||||
COALESCE(da.assignment_time, p.place_time) as place_time,
|
||||
COALESCE(da.assignment_end_time, p.end_time) as end_time,
|
||||
p.duration_minutes, p.notes as place_notes,
|
||||
p.image_url, p.transport_mode, p.google_place_id, p.website, p.phone,
|
||||
p.image_url, p.transport_mode, p.google_place_id, p.google_ftid, p.website, p.phone,
|
||||
c.name as category_name, c.color as category_color, c.icon as category_icon
|
||||
FROM day_assignments da
|
||||
JOIN places p ON da.place_id = p.id
|
||||
@@ -54,6 +54,7 @@ export function getAssignmentsForDay(dayId: number | string) {
|
||||
image_url: a.image_url,
|
||||
transport_mode: a.transport_mode,
|
||||
google_place_id: a.google_place_id,
|
||||
google_ftid: a.google_ftid,
|
||||
website: a.website,
|
||||
phone: a.phone,
|
||||
category: a.category_id ? {
|
||||
@@ -88,7 +89,7 @@ export function listDays(tripId: string | number) {
|
||||
COALESCE(da.assignment_time, p.place_time) as place_time,
|
||||
COALESCE(da.assignment_end_time, p.end_time) as end_time,
|
||||
p.duration_minutes, p.notes as place_notes,
|
||||
p.image_url, p.transport_mode, p.google_place_id, p.website, p.phone,
|
||||
p.image_url, p.transport_mode, p.google_place_id, p.google_ftid, p.website, p.phone,
|
||||
c.name as category_name, c.color as category_color, c.icon as category_icon
|
||||
FROM day_assignments da
|
||||
JOIN places p ON da.place_id = p.id
|
||||
|
||||
@@ -45,6 +45,7 @@ interface GooglePlaceResult {
|
||||
websiteUri?: string;
|
||||
nationalPhoneNumber?: string;
|
||||
types?: string[];
|
||||
googleMapsUri?: string;
|
||||
}
|
||||
|
||||
interface GoogleAutocompleteSuggestion {
|
||||
@@ -60,7 +61,6 @@ interface GoogleAutocompleteSuggestion {
|
||||
interface GooglePlaceDetails extends GooglePlaceResult {
|
||||
userRatingCount?: number;
|
||||
regularOpeningHours?: { weekdayDescriptions?: string[]; openNow?: boolean };
|
||||
googleMapsUri?: string;
|
||||
editorialSummary?: { text: string };
|
||||
reviews?: { authorAttribution?: { displayName?: string; photoUri?: string }; rating?: number; text?: { text?: string }; relativePublishTimeDescription?: string }[];
|
||||
photos?: { name: string; authorAttributions?: { displayName?: string }[] }[];
|
||||
@@ -88,6 +88,18 @@ function toApiLang(lang: string | undefined, fallback = 'en'): string {
|
||||
return API_LANG_OVERRIDES[code] ?? code;
|
||||
}
|
||||
|
||||
const GOOGLE_FTID_RE = /^0x[0-9a-f]+:0x[0-9a-f]+$/i;
|
||||
|
||||
export function googleFtidFromMapsUrl(url?: string | null): string | null {
|
||||
if (!url) return null;
|
||||
try {
|
||||
const ftid = new URL(url).searchParams.get('ftid')?.trim();
|
||||
return ftid && GOOGLE_FTID_RE.test(ftid) ? ftid.toLowerCase() : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Photo cache (disk-backed) ────────────────────────────────────────────────
|
||||
import * as placePhotoCache from './placePhotoCache';
|
||||
|
||||
@@ -145,6 +157,7 @@ export async function searchNominatim(query: string, lang?: string) {
|
||||
const data = await response.json() as NominatimResult[];
|
||||
return data.map(item => ({
|
||||
google_place_id: null,
|
||||
google_ftid: null,
|
||||
osm_id: `${item.osm_type}:${item.osm_id}`,
|
||||
name: item.name || item.display_name?.split(',')[0] || '',
|
||||
address: item.display_name || '',
|
||||
@@ -573,7 +586,7 @@ export async function searchPlaces(userId: number, query: string, lang?: string,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Goog-Api-Key': apiKey,
|
||||
'X-Goog-FieldMask': 'places.id,places.displayName,places.formattedAddress,places.location,places.rating,places.websiteUri,places.nationalPhoneNumber,places.types',
|
||||
'X-Goog-FieldMask': 'places.id,places.displayName,places.formattedAddress,places.location,places.rating,places.websiteUri,places.nationalPhoneNumber,places.types,places.googleMapsUri',
|
||||
},
|
||||
body: JSON.stringify(searchBody),
|
||||
});
|
||||
@@ -588,6 +601,7 @@ export async function searchPlaces(userId: number, query: string, lang?: string,
|
||||
|
||||
const places = (data.places || []).map((p: GooglePlaceResult) => ({
|
||||
google_place_id: p.id,
|
||||
google_ftid: googleFtidFromMapsUrl(p.googleMapsUri),
|
||||
name: p.displayName?.text || '',
|
||||
address: p.formattedAddress || '',
|
||||
lat: p.location?.latitude || null,
|
||||
@@ -740,6 +754,7 @@ export async function getPlaceDetails(userId: number, placeId: string, lang?: st
|
||||
|
||||
const place = {
|
||||
google_place_id: data.id,
|
||||
google_ftid: googleFtidFromMapsUrl(data.googleMapsUri),
|
||||
name: data.displayName?.text || '',
|
||||
address: data.formattedAddress || '',
|
||||
lat: data.location?.latitude || null,
|
||||
@@ -799,6 +814,7 @@ export async function getPlaceDetailsExpanded(userId: number, placeId: string, l
|
||||
|
||||
const place = {
|
||||
google_place_id: data.id,
|
||||
google_ftid: googleFtidFromMapsUrl(data.googleMapsUri),
|
||||
name: data.displayName?.text || '',
|
||||
address: data.formattedAddress || '',
|
||||
lat: data.location?.latitude || null,
|
||||
@@ -983,7 +999,7 @@ export async function reverseGeocode(lat: string, lng: string, lang?: string): P
|
||||
|
||||
// ── Resolve Google Maps URL ──────────────────────────────────────────────────
|
||||
|
||||
export async function resolveGoogleMapsUrl(url: string): Promise<{ lat: number; lng: number; name: string | null; address: string | null }> {
|
||||
export async function resolveGoogleMapsUrl(url: string): Promise<{ lat: number; lng: number; name: string | null; address: string | null; google_ftid: string | null }> {
|
||||
let resolvedUrl = url;
|
||||
|
||||
// Extract coordinates from a string (URL or page body). Google Maps encodes
|
||||
@@ -1064,5 +1080,5 @@ export async function resolveGoogleMapsUrl(url: string): Promise<{ lat: number;
|
||||
const name = placeName || nominatim.name || nominatim.address?.tourism || nominatim.address?.building || null;
|
||||
const address = nominatim.display_name || null;
|
||||
|
||||
return { lat, lng, name, address };
|
||||
return { lat, lng, name, address, google_ftid: googleFtidFromMapsUrl(resolvedUrl) };
|
||||
}
|
||||
|
||||
@@ -10,8 +10,8 @@ import { getMapsKey, searchPlaces, getPlacePhoto } from './mapsService';
|
||||
* open/closed). When the importer opts in and a Google Maps key is configured,
|
||||
* we re-resolve each place by name — biased to and validated against the
|
||||
* imported coordinates — to a real Google place, then fill in the empty fields
|
||||
* and persist the resolved `google_place_id` (which is what powers on-demand
|
||||
* opening hours / the proper Maps link going forward).
|
||||
* and persist the resolved `google_place_id` plus `google_ftid` (which power
|
||||
* on-demand opening hours and proper Maps links going forward).
|
||||
*
|
||||
* This runs detached from the import request (fire-and-forget) so a long list
|
||||
* never blocks the response, and pushes each enriched row over the websocket so
|
||||
@@ -26,6 +26,7 @@ export interface EnrichablePlace {
|
||||
lat: number;
|
||||
lng: number;
|
||||
google_place_id?: string | null;
|
||||
google_ftid?: string | null;
|
||||
address?: string | null;
|
||||
website?: string | null;
|
||||
phone?: string | null;
|
||||
@@ -105,18 +106,20 @@ async function enrichOne(tripId: string, userId: number, place: EnrichablePlace,
|
||||
|
||||
const gpid = str(match.google_place_id);
|
||||
if (!gpid) return;
|
||||
const gftid = str(match.google_ftid);
|
||||
|
||||
// COALESCE so enrichment only fills empty columns — never overwrites data the
|
||||
// import already captured (e.g. Naver's address) or anything the user edited.
|
||||
db.prepare(
|
||||
`UPDATE places
|
||||
SET google_place_id = COALESCE(google_place_id, ?),
|
||||
address = COALESCE(address, ?),
|
||||
website = COALESCE(website, ?),
|
||||
phone = COALESCE(phone, ?),
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
SET google_place_id = COALESCE(google_place_id, ?),
|
||||
google_ftid = COALESCE(google_ftid, ?),
|
||||
address = COALESCE(address, ?),
|
||||
website = COALESCE(website, ?),
|
||||
phone = COALESCE(phone, ?),
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = ? AND trip_id = ?`,
|
||||
).run(gpid, str(match.address), str(match.website), str(match.phone), place.id, tripId);
|
||||
).run(gpid, gftid, str(match.address), str(match.website), str(match.phone), place.id, tripId);
|
||||
|
||||
// Photo is best-effort: Google often has none, and getPlacePhoto throws 404 in
|
||||
// that case — a missing photo must never abort the rest of the enrichment.
|
||||
|
||||
@@ -123,27 +123,27 @@ export function createPlace(
|
||||
category_id?: number; price?: number; currency?: string;
|
||||
place_time?: string; end_time?: string;
|
||||
duration_minutes?: number; notes?: string; image_url?: string;
|
||||
google_place_id?: string; osm_id?: string; website?: string; phone?: string;
|
||||
google_place_id?: string; google_ftid?: string; osm_id?: string; website?: string; phone?: string;
|
||||
transport_mode?: string; tags?: number[];
|
||||
},
|
||||
) {
|
||||
const {
|
||||
name, description, lat, lng, address, category_id, price, currency,
|
||||
place_time, end_time,
|
||||
duration_minutes, notes, image_url, google_place_id, osm_id, website, phone,
|
||||
duration_minutes, notes, image_url, google_place_id, google_ftid, osm_id, website, phone,
|
||||
transport_mode, tags = [],
|
||||
} = body;
|
||||
|
||||
const result = db.prepare(`
|
||||
INSERT INTO places (trip_id, name, description, lat, lng, address, category_id, price, currency,
|
||||
place_time, end_time,
|
||||
duration_minutes, notes, image_url, google_place_id, osm_id, website, phone, transport_mode)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
duration_minutes, notes, image_url, google_place_id, google_ftid, osm_id, website, phone, transport_mode)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`).run(
|
||||
tripId, name, description || null, lat || null, lng || null, address || null,
|
||||
category_id || null, price || null, currency || null,
|
||||
place_time || null, end_time || null, duration_minutes || 60, notes || null, image_url || null,
|
||||
google_place_id || null, osm_id || null, website || null, phone || null, transport_mode || 'walking',
|
||||
google_place_id || null, google_ftid || null, osm_id || null, website || null, phone || null, transport_mode || 'walking',
|
||||
);
|
||||
|
||||
const placeId = result.lastInsertRowid;
|
||||
@@ -180,7 +180,7 @@ export function updatePlace(
|
||||
category_id?: number; price?: number; currency?: string;
|
||||
place_time?: string; end_time?: string;
|
||||
duration_minutes?: number; notes?: string; image_url?: string;
|
||||
google_place_id?: string; osm_id?: string; website?: string; phone?: string;
|
||||
google_place_id?: string; google_ftid?: string; osm_id?: string; website?: string; phone?: string;
|
||||
transport_mode?: string; tags?: number[];
|
||||
},
|
||||
) {
|
||||
@@ -190,7 +190,7 @@ export function updatePlace(
|
||||
const {
|
||||
name, description, lat, lng, address, category_id, price, currency,
|
||||
place_time, end_time,
|
||||
duration_minutes, notes, image_url, google_place_id, osm_id, website, phone,
|
||||
duration_minutes, notes, image_url, google_place_id, google_ftid, osm_id, website, phone,
|
||||
transport_mode, tags,
|
||||
} = body;
|
||||
|
||||
@@ -210,6 +210,7 @@ export function updatePlace(
|
||||
notes = ?,
|
||||
image_url = ?,
|
||||
google_place_id = ?,
|
||||
google_ftid = ?,
|
||||
osm_id = ?,
|
||||
website = ?,
|
||||
phone = ?,
|
||||
@@ -231,6 +232,7 @@ export function updatePlace(
|
||||
notes !== undefined ? notes : existingPlace.notes,
|
||||
image_url !== undefined ? image_url : existingPlace.image_url,
|
||||
google_place_id !== undefined ? google_place_id : existingPlace.google_place_id,
|
||||
google_ftid !== undefined ? google_ftid : existingPlace.google_ftid,
|
||||
osm_id !== undefined ? osm_id : existingPlace.osm_id,
|
||||
website !== undefined ? website : existingPlace.website,
|
||||
phone !== undefined ? phone : existingPlace.phone,
|
||||
@@ -625,6 +627,65 @@ export async function importMapFile(tripId: string, fileBuffer: Buffer, filename
|
||||
// Import Google Maps list
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function googleMapsHexId(value: unknown): string | null {
|
||||
if (typeof value !== 'string' && typeof value !== 'number') return null;
|
||||
const raw = String(value).trim();
|
||||
if (/^0x[0-9a-f]+$/i.test(raw)) return raw.toLowerCase();
|
||||
if (!/^-?\d+$/.test(raw)) return null;
|
||||
try {
|
||||
const parsed = BigInt(raw);
|
||||
const unsigned = parsed < 0n ? (1n << 64n) + parsed : parsed;
|
||||
return `0x${unsigned.toString(16)}`;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function googleMapsFeatureIdFromItem(item: unknown): string | null {
|
||||
if (!Array.isArray(item)) return null;
|
||||
const candidates = [
|
||||
Array.isArray(item[1]) ? item[1][6] : null,
|
||||
Array.isArray(item[7]) ? item[7][1] : null,
|
||||
];
|
||||
|
||||
for (const ids of candidates) {
|
||||
if (!Array.isArray(ids) || ids.length < 2) continue;
|
||||
const first = googleMapsHexId(ids[0]);
|
||||
const second = googleMapsHexId(ids[1]);
|
||||
if (first && second) return `${first}:${second}`;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function findDuplicatePlace(
|
||||
tripId: string,
|
||||
place: { name: string | null | undefined; lat: number | null; lng: number | null },
|
||||
): { id: number; google_ftid: string | null } | null {
|
||||
const normalizedName = place.name?.trim().toLowerCase();
|
||||
if (normalizedName) {
|
||||
const duplicate = db.prepare(`
|
||||
SELECT id, google_ftid FROM places
|
||||
WHERE trip_id = ? AND lower(trim(name)) = ?
|
||||
ORDER BY id ASC
|
||||
LIMIT 1
|
||||
`).get(tripId, normalizedName) as { id: number; google_ftid: string | null } | undefined;
|
||||
if (duplicate) return duplicate;
|
||||
}
|
||||
if (place.lat != null && place.lng != null) {
|
||||
return db.prepare(`
|
||||
SELECT id, google_ftid FROM places
|
||||
WHERE trip_id = ?
|
||||
AND lat IS NOT NULL AND lng IS NOT NULL
|
||||
AND abs(lat - ?) <= ?
|
||||
AND abs(lng - ?) <= ?
|
||||
ORDER BY id ASC
|
||||
LIMIT 1
|
||||
`).get(tripId, place.lat, COORD_DEDUP_TOLERANCE, place.lng, COORD_DEDUP_TOLERANCE) as { id: number; google_ftid: string | null } | undefined || null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function importGoogleList(tripId: string, url: string, opts?: ListImportOptions) {
|
||||
let listId: string | null = null;
|
||||
let resolvedUrl = url;
|
||||
@@ -689,7 +750,7 @@ export async function importGoogleList(tripId: string, url: string, opts?: ListI
|
||||
}
|
||||
|
||||
// Parse place data from items
|
||||
const places: { name: string; lat: number; lng: number; notes: string | null }[] = [];
|
||||
const places: { name: string; lat: number; lng: number; notes: string | null; googleFtid: string | null }[] = [];
|
||||
for (const item of items) {
|
||||
const coords = item?.[1]?.[5];
|
||||
const lat = coords?.[2];
|
||||
@@ -698,7 +759,7 @@ export async function importGoogleList(tripId: string, url: string, opts?: ListI
|
||||
const note = item?.[3] || null;
|
||||
|
||||
if (name && typeof lat === 'number' && typeof lng === 'number' && !isNaN(lat) && !isNaN(lng)) {
|
||||
places.push({ name, lat, lng, notes: note || null });
|
||||
places.push({ name, lat, lng, notes: note || null, googleFtid: googleMapsFeatureIdFromItem(item) });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -708,18 +769,23 @@ export async function importGoogleList(tripId: string, url: string, opts?: ListI
|
||||
|
||||
const dedup = buildDedupSet(tripId);
|
||||
const insertStmt = db.prepare(`
|
||||
INSERT INTO places (trip_id, name, lat, lng, notes, transport_mode)
|
||||
VALUES (?, ?, ?, ?, ?, 'walking')
|
||||
INSERT INTO places (trip_id, name, lat, lng, notes, google_ftid, transport_mode)
|
||||
VALUES (?, ?, ?, ?, ?, ?, 'walking')
|
||||
`);
|
||||
const updateGoogleFtidStmt = db.prepare('UPDATE places SET google_ftid = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?');
|
||||
const created: any[] = [];
|
||||
let skipped = 0;
|
||||
const insertAll = db.transaction(() => {
|
||||
for (const p of places) {
|
||||
if (isPlaceDuplicate({ name: p.name, lat: p.lat, lng: p.lng }, dedup)) {
|
||||
const duplicate = findDuplicatePlace(tripId, p);
|
||||
if (duplicate && !duplicate.google_ftid && p.googleFtid) {
|
||||
updateGoogleFtidStmt.run(p.googleFtid, duplicate.id);
|
||||
}
|
||||
skipped++;
|
||||
continue;
|
||||
}
|
||||
const result = insertStmt.run(tripId, p.name, p.lat, p.lng, p.notes);
|
||||
const result = insertStmt.run(tripId, p.name, p.lat, p.lng, p.notes, p.googleFtid);
|
||||
const place = getPlaceWithTags(Number(result.lastInsertRowid));
|
||||
created.push(place);
|
||||
trackInsertedInDedupSet({ name: p.name, lat: p.lat, lng: p.lng }, dedup);
|
||||
|
||||
@@ -80,6 +80,7 @@ function formatAssignmentWithPlace(a: AssignmentRow, tags: Partial<Tag>[], parti
|
||||
image_url: a.image_url,
|
||||
transport_mode: a.transport_mode,
|
||||
google_place_id: a.google_place_id,
|
||||
google_ftid: a.google_ftid,
|
||||
website: a.website,
|
||||
phone: a.phone,
|
||||
category: a.category_id ? {
|
||||
|
||||
@@ -632,14 +632,14 @@ export function copyTripById(sourceTripId: string | number, newOwnerId: number,
|
||||
const insertPlace = db.prepare(`
|
||||
INSERT INTO places (trip_id, name, description, lat, lng, address, category_id, price, currency,
|
||||
reservation_status, reservation_notes, reservation_datetime, place_time, end_time,
|
||||
duration_minutes, notes, image_url, google_place_id, website, phone, transport_mode, osm_id)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
duration_minutes, notes, image_url, google_place_id, google_ftid, website, phone, transport_mode, osm_id)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`);
|
||||
for (const p of oldPlaces) {
|
||||
const r = insertPlace.run(newTripId, p.name, p.description, p.lat, p.lng, p.address, p.category_id,
|
||||
p.price, p.currency, p.reservation_status, p.reservation_notes, p.reservation_datetime,
|
||||
p.place_time, p.end_time, p.duration_minutes, p.notes, p.image_url, p.google_place_id,
|
||||
p.website, p.phone, p.transport_mode, p.osm_id);
|
||||
p.google_ftid, p.website, p.phone, p.transport_mode, p.osm_id);
|
||||
placeMap.set(p.id, r.lastInsertRowid);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user