website 1.12.1: the With map layouts show the map
- Accounts' profile never has the address's geo, so Service times' and Contact's map layouts never drew a map. church/geocode.ts looks the address up on OpenStreetMap's Nominatim (the street, else the suburb and city) for the public site and the preview, kept in AppSetting church_geocode per address; one not found is retried after a day. - Tests: backend (157, one new, with a stand-in Nominatim). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* The church's place on the map. The "With map" layouts (Service times, Contact) need the address's
|
||||
* `geo`, but Accounts' profile rarely has one (nothing there fills it in), so the map never showed.
|
||||
* When the address has none, it's looked up once on OpenStreetMap's Nominatim (no Google, as the
|
||||
* map itself) and kept in AppSetting `church_geocode` with the address it was for: a new address
|
||||
* is looked up again, one that wasn't found is tried again after a day. Only what visitors are
|
||||
* shown gets it; the admin's copy of the profile is left as Accounts has it.
|
||||
*/
|
||||
import type { Church } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
|
||||
type Address = NonNullable<Church['contact']['address']>;
|
||||
type Geo = NonNullable<Address['geo']>;
|
||||
type Stored = { query: string; geo: Geo | null; at: number };
|
||||
|
||||
const KEY = 'church_geocode';
|
||||
const RETRY_MS = 24 * 3600e3;
|
||||
const TIMEOUT_MS = 4000;
|
||||
const pending = new Map<string, Promise<Geo | null>>();
|
||||
|
||||
const queryOf = (a: Address, full: boolean) =>
|
||||
(full ? [a.line1, a.line2, a.suburb, a.city, a.province, a.postalCode] : [a.suburb, a.city, a.province]).map((s) => s?.trim()).filter(Boolean).join(', ');
|
||||
|
||||
async function lookup(ctx: Ctx, q: string, country: string): Promise<Geo | null> {
|
||||
const url = `https://nominatim.openstreetmap.org/search?format=jsonv2&limit=1&countrycodes=${encodeURIComponent(country.toLowerCase())}&q=${encodeURIComponent(q)}`;
|
||||
const res = ctx.fetch
|
||||
? await ctx.fetch(url)
|
||||
: await fetch(url, { headers: { accept: 'application/json', 'user-agent': 'CrossCode-Website/1.0 (church website map)' }, signal: AbortSignal.timeout(TIMEOUT_MS) });
|
||||
if (!res.ok) throw new Error(`Nominatim answered ${res.status}`);
|
||||
const hits = (await res.json()) as { lat?: string; lon?: string }[];
|
||||
const lat = Number(hits[0]?.lat), lng = Number(hits[0]?.lon);
|
||||
return Number.isFinite(lat) && Number.isFinite(lng) && Math.abs(lat) <= 90 && Math.abs(lng) <= 180 ? { lat, lng } : null;
|
||||
}
|
||||
|
||||
async function geocode(ctx: Ctx, a: Address): Promise<Geo | null> {
|
||||
const query = queryOf(a, true);
|
||||
if (!query) return null;
|
||||
const stored = await ctx.settings.json<Stored | null>(KEY, null);
|
||||
if (stored?.query === query && (stored.geo || ctx.now().getTime() - stored.at < RETRY_MS)) return stored.geo;
|
||||
// Tests never reach the real Nominatim (they give ctx.fetch when they want a lookup).
|
||||
if (!ctx.fetch && process.env.NODE_TEST_CONTEXT) return null;
|
||||
let p = pending.get(query);
|
||||
if (!p) {
|
||||
p = (async () => {
|
||||
try {
|
||||
// The street can be too exact for OpenStreetMap: then the suburb and city.
|
||||
const geo = (await lookup(ctx, query, a.country)) ?? (queryOf(a, false) ? await lookup(ctx, queryOf(a, false), a.country) : null);
|
||||
await ctx.settings.set(KEY, JSON.stringify({ query, geo, at: ctx.now().getTime() } satisfies Stored));
|
||||
return geo;
|
||||
} catch (e) {
|
||||
console.warn('[church] address not found on the map:', (e as Error).message);
|
||||
return stored?.query === query ? stored.geo : null;
|
||||
} finally {
|
||||
pending.delete(query);
|
||||
}
|
||||
})();
|
||||
pending.set(query, p);
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
/** The profile with its address's `geo` filled in when it had none. Never throws. */
|
||||
export async function withGeo(ctx: Ctx, church: Church | null): Promise<Church | null> {
|
||||
const a = church?.contact.address;
|
||||
if (!church || !a || a.geo) return church;
|
||||
const geo = await geocode(ctx, a).catch(() => null);
|
||||
return geo ? { ...church, contact: { ...church.contact, address: { ...a, geo } } } : church;
|
||||
}
|
||||
@@ -7,6 +7,7 @@
|
||||
import { TEMPLATE_FONT_PAIRINGS, type Church, type CrosscodeEvent, type WebsiteTemplate } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { churchProfile } from '../church/profile.js';
|
||||
import { withGeo } from '../church/geocode.js';
|
||||
import { buildPalette, type Palette } from './palette.js';
|
||||
import { buildSnapshot, framed, imageOf, mediaUrl, publishedSnapshot, type Image, type Snapshot } from './snapshot.js';
|
||||
import { headerIsTransparent, TEMPLATE_STYLE, type Variant } from './variants.js';
|
||||
@@ -156,13 +157,13 @@ async function liveEvents(ctx: Ctx): Promise<SiteEvent[]> {
|
||||
|
||||
/** What visitors see: the latest published version, else Coming soon. */
|
||||
export async function siteContent(ctx: Ctx): Promise<SiteContent> {
|
||||
const [church, published] = await Promise.all([churchProfile(ctx), publishedSnapshot(ctx)]);
|
||||
const [church, published] = await Promise.all([churchProfile(ctx).then((c) => withGeo(ctx, c)), publishedSnapshot(ctx)]);
|
||||
return contentFrom(ctx, church, published);
|
||||
}
|
||||
|
||||
/** The preview (§4): the working copy as it would look published, whatever was published before. */
|
||||
export async function previewContent(ctx: Ctx, opts: { asTemplate?: WebsiteTemplate } = {}): Promise<SiteContent> {
|
||||
const [church, snapshot] = await Promise.all([churchProfile(ctx), buildSnapshot(ctx, opts)]);
|
||||
const [church, snapshot] = await Promise.all([churchProfile(ctx).then((c) => withGeo(ctx, c)), buildSnapshot(ctx, opts)]);
|
||||
return contentFrom(ctx, church, { number: 0, publishedAt: ctx.now(), snapshot });
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user