diff --git a/data/CONTRIBUTING.md b/data/CONTRIBUTING.md index 11cd0b7..d2fc35e 100644 --- a/data/CONTRIBUTING.md +++ b/data/CONTRIBUTING.md @@ -42,6 +42,7 @@ below is also machine-enforced by [`places.schema.json`](places.schema.json), wh - `type`: must match the filename exactly - `lat`/`lng`: from Google Maps (right-click pin, "What's here?"). Any real-world coordinate works: `places.schema.json` checks latitude is between -90 and 90 and longitude between -180 and 180. - `address`: optional, short, human-readable +- `website`, `phone` and `hours`: all optional, so a record without them stays valid. `website` is the place's own `https://` page. `phone` is international format with no spaces or punctuation, like `+442074127000` (drop the national `0` in `+44 (0)20...`). `hours` is short free text of at most 120 characters, like `Mon-Fri 09:00-17:00`. They must come from the place's own website or listing, not a third-party directory, and you note where and when you checked them in the PR (see [Verification](#verification)). - `exam` and `valid_till` (exam centres only): `exam` is one label per exam, so the same exam is never spelled two ways. Use `IELTS`, `TOEFL`, `Goethe-Zertifikat (A1-C2)`, `DELF/DALF` (`TEF/TCF/DELF/DALF` for a centre that also takes the TEF and TCF), `DELF`, `DELE`, `TOMER Turkish Proficiency Certificate` or `SAT`, and add a new label here when you add a new exam. `valid_till` is the date to reconfirm the centre by: 6 months after you last checked it (the PR date for a new record). - `gmaps_link`: Google Maps share link (Share -> Copy link) - Do not add rating, review count, or verified date to the JSON. Those go in the PR. @@ -71,6 +72,21 @@ re-checked the place: - `npm run validate` fails on a malformed `verified` block (missing or empty `by`, a non-date or impossible `on`, or extra keys). +### Phone, website and opening hours + +Opening hours and phone numbers go stale faster than a pin. When a PR adds or +changes `website`, `phone` or `hours`: + +- take each one from the place's **own** website or listing, never from a + directory or a map app's aggregated "popular times"; +- put the page you read it from and the date you checked it in the PR + description (it stays in the PR, not in the JSON, like the other proof); +- leave a field out rather than guess: all three are optional; +- when you re-verify a place (above), re-check these three as well. + +`npm run validate` checks the format only (`https://` URL, `+` and digits for +the phone, short single-line hours). It cannot tell you the value is right. + ## Quality gate (must pass before merge) Include in your pull request description: diff --git a/data/places.schema.json b/data/places.schema.json index ccb12ad..cc44278 100644 --- a/data/places.schema.json +++ b/data/places.schema.json @@ -46,6 +46,23 @@ "type": "string", "description": "Optional, short, human-readable" }, + "website": { + "type": "string", + "pattern": "^https://[^\\s]+$", + "maxLength": 300, + "description": "Optional. The place's own https:// website or listing page. Must come from the place itself, not a third-party directory." + }, + "phone": { + "type": "string", + "pattern": "^\\+[1-9][0-9]{6,14}$", + "description": "Optional. International format with no spaces, e.g. \"+442074127000\" (E.164). Must come from the place's own site or listing." + }, + "hours": { + "type": "string", + "minLength": 1, + "maxLength": 120, + "description": "Optional. Short free text for now, e.g. \"Mon-Fri 09:00-17:00\". Must come from the place's own site or listing." + }, "gmaps_link": { "type": "string", "pattern": "^https://(maps\\.google\\.com(\\?|/)|maps\\.app\\.goo\\.gl/|www\\.google\\.com/maps/|goo\\.gl/maps/)" diff --git a/data/places/library.json b/data/places/library.json index 46fcda3..9edc378 100644 --- a/data/places/library.json +++ b/data/places/library.json @@ -488,6 +488,8 @@ "lat": 51.5299119, "lng": -0.1276918, "address": "96 Euston Road, London NW1 2DB", + "website": "https://www.bl.uk/visit", + "hours": "Mon-Thu 09:30-20:00, Fri 09:30-18:00, Sat 09:30-17:00, Sun 11:00-17:00", "gmaps_link": "https://maps.google.com/?q=51.5299119,-0.1276918", "added_by": "yakew7", "verified": { @@ -996,6 +998,8 @@ "lat": -35.2965236, "lng": 149.1295736, "address": "Parkes Place, Parkes, Canberra ACT 2600, Australia", + "website": "https://www.library.gov.au/visit", + "phone": "+61262621111", "gmaps_link": "https://maps.google.com/?q=-35.2965236,149.1295736", "added_by": "yakew7", "verified": { @@ -1360,6 +1364,9 @@ "lat": -33.8672, "lng": 151.214, "address": "Macquarie St, Sydney NSW 2000, Australia", + "website": "https://www.sl.nsw.gov.au/visit-us/opening-hours", + "phone": "+61292731414", + "hours": "Mon-Thu 09:00-20:00, Fri 09:00-17:00, Sat-Sun 10:00-17:00", "gmaps_link": "https://maps.google.com/?q=-33.8672,151.2140", "added_by": "yakew7" }, @@ -5752,6 +5759,9 @@ "lat": -37.8097696, "lng": 144.9655352, "address": "328 Swanston St, Melbourne VIC 3000, Australia", + "website": "https://www.slv.vic.gov.au/visit", + "phone": "+61386647000", + "hours": "Daily 10:00-18:00", "gmaps_link": "https://maps.google.com/?q=-37.8097696,144.9655352", "added_by": "anaydhawan" }, @@ -5824,6 +5834,9 @@ "lat": 38.888674, "lng": -77.004636, "address": "10 First Street SE, Washington, DC 20540", + "website": "https://www.loc.gov/visit/", + "phone": "+12027079779", + "hours": "Tue-Wed 10:00-17:00, Thu 10:00-20:00, Fri-Sat 10:00-17:00, closed Sun-Mon", "gmaps_link": "https://maps.google.com/?q=38.888674,-77.004636", "added_by": "propcgamer20-png", "verified": { @@ -5840,6 +5853,8 @@ "lat": 53.341125, "lng": -6.2545, "address": "7-8 Kildare Street, Dublin D02 P638", + "website": "https://www.nli.ie/contact", + "phone": "+35316030200", "gmaps_link": "https://maps.google.com/?q=53.341125,-6.2545", "added_by": "propcgamer20-png", "verified": { diff --git a/scripts/lib/data-validation.mjs b/scripts/lib/data-validation.mjs index c064524..578f0ea 100644 --- a/scripts/lib/data-validation.mjs +++ b/scripts/lib/data-validation.mjs @@ -90,6 +90,24 @@ export function isHttpUrl(value) { } } +/** + * True when `value` is an international phone number in E.164 form: "+", a non-zero + * country digit, then 6 to 14 more digits, with no spaces or punctuation (#356). + */ +export function isE164Phone(value) { + return typeof value === "string" && /^\+[1-9][0-9]{6,14}$/.test(value); +} + +/** True when `value` is a short, non-blank, single-line opening-hours text (#356). */ +export function isOpeningHours(value) { + return ( + typeof value === "string" && + value.trim().length > 0 && + value.length <= 120 && + !/[\r\n]/.test(value) + ); +} + /** True when `value` is a string containing an em dash. House rule, see #193/#194. */ export function hasEmDash(value) { return typeof value === "string" && value.includes("—"); diff --git a/scripts/lib/place-submission.mjs b/scripts/lib/place-submission.mjs index ab45700..8151456 100644 --- a/scripts/lib/place-submission.mjs +++ b/scripts/lib/place-submission.mjs @@ -10,7 +10,7 @@ * and synchronous; network and file access live in the callers. */ -import { normalizePlaceName } from "./data-validation.mjs"; +import { isE164Phone, isHttpsUrl, normalizePlaceName } from "./data-validation.mjs"; export const SUBMISSION_LABEL = "place-submission"; export const SUBMISSION_MARKER = ""; @@ -24,7 +24,7 @@ export const PLACE_TYPES = [ "gov_offices", ]; -const MAX = { name: 120, city: 60, contributor: 60, note: 500 }; +const MAX = { name: 120, city: 60, contributor: 60, note: 500, website: 300, hours: 120 }; // Same host rules as the place schema's gmaps_link pattern, plus the short // links the "Share" button produces (which the processing script resolves). @@ -57,6 +57,18 @@ function clean(value, max) { .slice(0, max); } +/** + * "+44 (20) 7412-7000" and "0044 20 7412 7000" both become "+442074127000". + * Anything that is still not E.164 afterwards is left for the caller to reject. + */ +export function normalizePhone(input) { + // "(0)" is the national trunk digit written after the country code ("+44 (0)20 ..."); it is not dialled from abroad. + const stripped = String(input ?? "") + .replace(/\(0\)/g, "") + .replace(/[\s().-]/g, ""); + return stripped.startsWith("00") ? `+${stripped.slice(2)}` : stripped; +} + /** * Validates and normalises a raw submission. Returns * { ok: true, value } or { ok: false, error }. @@ -78,6 +90,34 @@ export function normalizeSubmission(raw) { return { ok: false, error: "Enter a valid Google Maps link." }; } + // Optional contact details (#356). Blank means "not given"; a value that is + // given but malformed is rejected, so a typo never silently disappears. + // The form sends the real field as `placeWebsite`: `website` on the request is the + // hidden honeypot, which the route drops when filled, so the two must not share a + // key. A stored submission (read back from an issue) uses the normalised `website`. + const websiteInput = [raw.placeWebsite, raw.website].find( + (value) => typeof value === "string" && value.trim() !== "", + ); + const website = typeof websiteInput === "string" ? websiteInput.trim() : ""; + if ( + website && + (website.length > MAX.website || !isHttpsUrl(website) || /\s/.test(website)) + ) { + return { + ok: false, + error: "Enter the website as an https:// link, or leave it blank.", + }; + } + const phone = normalizePhone(typeof raw.phone === "string" ? raw.phone : ""); + if (phone && !isE164Phone(phone)) { + return { + ok: false, + error: + "Enter the phone with its country code, like +442074127000, or leave it blank.", + }; + } + const hours = clean(raw.hours, MAX.hours); + return { ok: true, value: { @@ -85,6 +125,9 @@ export function normalizeSubmission(raw) { type, city, gmapsLink, + ...(website ? { website } : {}), + ...(phone ? { phone } : {}), + ...(hours ? { hours } : {}), contributor: clean(raw.contributor, MAX.contributor), note: clean(raw.note, MAX.note), }, @@ -99,6 +142,9 @@ export function buildIssueBody(sub) { `**Type:** ${sub.type}`, `**City:** ${sub.city}`, `**Google Maps link:** ${sub.gmapsLink}`, + ...(sub.website ? [`**Website:** ${sub.website}`] : []), + ...(sub.phone ? [`**Phone:** ${sub.phone}`] : []), + ...(sub.hours ? [`**Hours:** ${sub.hours}`] : []), `**Contributor:** ${sub.contributor || "(anonymous)"}`, ...(sub.note ? [`**Note:** ${sub.note}`] : []), "", @@ -211,6 +257,9 @@ export function buildPlaceRecord({ sub, coords, country, id }) { country, lat: coords.lat, lng: coords.lng, + ...(sub.website ? { website: sub.website } : {}), + ...(sub.phone ? { phone: sub.phone } : {}), + ...(sub.hours ? { hours: sub.hours } : {}), gmaps_link: `https://maps.google.com/?q=${coords.lat},${coords.lng}`, added_by: addedByFor(sub.contributor), }; diff --git a/scripts/process-place-submission.mjs b/scripts/process-place-submission.mjs index bb093f4..b940385 100644 --- a/scripts/process-place-submission.mjs +++ b/scripts/process-place-submission.mjs @@ -85,7 +85,11 @@ export async function processSubmission({ body, records, resolve = resolveShortL const record = buildPlaceRecord({ sub, coords, country, id }); return { status: "ready", - message: `Added \`${id}\`. Check the pin location and the quality gate (rating 4.0+, 50+ reviews) before merging.`, + message: `Added \`${id}\`. Check the pin location and the quality gate (rating 4.0+, 50+ reviews) before merging.${ + record.website || record.phone || record.hours + ? " The website, phone and hours were typed by the submitter: confirm each against the place's own site or listing, and drop any you cannot." + : "" + }`, record, sub, }; diff --git a/scripts/validate-places.mjs b/scripts/validate-places.mjs index ddff4c4..51b86e7 100644 --- a/scripts/validate-places.mjs +++ b/scripts/validate-places.mjs @@ -17,6 +17,9 @@ * - lat/lng are numbers within the schema's min/max bounds * - gmaps_link matches the schema's pattern * - valid_till is a real ISO date (YYYY-MM-DD), when present + * - website is an https:// URL, phone is E.164 (+ then 7 to 15 digits, no + * spaces) and hours is short single-line text, when present (all three + * are optional, so no existing record needs them) * - No em dashes in any string field * - gmaps_link in the ?q=, form points at the record's own lat/lng * (within 0.01 degrees) @@ -37,7 +40,10 @@ import { gmapsLinkCoordinates, hasEmDash, isCountryCode, + isE164Phone, + isHttpsUrl, isLatLngPlaceholderGmapsLink, + isOpeningHours, isRealIsoDate, } from "./lib/data-validation.mjs"; @@ -198,6 +204,26 @@ for (const file of files) { err(loc, `valid_till must be a real ISO date (YYYY-MM-DD), got "${r.valid_till}"`); } + // Optional contact details (#356): format only, the fields stay optional + if (r.website !== undefined && (!isHttpsUrl(r.website) || r.website.length > 300)) { + err( + loc, + `website must be an https:// URL of at most 300 characters, got ${JSON.stringify(r.website)}`, + ); + } + if (r.phone !== undefined && !isE164Phone(r.phone)) { + err( + loc, + `phone must be in international format with no spaces, like "+442074127000", got ${JSON.stringify(r.phone)}`, + ); + } + if (r.hours !== undefined && !isOpeningHours(r.hours)) { + err( + loc, + `hours must be short single-line text of at most 120 characters, like "Mon-Fri 09:00-17:00", got ${JSON.stringify(r.hours)}`, + ); + } + // lat bounds if (r.lat !== undefined) { if (typeof r.lat !== "number") { diff --git a/src/app/api/submit-place/route.test.ts b/src/app/api/submit-place/route.test.ts index 230d5eb..7f69bd3 100644 --- a/src/app/api/submit-place/route.test.ts +++ b/src/app/api/submit-place/route.test.ts @@ -81,6 +81,32 @@ describe("POST /api/submit-place", () => { expect(createIssue).not.toHaveBeenCalled(); }); + it("files a real website sent as placeWebsite, which is not the honeypot (#356)", async () => { + const res = await post({ + ...good, + placeWebsite: "https://www.bl.uk/", + phone: "+44 20 7412 7000", + hours: "Mon-Fri 09:30-20:00", + website: "", + }); + expect(res.status).toBe(201); + expect(createIssue).toHaveBeenCalledWith( + "test-token", + expect.objectContaining({ + website: "https://www.bl.uk/", + phone: "+442074127000", + hours: "Mon-Fri 09:30-20:00", + }), + ); + }); + + it("rejects a malformed phone with a message instead of dropping it (#356)", async () => { + const res = await post({ ...good, phone: "020 7412 7000" }); + expect(res.status).toBe(400); + expect(await res.json()).toMatchObject({ ok: false, reason: "invalid" }); + expect(createIssue).not.toHaveBeenCalled(); + }); + it("returns 503 unavailable when no token is configured", async () => { delete process.env.PLACE_SUBMISSION_TOKEN; const res = await post(good); diff --git a/src/app/docs/(article)/places-api/page.tsx b/src/app/docs/(article)/places-api/page.tsx index dd86df3..d9a509b 100644 --- a/src/app/docs/(article)/places-api/page.tsx +++ b/src/app/docs/(article)/places-api/page.tsx @@ -29,6 +29,9 @@ const RESPONSE_EXAMPLE = `{ "lat": 18.9674, "lng": 72.8339, "address": "Fort, Mumbai 400001", + "website": "https://example.org/library", + "phone": "+912222660000", + "hours": "Mon-Sat 10:00-18:00", "gmaps_link": "https://maps.google.com/?q=18.9674,72.8339", "added_by": "thunderblitzyt-eng" } diff --git a/src/components/map/place-detail-drawer.tsx b/src/components/map/place-detail-drawer.tsx index 5b9b9bd..7e36fde 100644 --- a/src/components/map/place-detail-drawer.tsx +++ b/src/components/map/place-detail-drawer.tsx @@ -7,6 +7,7 @@ import { humanizeCity, PLACE_TYPE_LABELS } from "@/lib/types"; import { CategoryIcon } from "@/components/map/category-icon"; import { PlacePhotoGallery } from "@/components/map/place-photo-gallery"; import { SharePlaceCard } from "@/components/map/share-place-card"; +import { PlaceContact } from "@/components/pins/place-contact"; import { VerifiedBadge } from "@/components/pins/verified-badge"; import { Button } from "@/components/ui/button"; import { @@ -56,6 +57,8 @@ export function PlaceDetailDrawer({ place, open, onOpenChange }: PlaceDetailDraw )} + + {place.exam && (

Exam centre

diff --git a/src/components/map/suggest-place-dialog.test.tsx b/src/components/map/suggest-place-dialog.test.tsx index 2ed686f..247cdfa 100644 --- a/src/components/map/suggest-place-dialog.test.tsx +++ b/src/components/map/suggest-place-dialog.test.tsx @@ -182,3 +182,99 @@ describe("SuggestPlaceDialog submission", () => { expect(onOpenChange).toHaveBeenCalledWith(false); }); }); + +describe("SuggestPlaceDialog contact details (#356)", () => { + function renderForm() { + render(); + fillRequiredFields("https://maps.google.com/?q=19.0176,72.8562"); + } + + const submitButton = () => + screen.getByRole("button", { name: "Submit place" }) as HTMLButtonElement; + + it("offers optional website, phone and opening hours fields", () => { + renderForm(); + + expect(screen.getByLabelText("Place website (optional)")).toBeTruthy(); + expect(screen.getByLabelText("Phone (optional)")).toBeTruthy(); + expect(screen.getByLabelText("Opening hours (optional)")).toBeTruthy(); + expect(submitButton().disabled).toBe(false); + }); + + it("sends the website as placeWebsite and keeps the honeypot field empty", async () => { + const fetchMock = mockApi(201, { + ok: true, + issueUrl: "https://github.com/o/r/issues/1", + }); + renderForm(); + fireEvent.change(screen.getByLabelText("Place website (optional)"), { + target: { value: "https://www.bl.uk/" }, + }); + fireEvent.change(screen.getByLabelText("Phone (optional)"), { + target: { value: "+44 (0)20 7412 7000" }, + }); + fireEvent.change(screen.getByLabelText("Opening hours (optional)"), { + target: { value: "Mon-Fri 09:30-20:00" }, + }); + fireEvent.click(submitButton()); + await screen.findByText(/in the queue/); + + const body = JSON.parse( + (fetchMock.mock.calls[0] as [string, RequestInit])[1].body as string, + ); + expect(body).toMatchObject({ + placeWebsite: "https://www.bl.uk/", + phone: "+442074127000", + hours: "Mon-Fri 09:30-20:00", + website: "", + }); + }); + + it("blocks a phone number with no country code and says why", () => { + renderForm(); + fireEvent.change(screen.getByLabelText("Phone (optional)"), { + target: { value: "020 7412 7000" }, + }); + + expect(screen.getByRole("alert").textContent).toContain("Include the country code"); + expect(submitButton().disabled).toBe(true); + }); + + it("blocks a website that is not https and says why", () => { + renderForm(); + fireEvent.change(screen.getByLabelText("Place website (optional)"), { + target: { value: "http://www.bl.uk" }, + }); + + expect(screen.getByRole("alert").textContent).toContain("https://"); + expect(submitButton().disabled).toBe(true); + }); + + it("allows the fields to be left blank", () => { + renderForm(); + + expect(screen.queryByRole("alert")).toBeNull(); + expect(submitButton().disabled).toBe(false); + }); + + it("puts the contact details into the GitHub issue fallback", async () => { + mockApi(503, { ok: false, reason: "unavailable" }); + render(); + fillRequiredFields("https://maps.app.goo.gl/abc123"); + fireEvent.change(screen.getByLabelText("Phone (optional)"), { + target: { value: "+442074127000" }, + }); + fireEvent.click(submitButton()); + await screen.findByRole("button", { name: "Open GitHub issue" }); + const replace = vi.fn(); + vi.spyOn(window, "open").mockReturnValue({ + opener: window, + location: { replace }, + } as unknown as Window); + + fireEvent.click(screen.getByRole("button", { name: "Open GitHub issue" })); + + const url = new URL(replace.mock.calls[0]?.[0] as string); + expect(url.searchParams.get("body")).toContain("**Phone:** +442074127000"); + }); +}); diff --git a/src/components/map/suggest-place-dialog.tsx b/src/components/map/suggest-place-dialog.tsx index 53b7a01..065a8da 100644 --- a/src/components/map/suggest-place-dialog.tsx +++ b/src/components/map/suggest-place-dialog.tsx @@ -29,6 +29,8 @@ import { type City, } from "@/lib/types"; import { site } from "@/lib/site"; +import { isE164Phone, isHttpsUrl } from "../../../scripts/lib/data-validation.mjs"; +import { normalizePhone } from "../../../scripts/lib/place-submission.mjs"; interface SuggestPlaceDialogProps { /** Cities already in the public dataset, offered as suggestions. */ @@ -42,6 +44,9 @@ function buildIssueUrl(fields: { type: PlaceType; city: string; gmapsLink: string; + website: string; + phone: string; + hours: string; contributor: string; note: string; }): string { @@ -51,6 +56,9 @@ function buildIssueUrl(fields: { `**Type:** ${PLACE_TYPE_LABELS[fields.type]}`, `**City:** ${fields.city}`, `**Google Maps link:** ${fields.gmapsLink}`, + ...(fields.website ? [`**Website:** ${fields.website}`] : []), + ...(fields.phone ? [`**Phone:** ${fields.phone}`] : []), + ...(fields.hours ? [`**Hours:** ${fields.hours}`] : []), ...(fields.contributor.trim() ? [`**Contributor:** ${fields.contributor.trim()}`] : []), @@ -104,6 +112,9 @@ export function SuggestPlaceDialog({ const [type, setType] = React.useState("library"); const [city, setCity] = React.useState(""); const [gmapsLink, setGmapsLink] = React.useState(""); + const [placeWebsite, setPlaceWebsite] = React.useState(""); + const [phone, setPhone] = React.useState(""); + const [hours, setHours] = React.useState(""); const [contributor, setContributor] = React.useState(""); const [note, setNote] = React.useState(""); const [honeypot, setHoneypot] = React.useState(""); @@ -122,6 +133,9 @@ export function SuggestPlaceDialog({ setType("library"); setCity(""); setGmapsLink(""); + setPlaceWebsite(""); + setPhone(""); + setHours(""); setContributor(""); setNote(""); setHoneypot(""); @@ -137,13 +151,30 @@ export function SuggestPlaceDialog({ const trimmedGmapsLink = gmapsLink.trim(); const isGmapsLinkValid = isGoogleMapsUrl(trimmedGmapsLink); const showGmapsError = trimmedGmapsLink.length > 0 && !isGmapsLinkValid; - const isValid = Boolean(trimmedName && trimmedCity && isGmapsLinkValid); + // The three contact fields are optional: blank is fine, a filled one must be well formed. + const trimmedWebsite = placeWebsite.trim(); + const normalizedPhone = normalizePhone(phone); + const trimmedHours = hours.trim(); + const showWebsiteError = + trimmedWebsite.length > 0 && + (!isHttpsUrl(trimmedWebsite) || /\s/.test(trimmedWebsite)); + const showPhoneError = normalizedPhone.length > 0 && !isE164Phone(normalizedPhone); + const isValid = Boolean( + trimmedName && + trimmedCity && + isGmapsLinkValid && + !showWebsiteError && + !showPhoneError, + ); const fallbackUrl = isValid ? buildIssueUrl({ name: trimmedName, type, city: trimmedCity, gmapsLink: trimmedGmapsLink, + website: trimmedWebsite, + phone: normalizedPhone, + hours: trimmedHours, contributor, note, }) @@ -163,6 +194,10 @@ export function SuggestPlaceDialog({ type, city: trimmedCity, gmapsLink: trimmedGmapsLink, + // `website` below is the hidden honeypot; the real one is `placeWebsite`. + placeWebsite: trimmedWebsite, + phone: normalizedPhone, + hours: trimmedHours, contributor: contributor.trim(), note: note.trim(), website: honeypot, @@ -331,6 +366,69 @@ export function SuggestPlaceDialog({ ) : null}
+
+ + setPlaceWebsite(e.target.value)} + placeholder="https://..." + maxLength={300} + aria-invalid={showWebsiteError} + aria-describedby={showWebsiteError ? "suggest-place-site-error" : undefined} + /> + {showWebsiteError ? ( + + ) : null} +
+ +
+ + setPhone(e.target.value)} + placeholder="+44 20 7412 7000" + maxLength={30} + aria-invalid={showPhoneError} + aria-describedby={showPhoneError ? "suggest-place-phone-error" : undefined} + /> + {showPhoneError ? ( + + ) : null} +
+ +
+ + setHours(e.target.value)} + placeholder="Mon-Fri 09:00-17:00" + maxLength={120} + aria-describedby="suggest-place-contact-hint" + /> +

+ Only details from the website or listing of the place itself, please. +

+
+
{place.address}

)} + + {/* Exam centre: the validity pill in the header carries the reconfirm date */} diff --git a/src/components/pins/place-contact.test.tsx b/src/components/pins/place-contact.test.tsx new file mode 100644 index 0000000..7c9f84e --- /dev/null +++ b/src/components/pins/place-contact.test.tsx @@ -0,0 +1,125 @@ +import { cleanup, render, screen } from "@testing-library/react"; +import { afterEach, describe, expect, it } from "vitest"; + +import { PlaceContact } from "@/components/pins/place-contact"; +import { PinPopup } from "@/components/pins/pin-popup"; +import type { Place } from "@/lib/types"; + +afterEach(cleanup); + +const base: Place = { + id: "lon-library-01", + name: "British Library", + type: "library", + city: "london", + country: "GB", + lat: 51.5299, + lng: -0.1269, + gmaps_link: "https://maps.google.com/?q=51.5299,-0.1269", + added_by: "someone", +}; + +describe("PlaceContact (#356)", () => { + it("renders nothing for a place with none of the three fields", () => { + const { container } = render(); + expect(container.firstChild).toBeNull(); + }); + + it("renders nothing when the fields are blank", () => { + const { container } = render( + , + ); + expect(container.firstChild).toBeNull(); + }); + + it("links the website by its host, opening in a new tab without leaking the opener", () => { + render(); + + const link = screen.getByRole("link", { name: "bl.uk" }); + expect(link.getAttribute("href")).toBe("https://www.bl.uk/visit"); + expect(link.getAttribute("target")).toBe("_blank"); + expect(link.getAttribute("rel")).toContain("noopener"); + }); + + it("makes the phone number a tel: link", () => { + render(); + + expect(screen.getByRole("link", { name: "+442074127000" }).getAttribute("href")).toBe( + "tel:+442074127000", + ); + }); + + it("shows the opening hours as text", () => { + render(); + + expect(screen.getByText("Mon-Fri 09:30-20:00")).toBeTruthy(); + }); + + it("shows only the fields that exist", () => { + render(); + + expect(screen.queryByRole("link", { name: /bl\.uk/ })).toBeNull(); + expect(screen.queryByText(/Mon-Fri/)).toBeNull(); + expect(screen.getAllByRole("link")).toHaveLength(1); + }); + + it("does not link a website that is not https", () => { + render( + , + ); + + expect(screen.queryByRole("link")).toBeNull(); + expect(screen.getByText("Open daily")).toBeTruthy(); + }); + + it("shows a phone that is not in international form as text, not as a dial link", () => { + render(); + + expect(screen.getByText("020 7412 7000")).toBeTruthy(); + expect(screen.queryByRole("link")).toBeNull(); + }); + + it("labels each row in the detailed variant", () => { + render( + , + ); + + expect(screen.getByText("Website")).toBeTruthy(); + expect(screen.getByText("Phone")).toBeTruthy(); + expect(screen.getByText("Opening hours")).toBeTruthy(); + }); +}); + +describe("PinPopup contact details (#356)", () => { + it("shows the contact details of a place that has them", () => { + render( + , + ); + + expect(screen.getByRole("link", { name: "bl.uk" })).toBeTruthy(); + expect(screen.getByRole("link", { name: "+442074127000" })).toBeTruthy(); + expect(screen.getByText("Mon-Fri 09:30-20:00")).toBeTruthy(); + }); + + it("renders a place without them exactly as before, with no contact links", () => { + render(); + + expect(screen.queryByRole("link", { name: /^tel|bl\.uk/ })).toBeNull(); + expect(screen.getByText("British Library")).toBeTruthy(); + expect(screen.getByRole("link", { name: /Google Maps/ })).toBeTruthy(); + }); +}); diff --git a/src/components/pins/place-contact.tsx b/src/components/pins/place-contact.tsx new file mode 100644 index 0000000..eb4362a --- /dev/null +++ b/src/components/pins/place-contact.tsx @@ -0,0 +1,93 @@ +import { Clock, Globe, Phone } from "lucide-react"; + +import type { Place } from "@/lib/types"; + +/** The link target for a place's website, or null unless it is a well-formed https URL. */ +function safeWebsite(value: string | undefined): { href: string; label: string } | null { + if (!value) return null; + try { + const url = new URL(value); + if (url.protocol !== "https:") return null; + return { href: url.href, label: url.hostname.replace(/^www\./, "") }; + } catch { + return null; + } +} + +/** Only an international-format number is dialled; anything else is shown as plain text. */ +function isDialable(value: string): boolean { + return /^\+[1-9][0-9]{6,14}$/.test(value); +} + +interface PlaceContactProps { + place: Pick; + /** "compact" for the map popup, "detailed" for the drawer, with a label above each row. */ + variant?: "compact" | "detailed"; +} + +/** + * A place's optional website, phone and opening hours (#356). Empty ones are + * left out, and a place with none of them renders nothing at all, exactly as + * it did before these fields existed. + */ +export function PlaceContact({ place, variant = "compact" }: PlaceContactProps) { + const website = safeWebsite(place.website); + const phone = place.phone?.trim() || null; + const hours = place.hours?.trim() || null; + if (!website && !phone && !hours) return null; + + const detailed = variant === "detailed"; + const rowClass = detailed ? "space-y-1" : "flex items-start gap-1.5"; + const textClass = detailed ? "text-sm text-foreground" : "text-xs leading-snug"; + const iconClass = "mt-0.5 size-3.5 shrink-0 text-muted-foreground"; + const linkClass = + "break-all text-foreground underline underline-offset-2 hover:text-primary"; + + return ( +
+ {website && ( +
+ {detailed ? ( +

Website

+ ) : ( + + )} + + {website.label} + +
+ )} + {phone && ( +
+ {detailed ? ( +

Phone

+ ) : ( + + )} + {isDialable(phone) ? ( + + {phone} + + ) : ( + {phone} + )} +
+ )} + {hours && ( +
+ {detailed ? ( +

Opening hours

+ ) : ( + + )} +

{hours}

+
+ )} +
+ ); +} diff --git a/src/lib/data-validation.test.ts b/src/lib/data-validation.test.ts index 6482ef7..0cfdb96 100644 --- a/src/lib/data-validation.test.ts +++ b/src/lib/data-validation.test.ts @@ -1,8 +1,13 @@ +import { readFileSync } from "node:fs"; +import { join } from "node:path"; import { describe, expect, it } from "vitest"; import { findSameNamePlaces, gmapsLinkCoordinates, + isE164Phone, + isHttpsUrl, + isOpeningHours, normalizePlaceName, } from "../../scripts/lib/data-validation.mjs"; @@ -87,3 +92,89 @@ describe("findSameNamePlaces", () => { ).toEqual([]); }); }); + +describe("isE164Phone (#356)", () => { + it.each(["+442074127000", "+14155552671", "+912212345678", "+8613800138000"])( + "accepts %s", + (value) => { + expect(isE164Phone(value)).toBe(true); + }, + ); + + it.each([ + "442074127000", + "+44 20 7412 7000", + "+44-20-7412-7000", + "(020) 7412 7000", + "+0442074127000", + "+4420", + "+1234567890123456", + "", + "tel:+442074127000", + ])("rejects %j", (value) => { + expect(isE164Phone(value)).toBe(false); + }); + + it("rejects values that are not strings", () => { + expect(isE164Phone(442074127000)).toBe(false); + expect(isE164Phone(null)).toBe(false); + }); +}); + +describe("isOpeningHours (#356)", () => { + it("accepts short single-line text", () => { + expect(isOpeningHours("Mon-Fri 09:00-17:00")).toBe(true); + expect(isOpeningHours("Open 24 hours")).toBe(true); + }); + + it("rejects blank text, line breaks and anything over 120 characters", () => { + expect(isOpeningHours("")).toBe(false); + expect(isOpeningHours(" ")).toBe(false); + expect(isOpeningHours("Mon-Fri\n9-5")).toBe(false); + expect(isOpeningHours("x".repeat(121))).toBe(false); + expect(isOpeningHours("x".repeat(120))).toBe(true); + }); +}); + +describe("place schema and validator agree on the contact fields (#356)", () => { + const schema = JSON.parse( + readFileSync(join(process.cwd(), "data", "places.schema.json"), "utf8"), + ); + const props = schema.properties; + + it("lists website, phone and hours as optional properties", () => { + for (const field of ["website", "phone", "hours"]) { + expect(props[field]).toBeTruthy(); + expect(schema.required).not.toContain(field); + } + }); + + it("uses a phone pattern that matches the validator on the same samples", () => { + const re = new RegExp(props.phone.pattern); + for (const sample of [ + "+442074127000", + "+14155552671", + "442074127000", + "+44 20 7412", + "", + ]) { + expect(re.test(sample)).toBe(isE164Phone(sample)); + } + }); + + it("uses a website pattern that requires https", () => { + const re = new RegExp(props.website.pattern); + for (const sample of [ + "https://www.bl.uk", + "http://www.bl.uk", + "www.bl.uk", + "https://with space.com", + ]) { + expect(re.test(sample)).toBe(isHttpsUrl(sample) && !/\s/.test(sample)); + } + }); + + it("caps the hours length at the same limit as the validator", () => { + expect(props.hours.maxLength).toBe(120); + }); +}); diff --git a/src/lib/place-submission.test.ts b/src/lib/place-submission.test.ts index 6bbd512..4990ebe 100644 --- a/src/lib/place-submission.test.ts +++ b/src/lib/place-submission.test.ts @@ -283,3 +283,121 @@ describe("appendRecordText", () => { expect(JSON.parse(appendRecordText("[]\n", record))).toEqual([record]); }); }); + +describe("optional contact details (#356)", () => { + const withContact = { + ...valid, + city: "Mumbai", + placeWebsite: "https://www.bl.uk/", + phone: "+44 (0)20 7412 7000", + hours: "Mon-Fri 09:30-20:00", + }; + + it("leaves the three fields out entirely when they are blank or absent", () => { + const value = submission({ ...valid, placeWebsite: "", phone: " ", hours: "" }); + expect(value).not.toHaveProperty("website"); + expect(value).not.toHaveProperty("phone"); + expect(value).not.toHaveProperty("hours"); + }); + + it("normalises a typed phone number to E.164", () => { + for (const typed of [ + "+44 20 7412 7000", + "+44-20-7412-7000", + "0044 20 7412 7000", + "+44 (0)20 7412 7000", + "+442074127000", + ]) { + expect(submission({ ...valid, phone: typed }).phone).toBe("+442074127000"); + } + }); + + it("rejects a phone number with no country code", () => { + const result = normalizeSubmission({ ...valid, phone: "020 7412 7000" }); + expect(result.ok).toBe(false); + expect((result as { error: string }).error).toContain("country code"); + }); + + it("rejects a website that is not https, has no scheme, or contains spaces", () => { + for (const website of [ + "http://www.bl.uk", + "www.bl.uk", + "https://bl .uk", + "javascript:alert(1)", + ]) { + const result = normalizeSubmission({ ...valid, placeWebsite: website }); + expect(result.ok, website).toBe(false); + } + }); + + it("reads the website from placeWebsite, the key the form sends", () => { + expect(submission({ ...valid, placeWebsite: "https://www.bl.uk/" }).website).toBe( + "https://www.bl.uk/", + ); + }); + + it("reads the website back from a stored submission, which uses website", () => { + expect(submission({ ...valid, website: "https://www.bl.uk/" }).website).toBe( + "https://www.bl.uk/", + ); + }); + + it("flattens line breaks and em dashes in hours", () => { + expect(submission({ ...valid, hours: "Mon—Fri\n9-5" }).hours).toBe("Mon-Fri 9-5"); + }); + + it("caps hours at 120 characters", () => { + expect(submission({ ...valid, hours: "x".repeat(300) }).hours).toHaveLength(120); + }); + + it("round-trips through the issue body", () => { + const sub = submission(withContact); + const body = buildIssueBody(sub); + expect(body).toContain("**Website:** https://www.bl.uk/"); + expect(body).toContain("**Phone:** +442074127000"); + expect(body).toContain("**Hours:** Mon-Fri 09:30-20:00"); + expect(parseIssueBody(body)).toMatchObject({ + website: "https://www.bl.uk/", + phone: "+442074127000", + hours: "Mon-Fri 09:30-20:00", + }); + }); + + it("puts only the given fields in the record, before gmaps_link", () => { + const sub = submission({ ...valid, city: "Mumbai", hours: "Mon-Sat 10:00-18:00" }); + const record = buildPlaceRecord({ + sub, + coords: { lat: 19.033, lng: 73.0297 }, + country: "IN", + id: "mum-library-03", + }); + expect(record).toMatchObject({ hours: "Mon-Sat 10:00-18:00" }); + expect(record).not.toHaveProperty("website"); + expect(record).not.toHaveProperty("phone"); + const keys = Object.keys(record); + expect(keys.indexOf("hours")).toBeLessThan(keys.indexOf("gmaps_link")); + }); + + it("turns a submission with contact details into a record and tells the reviewer to check them", async () => { + const result = await processSubmission({ + body: buildIssueBody(submission(withContact)), + records, + }); + expect(result.status).toBe("ready"); + expect((result as { record: Record }).record).toMatchObject({ + website: "https://www.bl.uk/", + phone: "+442074127000", + hours: "Mon-Fri 09:30-20:00", + }); + expect(result.message).toContain("place's own site or listing"); + }); + + it("does not ask the reviewer to check contact details when there are none", async () => { + const result = await processSubmission({ + body: buildIssueBody(submission({ ...valid, city: "Mumbai" })), + records, + }); + expect(result.status).toBe("ready"); + expect(result.message).not.toContain("typed by the submitter"); + }); +}); diff --git a/src/lib/places-api.test.ts b/src/lib/places-api.test.ts index 61ea167..1b5642b 100644 --- a/src/lib/places-api.test.ts +++ b/src/lib/places-api.test.ts @@ -204,3 +204,26 @@ describe("unknownCountryError", () => { ).toContain('"ZZ"'); }); }); + +describe("queryPlaces contact fields (#356)", () => { + it("returns the optional website, phone and hours unchanged, and nothing extra for places without them", () => { + const withContact: Place = { + ...place("lon-1", "london", "library", "GB"), + website: "https://www.bl.uk/", + phone: "+442074127000", + hours: "Mon-Fri 09:30-20:00", + }; + const plain = place("lon-2", "london", "library", "GB"); + + const result = queryPlaces([withContact, plain], { limit: 100, offset: 0 }); + + expect(result.data[0]).toMatchObject({ + website: "https://www.bl.uk/", + phone: "+442074127000", + hours: "Mon-Fri 09:30-20:00", + }); + expect(result.data[1]).not.toHaveProperty("website"); + expect(result.data[1]).not.toHaveProperty("phone"); + expect(result.data[1]).not.toHaveProperty("hours"); + }); +}); diff --git a/src/lib/types.ts b/src/lib/types.ts index 098fda2..0225c5b 100644 --- a/src/lib/types.ts +++ b/src/lib/types.ts @@ -289,6 +289,12 @@ export interface Place { lat: number; lng: number; address?: string; + /** Optional: the place's own https:// website or listing page (#356). */ + website?: string; + /** Optional: international format with no spaces, e.g. "+442074127000" (#356). */ + phone?: string; + /** Optional: short free text, e.g. "Mon-Fri 09:00-17:00" (#356). */ + hours?: string; gmaps_link: string; added_by: string; /** Optional proof a contributor re-checked this place; verified places show a badge. */