From d3bd77ad7ca2d64ea6c827358f66e75c7bdd6b73 Mon Sep 17 00:00:00 2001 From: Derek J <127624400+heyderekj@users.noreply.github.com> Date: Fri, 13 Nov 2026 16:03:54 -0600 Subject: [PATCH] Follow Here's My Church's claimed listings and automatic checks Here's My Church now lets a church that has claimed its listing review others' changes first, and checks held changes automatically before a person sees them. Lookup handles both, and still works with today's HMC: - Contributions pass through reviewBy: "church" from HMC's answer. The statuses are unchanged, and a maintenance 503 is still try_again. - Sync carries claimed from the export into a new D1 column (migration m4) and the record returns claimed: true/false. Only a claimed row hashes the flag, so existing rows don't all rewrite. - /v1/meta adds checks to each contributable field; review is kept. - The widget and the shadcn ChurchConsent badge a blank field "Goes live", a replacement "Checked automatically", a claimed listing "The church reviews this", and a held-for-church result "Sent to the church", in all six languages. - Docs describe the real rules, and that AI only locates a quote on the church's website that code then verifies. Co-Authored-By: Claude Opus 5.5 --- docs/api.md | 10 ++-- docs/data.md | 25 ++++++--- docs/how-search-works.md | 2 +- docs/index.md | 2 +- docs/react.md | 2 +- docs/widget.md | 2 +- .../src/components/church-consent.tsx | 20 ++++--- examples/shadcn-demo/src/lib/lookup-core.ts | 36 +++++++++++- .../shadcn-demo/src/lib/lookup-strings.ts | 15 +++++ packages/sdk/CHANGELOG.md | 6 ++ packages/sdk/src/client.ts | 8 ++- packages/sdk/src/core.ts | 21 ++++++- packages/sdk/src/element.ts | 17 +++--- packages/sdk/src/strings-de.ts | 3 + packages/sdk/src/strings-es.ts | 3 + packages/sdk/src/strings-fr.ts | 3 + packages/sdk/src/strings-pl.ts | 3 + packages/sdk/src/strings-pt.ts | 3 + packages/sdk/src/strings.ts | 10 ++++ packages/sdk/test/core.test.ts | 16 +++++- packages/sdk/test/element.test.ts | 13 ++++- registry/components/church-consent.tsx | 20 ++++--- registry/lib/lookup-core.ts | 36 +++++++++++- registry/lib/lookup-strings.ts | 15 +++++ scripts/build-index.ts | 4 +- worker/migrations-m4.sql | 2 + worker/schema.sql | 3 +- worker/src/contribute.ts | 27 ++++++--- worker/src/project.ts | 8 ++- worker/src/record.ts | 56 +++++++++++++------ worker/src/sync.ts | 6 +- worker/test/api.test.ts | 7 ++- worker/test/contribute.test.ts | 27 +++++++++ worker/test/project.test.ts | 9 +++ worker/test/sync.test.ts | 22 +++++++- 35 files changed, 373 insertions(+), 89 deletions(-) create mode 100644 worker/migrations-m4.sql diff --git a/docs/api.md b/docs/api.md index f7557aa..a164ca8 100644 --- a/docs/api.md +++ b/docs/api.md @@ -39,7 +39,7 @@ The response has `results`, plus `hasMore` when more churches ranked past `limit ## GET /v1/churches/:id -The autofill record. Every key in `fields` is always present, with `null` or `[]` when empty, plus `missing`, `completeness`, `hints`, `freshness.lastVerified` (when someone last confirmed it, in milliseconds, or `null`) and `links.heresMyChurch` (the church's page; add `?suggest=1` to open its fix form). Records are cached for a minute, and a change that goes live through Lookup refreshes it at once. +The autofill record. Every key in `fields` is always present, with `null` or `[]` when empty, plus `missing`, `completeness`, `hints`, `freshness.lastVerified` (when someone last confirmed it, in milliseconds, or `null`), `links.heresMyChurch` (the church's page; add `?suggest=1` to open its fix form) and `claimed` (`true` when the church has claimed its listing on Here's My Church, so others' changes go to the church first). Records are cached for a minute, and a change that goes live through Lookup refreshes it at once. ```bash curl https://lookup.heresmychurch.com/v1/churches/CA-ON-56994145 @@ -47,7 +47,7 @@ curl https://lookup.heresmychurch.com/v1/churches/CA-ON-56994145 ## GET /v1/meta -Field names, what can be contributed and how it's reviewed (`contributableFields`), whether adding churches is on (`addEnabled`), completeness weights, counts and attribution. +Field names, what can be contributed and how it's checked (`contributableFields`, each with `countries`, `review` and `checks`), whether adding churches is on (`addEnabled`), completeness weights, counts and attribution. ## POST /v1/churches/:id/contributions @@ -55,13 +55,15 @@ Send corrections as `{ client, changes: [{ field, value }] }`. Fields are `servi | Status | Meaning | |---|---| -| `live` | Applied now. These fields go live on one vote. | -| `in_review` | Waits for a Here's My Church moderator. | +| `live` | Applied now, such as a blank field filled in. | +| `in_review` | Held. Here's My Church checks it automatically, and a reviewer decides what the checks can't. With `reviewBy: "church"`, the church reviews it first, since it has claimed its listing. | | `not_applied` | Not changed: the listed value was already the same, or Here's My Church kept it. | | `rejected` | Not accepted, with a `message` saying why. | | `try_again` | A temporary problem, such as maintenance or a rate limit. Nothing was refused. | | `coming_soon` | A field Lookup will accept soon. Name is coming soon. | +`reviewBy` is only present when Here's My Church says who reviews a held change, and so far it's only ever `"church"`. The statuses themselves don't change, so code that reads only `status` keeps working. [Data and review](/docs/data#sharing-fixes-back) has the rules for each field. + ```bash curl -X POST https://lookup.heresmychurch.com/v1/churches/CA-ON-56994145/contributions \ -H "content-type: application/json" \ diff --git a/docs/data.md b/docs/data.md index 00b60a9..a843304 100644 --- a/docs/data.md +++ b/docs/data.md @@ -12,17 +12,24 @@ Its map counts every listing, about 655,000. Lookup leaves out about 68,000 that ## Sharing fixes back -When someone changes a detail Lookup filled, the widget offers to share it. Changed fields start checked, each says whether it goes live or waits for a moderator, and nothing is sent until they choose **Share** (or submit your form with a checked [`data-hmc-share`](/docs/widget#share-on-submit) box). Your form's own submit is never blocked. +When someone changes a detail Lookup filled, the widget offers to share it. Changed fields start checked, each says what will happen to it ("Goes live", "Checked automatically" or "The church reviews this"), and nothing is sent until they choose **Share** (or submit your form with a checked [`data-hmc-share`](/docs/widget#share-on-submit) box). Your form's own submit is never blocked. -| Field | Where | Review | +**Claimed listings come first.** When a church has claimed its listing on Here's My Church (verified its listed inbox), everyone else's changes go to the church to review. The record says `claimed: true`, and each held change comes back with `reviewBy: "church"`. + +**Filling a blank field** goes live on one vote, with an automatic spam check afterwards. Email and pastor name are the exception: from Lookup they're always held, since a host's form can hold someone's personal details. + +**Replacing a value that's already listed**, or reporting a problem, is held and checked automatically by Here's My Church: + +| Field | Approved when | Otherwise | |---|---|---| -| Service times, denomination, languages, ministries | Everywhere | Live on one vote | -| Phone | Everywhere | Live on one vote | -| Website | Everywhere | Waits for a moderator | -| Address (street, city and postal code, sent together) | Everywhere | Waits for a moderator | -| Email, pastor name | Everywhere | Always waits for a moderator, since a host's form can hold someone's personal details | -| Closed, duplicate or moved reports | Everywhere | Waits for a moderator | -| Name | Coming soon | Will wait for a moderator | +| Phone, service times | It appears on the church's own website, two or more people independently send the same value, or after three quiet days | A Here's My Church reviewer decides | +| Denomination, languages, ministries (additions only) | People agree, it passes the naming rules, or after three quiet days | A Here's My Church reviewer decides | +| Name, website, address (street, city and postal code, sent together) | There's evidence: the church's own website, a small spelling fix to a name, an address within 150 m of the map pin | A Here's My Church reviewer decides | +| Email, pastor name | There's evidence, such as the church's own website | A Here's My Church reviewer decides | +| Closed or duplicate reports | Strong evidence. The listing is hidden, not deleted, so it can come back | A Here's My Church reviewer decides | +| Moved reports | Never automatically | A Here's My Church reviewer decides | + +Name corrections are coming soon through Lookup. The checks never let AI approve anything: where they read the church's website, an AI model only points to the sentence that should hold the value, and code confirms that the quote is really on the page and contains the value. `/v1/meta` lists each field with `checks`: `"automatic"`, `"automatic-then-reviewer"` or `"reviewer"`. A change that goes live shows in Lookup's search and records within seconds, without waiting for the next sync. diff --git a/docs/how-search-works.md b/docs/how-search-works.md index 4c1f006..19e007d 100644 --- a/docs/how-search-works.md +++ b/docs/how-search-works.md @@ -34,5 +34,5 @@ A formula, not AI, orders results. | Semantic search | One AI model, bge-m3 on Cloudflare Workers AI and Vectorize, runs only when no name matches every word. On the held-out test it moved "in top 5" from 85% to 87% and "no results" from 1% to 0%. | | Ask AI in these docs | An instruct model on Workers AI answers questions using only these docs, and links the pages it used. Questions aren't stored. | | Ranking | A formula, not AI. | -| Church details | AI never writes or changes them. Every fill comes from Here's My Church, and every shared fix goes through its review rules. | +| Church details | AI never writes or approves them. Every fill comes from Here's My Church, and every shared fix goes through its rules: the church first when it has claimed its listing, then automatic checks. When a check reads the church's own website, an AI model on Workers AI only points to the sentence that should hold the value; code confirms that quote is on the page and matches. What the checks can't decide goes to a person. | | Searches | Lookup doesn't log them. | diff --git a/docs/index.md b/docs/index.md index ab18288..35104ef 100644 --- a/docs/index.md +++ b/docs/index.md @@ -24,7 +24,7 @@ Church tools keep asking people for the same details. Lookup fills them in from 1. **Search as you type.** Prefixes, typos and places like "church in dallas" all work, nearby churches first. 2. **Fill your form.** Pick a church and the empty fields you tagged with `data-hmc-field` fill in. Anything already typed is left alone. -3. **Share fixes back.** When someone corrects a detail Lookup filled, they can share it back to Here's My Church, one checked box at a time. +3. **Share fixes back.** When someone corrects a detail Lookup filled, they can share it back to Here's My Church, one checked box at a time. A church that has claimed its listing reviews changes to it first. Otherwise Here's My Church checks them automatically, for example against the church's own website, where AI locates a quote and code confirms it, and a person reviews whatever the checks can't decide. Because every pick comes from the same open directory, each app that uses Lookup helps keep church data accurate. diff --git a/docs/react.md b/docs/react.md index 9550e3b..f015674 100644 --- a/docs/react.md +++ b/docs/react.md @@ -116,7 +116,7 @@ pnpm dlx shadcn@latest add https://lookup.heresmychurch.com/r/church-consent.jso ``` -It shows only fields Here's My Church accepts for that church's country. Changed fields start checked, `street`, `city` and `postalCode` show as one Address row, each says whether it goes live or waits for a moderator, and nothing is sent until the person chooses Share. A checked `data-hmc-share` checkbox in the submitted form sends them too, without blocking the submit. When nothing changed, it asks "Still correct?" of listings nobody confirmed this year. It also offers **Report a problem** and a link to fix anything else on Here's My Church. +It shows only fields Here's My Church accepts for that church's country. Changed fields start checked, `street`, `city` and `postalCode` show as one Address row, each says whether it goes live, is checked automatically or goes to the church first (a claimed listing), and nothing is sent until the person chooses Share. A checked `data-hmc-share` checkbox in the submitted form sends them too, without blocking the submit. When nothing changed, it asks "Still correct?" of listings nobody confirmed this year. It also offers **Report a problem** and a link to fix anything else on Here's My Church. ## Your own UI diff --git a/docs/widget.md b/docs/widget.md index bbee1d6..7172a0f 100644 --- a/docs/widget.md +++ b/docs/widget.md @@ -150,7 +150,7 @@ document.querySelector("church-lookup").fieldMap = { website: "#site-url", phone ## Sharing fixes -After a fill, changing a field Lookup filled shows the changes below the church field, checked, with **Share N fixes**. Street, city and postal code show as one Address row. "Still correct?" appears only for listings nobody confirmed in the last year. See [Data and review](/docs/data#sharing-fixes-back) for what's accepted where. +After a fill, changing a field Lookup filled shows the changes below the church field, checked, with **Share N fixes**. Street, city and postal code show as one Address row. Each row says "Goes live" (a blank field), "Checked automatically" (a replacement) or, for a listing the church has claimed, "The church reviews this". "Still correct?" appears only for listings nobody confirmed in the last year. See [Data and review](/docs/data#sharing-fixes-back) for what's accepted where. ### Share on submit diff --git a/examples/shadcn-demo/src/components/church-consent.tsx b/examples/shadcn-demo/src/components/church-consent.tsx index 17da7b4..d8a75c5 100644 --- a/examples/shadcn-demo/src/components/church-consent.tsx +++ b/examples/shadcn-demo/src/components/church-consent.tsx @@ -1,8 +1,9 @@ "use client" // ChurchConsent: after a ChurchLookup fill, offer to share the person's corrections back to Here's My -// Church. Changed fields start checked, each says whether it goes live or waits for a moderator, and -// nothing is sent until they choose Share (or submit the form with a checked data-hmc-share box). +// Church. Changed fields start checked, each says whether it goes live, is checked automatically or +// goes to the church first (a claimed listing), and nothing is sent until they choose Share (or +// submit the form with a checked data-hmc-share box). // When nothing changed, it asks "Still correct?" of listings nobody confirmed this year. It also // offers "Report a problem" and a link to fix anything else on Here's My Church. import * as React from "react" @@ -13,12 +14,14 @@ import { Checkbox } from "@/components/ui/checkbox" import { cn } from "@/lib/utils" import { changeFor, + consentBadge, consentDiff, contributable, createLookup, fieldValue, isStale, mergeAddress, + resultText, stringsFor, suggestUrl, type ChurchRecord, @@ -42,7 +45,7 @@ export interface ChurchConsentProps { client?: string baseUrl?: string lookup?: Lookup - onShared?: (results: { field: string; status: FieldStatus; message?: string }[], sandbox: boolean) => void + onShared?: (results: { field: string; status: FieldStatus; message?: string; reviewBy?: "church" }[], sandbox: boolean) => void /** Text language, such as "es". Defaults to the page's. Load other languages with @/lib/lookup-strings. */ lang?: string /** Override any text. */ @@ -50,7 +53,7 @@ export interface ChurchConsentProps { className?: string } -type Result = { status: FieldStatus; message?: string } +type Result = { status: FieldStatus; message?: string; reviewBy?: "church" } const REPORTS = ["reportClosed", "reportDuplicate", "reportRelocated"] as const export function ChurchConsent({ record, values, labels = {}, client, baseUrl, lookup: own, onShared, lang, strings, className }: ChurchConsentProps) { @@ -152,7 +155,7 @@ export function ChurchConsent({ record, values, labels = {}, client, baseUrl, lo if (!picked.length) return const changes = picked.map(changeFor) setBusy(true) - let out: { sandbox?: boolean; results: { field: string; status: FieldStatus; message?: string }[] } + let out: { sandbox?: boolean; results: { field: string; status: FieldStatus; message?: string; reviewBy?: "church" }[] } try { out = await lookup.contribute(record!.id, changes) } catch { @@ -215,9 +218,8 @@ export function ChurchConsent({ record, values, labels = {}, client, baseUrl, lo const soon = r.rule.status === "coming_soon" const id = `${uid}-${r.field}` const label = r.parts ? t.address : r.label - const badge = res - ? res.status === "rejected" && res.message ? `${t.st.rejected}: ${res.message}` : t.st[res.status] - : soon ? t.soon : r.rule.review === "moderated" ? t.reviewed : t.goesLive + const before = consentBadge(t, r, soon, record.claimed) + const badge = res ? resultText(t, res) : before.text return (
  • {r.was || "—"} {sent.get(r.field) ?? r.value.trim()} - {badge} + {badge}
  • ) })} diff --git a/examples/shadcn-demo/src/lib/lookup-core.ts b/examples/shadcn-demo/src/lib/lookup-core.ts index 5f01f4c..ce9e29f 100644 --- a/examples/shadcn-demo/src/lib/lookup-core.ts +++ b/examples/shadcn-demo/src/lib/lookup-core.ts @@ -127,6 +127,8 @@ export interface ChurchRecord { hints: { nearestPlace: string | null }; /** The church's page on Here's My Church, where people can fix anything else. Add ?suggest=1 to open the form. */ links?: { heresMyChurch: string | null }; + /** The church has claimed its listing on Here's My Church. Others' changes go to the church first. */ + claimed?: boolean; attribution: string; } @@ -135,7 +137,8 @@ export type FieldStatus = "live" | "in_review" | "not_applied" | "rejected" | "t export interface ContributionResult { churchId: string; sandbox?: boolean; - results: { field: string; status: FieldStatus; message?: string }[]; + /** reviewBy "church": the change is held for the church itself to review (a claimed listing). */ + results: { field: string; status: FieldStatus; message?: string; reviewBy?: "church" }[]; } /** A church to add: record field names. Name, city and region (a code or name) are required. */ export interface NewChurch { @@ -148,7 +151,8 @@ export interface AddResult { status: "live" | "similar" | "rejected" | "try_agai export interface ConfirmResult { churchId: string; sandbox?: boolean; status: "confirmed" | FieldStatus; message?: string; lastVerified?: number } export interface Meta { fields: string[]; - contributableFields: Record; + /** `checks`: "automatic" fields are decided by Here's My Church's checks; "automatic-then-reviewer" ones go to a person when the checks can't decide; "reviewer" always does. */ + contributableFields: Record; completenessWeights: Record; /** Whether addChurch() takes new churches right now. */ addEnabled?: boolean; @@ -291,7 +295,14 @@ export interface Strings { share: string; notNow: string; goesLive: string; + /** No longer shown: replacements say `checked`. Kept so existing overrides still type-check. */ reviewed: string; + /** A replacement, which Here's My Church checks automatically. */ + checked: string; + /** Any change on a listing the church has claimed. */ + churchReviews: string; + /** After sending, a change held for the church to review. */ + sentToChurch: string; soon: string; st: { live: string; in_review: string; not_applied: string; rejected: string; try_again: string; coming_soon: string }; shared: (n: number) => string; @@ -354,6 +365,9 @@ export const EN: Strings = { notNow: "Not now", goesLive: "Goes live", reviewed: "A moderator reviews it", + checked: "Checked automatically", + churchReviews: "The church reviews this", + sentToChurch: "Sent to the church", soon: "Coming soon", st: { live: "Live now", in_review: "Sent for review", not_applied: "Not changed: Here's My Church kept the listed value", rejected: "Not accepted", try_again: "Couldn't send. Try again shortly.", coming_soon: "Coming soon" }, shared: (n) => `Shared ${n} ${n === 1 ? "change" : "changes"}.`, @@ -792,6 +806,24 @@ export function mergeAddress(rows: T[]): (T & { parts?: Re return rows.flatMap((r) => (r === parts[0] ? [address] : parts.includes(r) ? [] : [r])); } +/** Lookup always holds these, even into a blank field: a host form can hold someone's personal details. */ +const ALWAYS_HELD = ["email", "pastorName"]; + +/** + * What a consent row's badge says before sending: coming soon, the church reviews it (a claimed + * listing), goes live (a blank field), or checked automatically (a replacement). + */ +export function consentBadge(t: Strings, r: { field: string; was: string }, soon: boolean, claimed?: boolean): { text: string; live: boolean } { + const live = !soon && !claimed && !r.was.trim() && !ALWAYS_HELD.includes(r.field); + return { text: soon ? t.soon : claimed ? t.churchReviews : live ? t.goesLive : t.checked, live }; +} + +/** A sent field's outcome, as the badge shows it. */ +export function resultText(t: Strings, r: { status: FieldStatus; message?: string; reviewBy?: string }): string { + if (r.status === "rejected" && r.message) return `${t.st.rejected}: ${r.message}`; + return r.status === "in_review" && r.reviewBy === "church" ? t.sentToChurch : t.st[r.status]; +} + /** The change to send for a consent row: an address goes as its parts. */ export const changeFor = (r: ConsentRow & { parts?: Record }) => ({ field: r.field, value: r.parts ?? r.value.trim() }); diff --git a/examples/shadcn-demo/src/lib/lookup-strings.ts b/examples/shadcn-demo/src/lib/lookup-strings.ts index fca415a..ad5fa89 100644 --- a/examples/shadcn-demo/src/lib/lookup-strings.ts +++ b/examples/shadcn-demo/src/lib/lookup-strings.ts @@ -32,6 +32,9 @@ import { registerStrings, type Strings } from "@/lib/lookup-core" notNow: "Ahora no", goesLive: "Se publica", reviewed: "Lo revisa un moderador", + checked: "Se revisa automáticamente", + churchReviews: "La iglesia lo revisa", + sentToChurch: "Enviado a la iglesia", soon: "Próximamente", st: { live: "Publicado", in_review: "Enviado a revisión", not_applied: "Sin cambios: Here's My Church mantuvo el dato publicado", rejected: "No aceptado", try_again: "No se pudo enviar. Inténtalo en un momento.", coming_soon: "Próximamente" }, shared: (n) => `${n} ${n === 1 ? "cambio compartido" : "cambios compartidos"}.`, @@ -88,6 +91,9 @@ import { registerStrings, type Strings } from "@/lib/lookup-core" notNow: "Pas maintenant", goesLive: "Publié aussitôt", reviewed: "Un modérateur vérifie", + checked: "Vérifié automatiquement", + churchReviews: "L'église le vérifie", + sentToChurch: "Envoyé à l'église", soon: "Bientôt", st: { live: "Publié", in_review: "Envoyé pour vérification", not_applied: "Inchangé : Here's My Church a gardé la valeur publiée", rejected: "Non accepté", try_again: "Envoi impossible. Réessayez dans un instant.", coming_soon: "Bientôt" }, shared: (n) => `${n} ${n === 1 ? "modification partagée" : "modifications partagées"}.`, @@ -144,6 +150,9 @@ import { registerStrings, type Strings } from "@/lib/lookup-core" notNow: "Nicht jetzt", goesLive: "Sofort sichtbar", reviewed: "Wird moderiert", + checked: "Wird automatisch geprüft", + churchReviews: "Die Gemeinde prüft das", + sentToChurch: "An die Gemeinde gesendet", soon: "Bald verfügbar", st: { live: "Jetzt sichtbar", in_review: "Zur Prüfung gesendet", not_applied: "Nicht geändert: Here's My Church behält den bisherigen Wert", rejected: "Nicht angenommen", try_again: "Senden fehlgeschlagen. Bitte gleich noch einmal versuchen.", coming_soon: "Bald verfügbar" }, shared: (n) => `${n} ${n === 1 ? "Änderung" : "Änderungen"} geteilt.`, @@ -200,6 +209,9 @@ import { registerStrings, type Strings } from "@/lib/lookup-core" notNow: "Agora não", goesLive: "Publicado na hora", reviewed: "Um moderador revisa", + checked: "Verificado automaticamente", + churchReviews: "A igreja revisa isto", + sentToChurch: "Enviado para a igreja", soon: "Em breve", st: { live: "Publicado", in_review: "Enviado para revisão", not_applied: "Sem mudança: o Here's My Church manteve o dado publicado", rejected: "Não aceito", try_again: "Não foi possível enviar. Tente de novo em instantes.", coming_soon: "Em breve" }, shared: (n) => `${n} ${n === 1 ? "mudança compartilhada" : "mudanças compartilhadas"}.`, @@ -258,6 +270,9 @@ import { registerStrings, type Strings } from "@/lib/lookup-core" notNow: "Nie teraz", goesLive: "Od razu widoczne", reviewed: "Sprawdza moderator", + checked: "Sprawdzane automatycznie", + churchReviews: "Sprawdza kościół", + sentToChurch: "Wysłano do kościoła", soon: "Wkrótce", st: { live: "Widoczne", in_review: "Wysłano do sprawdzenia", not_applied: "Bez zmian: Here's My Church zachował obecną wartość", rejected: "Nie przyjęto", try_again: "Nie udało się wysłać. Spróbuj za chwilę.", coming_soon: "Wkrótce" }, shared: (n) => `Udostępniono zmiany: ${n}.`, diff --git a/packages/sdk/CHANGELOG.md b/packages/sdk/CHANGELOG.md index ac6c496..36fcf76 100644 --- a/packages/sdk/CHANGELOG.md +++ b/packages/sdk/CHANGELOG.md @@ -2,6 +2,12 @@ All notable changes to `@heresmychurch/lookup`. Versions follow [semver](https://semver.org); while the version is 0.x, a minor release can change behavior, so pin the exact version you test against. +## Unreleased + +- Consent badges follow Here's My Church's checks: filling a blank field says "Goes live", replacing a value says "Checked automatically", and every change on a listing the church has claimed says "The church reviews this". After sending, a change held for the church says "Sent to the church". New strings `checked`, `churchReviews` and `sentToChurch`, in every language; `reviewed` is no longer shown but stays in `Strings`. +- Types: `ChurchRecord.claimed`, `reviewBy?: "church"` on contribution results, and `checks` on `Meta.contributableFields`. All optional, so older API responses still type-check. +- Core: `consentBadge` and `resultText`, the badge wording the widget and the shadcn `ChurchConsent` share. + ## 0.4.0 - React: `useChurchLookup` ships in `@heresmychurch/lookup/react`, so React apps without shadcn/ui get the headless core as a hook. React is an optional peer dependency, needed only for that entry. diff --git a/packages/sdk/src/client.ts b/packages/sdk/src/client.ts index 0234480..6208335 100644 --- a/packages/sdk/src/client.ts +++ b/packages/sdk/src/client.ts @@ -111,6 +111,8 @@ export interface ChurchRecord { hints: { nearestPlace: string | null }; /** The church's page on Here's My Church, where people can fix anything else. Add ?suggest=1 to open the form. */ links?: { heresMyChurch: string | null }; + /** The church has claimed its listing on Here's My Church. Others' changes go to the church first. */ + claimed?: boolean; attribution: string; } @@ -119,7 +121,8 @@ export type FieldStatus = "live" | "in_review" | "not_applied" | "rejected" | "t export interface ContributionResult { churchId: string; sandbox?: boolean; - results: { field: string; status: FieldStatus; message?: string }[]; + /** reviewBy "church": the change is held for the church itself to review (a claimed listing). */ + results: { field: string; status: FieldStatus; message?: string; reviewBy?: "church" }[]; } /** A church to add: record field names. Name, city and region (a code or name) are required. */ export interface NewChurch { @@ -132,7 +135,8 @@ export interface AddResult { status: "live" | "similar" | "rejected" | "try_agai export interface ConfirmResult { churchId: string; sandbox?: boolean; status: "confirmed" | FieldStatus; message?: string; lastVerified?: number } export interface Meta { fields: string[]; - contributableFields: Record; + /** `checks`: "automatic" fields are decided by Here's My Church's checks; "automatic-then-reviewer" ones go to a person when the checks can't decide; "reviewer" always does. */ + contributableFields: Record; completenessWeights: Record; /** Whether addChurch() takes new churches right now. */ addEnabled?: boolean; diff --git a/packages/sdk/src/core.ts b/packages/sdk/src/core.ts index a778da3..6f39857 100644 --- a/packages/sdk/src/core.ts +++ b/packages/sdk/src/core.ts @@ -1,8 +1,9 @@ // @heresmychurch/lookup/core: the headless engine behind , for building your own UI // (the shadcn registry components use it). No rendering and no side effects on import: nothing is // registered, and timers only run while a search is pending. -import { createLookup, type ChurchRecord, type Lookup, type LookupError, type Meta, type NewChurch, type SearchResult } from "./client.ts"; +import { createLookup, type ChurchRecord, type FieldStatus, type Lookup, type LookupError, type Meta, type NewChurch, type SearchResult } from "./client.ts"; import { setNativeValue, type FieldTarget } from "./dom.ts"; +import type { Strings } from "./strings.ts"; export * from "./client.ts"; export { setNativeValue, type FieldTarget }; @@ -367,6 +368,24 @@ export function mergeAddress(rows: T[]): (T & { parts?: Re return rows.flatMap((r) => (r === parts[0] ? [address] : parts.includes(r) ? [] : [r])); } +/** Lookup always holds these, even into a blank field: a host form can hold someone's personal details. */ +const ALWAYS_HELD = ["email", "pastorName"]; + +/** + * What a consent row's badge says before sending: coming soon, the church reviews it (a claimed + * listing), goes live (a blank field), or checked automatically (a replacement). + */ +export function consentBadge(t: Strings, r: { field: string; was: string }, soon: boolean, claimed?: boolean): { text: string; live: boolean } { + const live = !soon && !claimed && !r.was.trim() && !ALWAYS_HELD.includes(r.field); + return { text: soon ? t.soon : claimed ? t.churchReviews : live ? t.goesLive : t.checked, live }; +} + +/** A sent field's outcome, as the badge shows it. */ +export function resultText(t: Strings, r: { status: FieldStatus; message?: string; reviewBy?: string }): string { + if (r.status === "rejected" && r.message) return `${t.st.rejected}: ${r.message}`; + return r.status === "in_review" && r.reviewBy === "church" ? t.sentToChurch : t.st[r.status]; +} + /** The change to send for a consent row: an address goes as its parts. */ export const changeFor = (r: ConsentRow & { parts?: Record }) => ({ field: r.field, value: r.parts ?? r.value.trim() }); diff --git a/packages/sdk/src/element.ts b/packages/sdk/src/element.ts index dc5103c..2987e90 100644 --- a/packages/sdk/src/element.ts +++ b/packages/sdk/src/element.ts @@ -2,7 +2,7 @@ // form-associated element: with a `name`, the chosen church's ID submits like any input. /// import { createLookup, type AddResult, type ChurchRecord, type FieldStatus, type Lookup, type LookupError, type Meta, type NewChurch, type SearchResult } from "./client.ts"; -import { addUrl, applyFill, changeFor, consentDiff, contributable, createLookupController, fieldValue, findTargets, isStale, mergeAddress, newChurchFrom, planFill, suggestUrl, type ControllerState, type FillChange } from "./core.ts"; +import { addUrl, applyFill, changeFor, consentBadge, consentDiff, contributable, createLookupController, fieldValue, findTargets, isStale, mergeAddress, newChurchFrom, planFill, resultText, suggestUrl, type ControllerState, type FillChange } from "./core.ts"; import { setNativeValue, type FieldTarget } from "./dom.ts"; import { devWarn } from "./dev.ts"; import { matchField } from "./fields.ts"; @@ -77,7 +77,7 @@ const Base = (typeof HTMLElement === "undefined" ? class {} : HTMLElement) as ty /** `detail` of church-error: what failed (a search, or loading a church) and why. */ export interface ChurchErrorDetail { query?: string; id?: string; status?: number; code?: string; retryAfter?: number; error: unknown } -interface WatchRow { field: string; el: FieldTarget; label: string; was: string; review: "live" | "moderated"; soon: boolean } +interface WatchRow { field: string; el: FieldTarget; label: string; was: string; soon: boolean } type Row = WatchRow & { value: string; parts?: Record }; interface Snapshot { id: string; record: ChurchRecord; rows: WatchRow[]; sent: Map; dismissed: string; confirmed: boolean; @@ -524,7 +524,7 @@ export class ChurchLookup extends Base { const rule = contributable(meta, field, country); if (!rule) continue; const label = (el.labels?.[0]?.textContent ?? el.getAttribute("aria-label") ?? field).trim(); - rows.push({ field, el, label, was: (fieldValue(record, field) ?? "").trim(), review: rule.review, soon: rule.status === "coming_soon" }); + rows.push({ field, el, label, was: (fieldValue(record, field) ?? "").trim(), soon: rule.status === "coming_soon" }); } const reports = (["reportClosed", "reportDuplicate", "reportRelocated"] as const).filter((f) => contributable(meta, f, country)); const render = () => this.renderPanel(); @@ -572,7 +572,7 @@ export class ChurchLookup extends Base { return ex; } - private renderPanel(result?: Map, sandbox?: boolean): void { + private renderPanel(result?: Map, sandbox?: boolean): void { const s = this.snap; const p = this.panel; if (!s) { p.hidden = true; return; } @@ -625,8 +625,9 @@ export class ChurchLookup extends Base { li.querySelector("s")!.textContent = r.was || "—"; li.querySelector("ins")!.textContent = res && !changed.includes(r) ? (s.sent.get(r.field) ?? r.value.trim()) : r.value.trim(); const b = li.querySelector(".b")!; - b.textContent = res ? (res.message && res.status === "rejected" ? `${t.st.rejected}: ${res.message}` : t.st[res.status]) : r.soon ? t.soon : r.review === "moderated" ? t.reviewed : t.goesLive; - b.classList.toggle("m", r.soon || r.review === "moderated" || (Boolean(res) && res!.status !== "live")); + const badge = consentBadge(t, r, r.soon, s.record.claimed); + b.textContent = res ? resultText(t, res) : badge.text; + b.classList.toggle("m", res ? res.status !== "live" : !badge.live); ul.append(li); }); count(); @@ -652,7 +653,7 @@ export class ChurchLookup extends Base { if (!this.dispatchEvent(new CustomEvent("church-contribute", { detail: { churchId: s.id, changes }, cancelable: true, bubbles: true, composed: true }))) return; const btn = this.panel.querySelector(".row .bt"); if (btn && !report) { btn.disabled = true; btn.textContent = this.t.sending; } - let out: { sandbox?: boolean; results: { field: string; status: FieldStatus; message?: string }[] }; + let out: { sandbox?: boolean; results: { field: string; status: FieldStatus; message?: string; reviewBy?: string }[] }; try { out = await this.client().contribute(s.id, changes); } catch { out = { results: changes.map((c) => ({ field: c.field, status: "try_again" as const })) }; } if (this.snap !== s) return; @@ -669,7 +670,7 @@ export class ChurchLookup extends Base { for (const c of changes) if (result.get(c.field)?.status !== "try_again") s.sent.set(c.field, rows.find((r) => r.field === c.field)?.value.trim() ?? String(c.value)); this.renderPanel(result, out.sandbox); const done = out.results.filter((r) => r.status === "live" || r.status === "in_review").length; - this.say(`${t.shared(done)} ${out.results.map((r) => `${r.field}: ${t.st[r.status]}`).join(". ")}.`); + this.say(`${t.shared(done)} ${out.results.map((r) => `${r.field}: ${resultText(t, r)}`).join(". ")}.`); } private sendShare(): Promise { diff --git a/packages/sdk/src/strings-de.ts b/packages/sdk/src/strings-de.ts index c361212..b6063c5 100644 --- a/packages/sdk/src/strings-de.ts +++ b/packages/sdk/src/strings-de.ts @@ -28,6 +28,9 @@ const strings: Strings = { notNow: "Nicht jetzt", goesLive: "Sofort sichtbar", reviewed: "Wird moderiert", + checked: "Wird automatisch geprüft", + churchReviews: "Die Gemeinde prüft das", + sentToChurch: "An die Gemeinde gesendet", soon: "Bald verfügbar", st: { live: "Jetzt sichtbar", in_review: "Zur Prüfung gesendet", not_applied: "Nicht geändert: Here's My Church behält den bisherigen Wert", rejected: "Nicht angenommen", try_again: "Senden fehlgeschlagen. Bitte gleich noch einmal versuchen.", coming_soon: "Bald verfügbar" }, shared: (n) => `${n} ${n === 1 ? "Änderung" : "Änderungen"} geteilt.`, diff --git a/packages/sdk/src/strings-es.ts b/packages/sdk/src/strings-es.ts index d840af7..e10e933 100644 --- a/packages/sdk/src/strings-es.ts +++ b/packages/sdk/src/strings-es.ts @@ -28,6 +28,9 @@ const strings: Strings = { notNow: "Ahora no", goesLive: "Se publica", reviewed: "Lo revisa un moderador", + checked: "Se revisa automáticamente", + churchReviews: "La iglesia lo revisa", + sentToChurch: "Enviado a la iglesia", soon: "Próximamente", st: { live: "Publicado", in_review: "Enviado a revisión", not_applied: "Sin cambios: Here's My Church mantuvo el dato publicado", rejected: "No aceptado", try_again: "No se pudo enviar. Inténtalo en un momento.", coming_soon: "Próximamente" }, shared: (n) => `${n} ${n === 1 ? "cambio compartido" : "cambios compartidos"}.`, diff --git a/packages/sdk/src/strings-fr.ts b/packages/sdk/src/strings-fr.ts index de6263c..0189a8e 100644 --- a/packages/sdk/src/strings-fr.ts +++ b/packages/sdk/src/strings-fr.ts @@ -28,6 +28,9 @@ const strings: Strings = { notNow: "Pas maintenant", goesLive: "Publié aussitôt", reviewed: "Un modérateur vérifie", + checked: "Vérifié automatiquement", + churchReviews: "L'église le vérifie", + sentToChurch: "Envoyé à l'église", soon: "Bientôt", st: { live: "Publié", in_review: "Envoyé pour vérification", not_applied: "Inchangé : Here's My Church a gardé la valeur publiée", rejected: "Non accepté", try_again: "Envoi impossible. Réessayez dans un instant.", coming_soon: "Bientôt" }, shared: (n) => `${n} ${n === 1 ? "modification partagée" : "modifications partagées"}.`, diff --git a/packages/sdk/src/strings-pl.ts b/packages/sdk/src/strings-pl.ts index a795028..b52822c 100644 --- a/packages/sdk/src/strings-pl.ts +++ b/packages/sdk/src/strings-pl.ts @@ -30,6 +30,9 @@ const strings: Strings = { notNow: "Nie teraz", goesLive: "Od razu widoczne", reviewed: "Sprawdza moderator", + checked: "Sprawdzane automatycznie", + churchReviews: "Sprawdza kościół", + sentToChurch: "Wysłano do kościoła", soon: "Wkrótce", st: { live: "Widoczne", in_review: "Wysłano do sprawdzenia", not_applied: "Bez zmian: Here's My Church zachował obecną wartość", rejected: "Nie przyjęto", try_again: "Nie udało się wysłać. Spróbuj za chwilę.", coming_soon: "Wkrótce" }, shared: (n) => `Udostępniono zmiany: ${n}.`, diff --git a/packages/sdk/src/strings-pt.ts b/packages/sdk/src/strings-pt.ts index 38fafef..a5fd40c 100644 --- a/packages/sdk/src/strings-pt.ts +++ b/packages/sdk/src/strings-pt.ts @@ -28,6 +28,9 @@ const strings: Strings = { notNow: "Agora não", goesLive: "Publicado na hora", reviewed: "Um moderador revisa", + checked: "Verificado automaticamente", + churchReviews: "A igreja revisa isto", + sentToChurch: "Enviado para a igreja", soon: "Em breve", st: { live: "Publicado", in_review: "Enviado para revisão", not_applied: "Sem mudança: o Here's My Church manteve o dado publicado", rejected: "Não aceito", try_again: "Não foi possível enviar. Tente de novo em instantes.", coming_soon: "Em breve" }, shared: (n) => `${n} ${n === 1 ? "mudança compartilhada" : "mudanças compartilhadas"}.`, diff --git a/packages/sdk/src/strings.ts b/packages/sdk/src/strings.ts index 54d8648..38846ea 100644 --- a/packages/sdk/src/strings.ts +++ b/packages/sdk/src/strings.ts @@ -31,7 +31,14 @@ export interface Strings { share: string; notNow: string; goesLive: string; + /** No longer shown: replacements say `checked`. Kept so existing overrides still type-check. */ reviewed: string; + /** A replacement, which Here's My Church checks automatically. */ + checked: string; + /** Any change on a listing the church has claimed. */ + churchReviews: string; + /** After sending, a change held for the church to review. */ + sentToChurch: string; soon: string; st: { live: string; in_review: string; not_applied: string; rejected: string; try_again: string; coming_soon: string }; shared: (n: number) => string; @@ -94,6 +101,9 @@ export const EN: Strings = { notNow: "Not now", goesLive: "Goes live", reviewed: "A moderator reviews it", + checked: "Checked automatically", + churchReviews: "The church reviews this", + sentToChurch: "Sent to the church", soon: "Coming soon", st: { live: "Live now", in_review: "Sent for review", not_applied: "Not changed: Here's My Church kept the listed value", rejected: "Not accepted", try_again: "Couldn't send. Try again shortly.", coming_soon: "Coming soon" }, shared: (n) => `Shared ${n} ${n === 1 ? "change" : "changes"}.`, diff --git a/packages/sdk/test/core.test.ts b/packages/sdk/test/core.test.ts index 70f50a4..f7c07e2 100644 --- a/packages/sdk/test/core.test.ts +++ b/packages/sdk/test/core.test.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { addUrl, changeFor, isStale, mergeAddress, newChurchFrom, suggestUrl, STALE_MS } from "../src/core.ts"; -import { consentDiff, contributable, createLookup, createLookupController, fieldValue, fillTargets, findTargets, planFill, type ControllerState } from "../src/core.ts"; +import { consentBadge, consentDiff, contributable, EN, resultText, createLookup, createLookupController, fieldValue, fillTargets, findTargets, planFill, type ControllerState } from "../src/core.ts"; const result = (id: string, name: string) => ({ id, name, label: name, locationLabel: "Dallas, Texas", street: null, city: "Dallas", nearestPlace: null, region: "TX", regionName: "Texas", country: "US", countryName: "United States", latitude: 1, longitude: 2, denomination: null, completeness: 50, distanceKm: null, band: 1, source: "lexical" as const }); const record = { @@ -367,6 +367,20 @@ describe("consent", () => { expect(changeFor(merged[0]!)).toEqual({ field: "phone", value: "2" }); expect(mergeAddress([{ field: "phone", was: "", value: "" }])).toHaveLength(1); }); + it("badges a blank field as going live, a replacement as checked, and a claimed listing as the church's", () => { + expect(consentBadge(EN, { field: "phone", was: "" }, false)).toEqual({ text: "Goes live", live: true }); + expect(consentBadge(EN, { field: "phone", was: "555" }, false)).toEqual({ text: "Checked automatically", live: false }); + // Email and pastor name are always held, even into a blank field. + expect(consentBadge(EN, { field: "email", was: "" }, false).text).toBe("Checked automatically"); + expect(consentBadge(EN, { field: "phone", was: "" }, false, true)).toEqual({ text: "The church reviews this", live: false }); + expect(consentBadge(EN, { field: "name", was: "A" }, true, true).text).toBe("Coming soon"); + }); + it("says a change held for the church was sent to the church", () => { + expect(resultText(EN, { status: "in_review", reviewBy: "church" })).toBe("Sent to the church"); + expect(resultText(EN, { status: "in_review" })).toBe("Sent for review"); + expect(resultText(EN, { status: "rejected", message: "Too long" })).toBe("Not accepted: Too long"); + expect(resultText(EN, { status: "try_again", reviewBy: "church" })).toBe(EN.st.try_again); + }); }); describe("Here's My Church", () => { diff --git a/packages/sdk/test/element.test.ts b/packages/sdk/test/element.test.ts index c52f8fb..6175d8a 100644 --- a/packages/sdk/test/element.test.ts +++ b/packages/sdk/test/element.test.ts @@ -553,7 +553,8 @@ describe("consent", () => { expect([...boxes].map((b) => b.checked)).toEqual([true, true]); expect(panel.textContent).toContain("https://grace.example"); expect(panel.textContent).toContain("https://new.example"); - expect(panel.textContent).toContain("A moderator reviews it"); + // A replacement is checked automatically; filling a blank field goes live. + expect([...panel.querySelectorAll("ul .b")].map((b) => b.textContent)).toEqual(["Checked automatically", "Goes live"]); const share = panel.querySelector(".row .bt")!; expect(share.textContent).toBe("Share 2 fixes"); expect(posts).toHaveLength(0); @@ -567,6 +568,16 @@ describe("consent", () => { await flush(10); expect(posts[0]!.body.changes).toEqual([{ field: "denomination", value: "Methodist" }]); }); + it("says the church reviews changes to a claimed listing, and that they were sent to the church", async () => { + recordExtra = { claimed: true }; + const { input, panel } = mountConsent("", { churchId: "R-1", results: [{ field: "denomination", status: "in_review", reviewBy: "church" }] }); + await pick(input); + edit("d", "Baptist"); + expect(panel.querySelector("ul .b")!.textContent).toBe("The church reviews this"); + panel.querySelector(".row .bt")!.click(); + await flush(10); + expect(panel.querySelector("ul .b")!.textContent).toBe("Sent to the church"); + }); it("asks Still correct only of a listing nobody confirmed this year", async () => { recordExtra = { freshness: { lastVerified: Date.now() - 30 * 864e5 } }; const fresh = mountConsent(); diff --git a/registry/components/church-consent.tsx b/registry/components/church-consent.tsx index 17da7b4..d8a75c5 100644 --- a/registry/components/church-consent.tsx +++ b/registry/components/church-consent.tsx @@ -1,8 +1,9 @@ "use client" // ChurchConsent: after a ChurchLookup fill, offer to share the person's corrections back to Here's My -// Church. Changed fields start checked, each says whether it goes live or waits for a moderator, and -// nothing is sent until they choose Share (or submit the form with a checked data-hmc-share box). +// Church. Changed fields start checked, each says whether it goes live, is checked automatically or +// goes to the church first (a claimed listing), and nothing is sent until they choose Share (or +// submit the form with a checked data-hmc-share box). // When nothing changed, it asks "Still correct?" of listings nobody confirmed this year. It also // offers "Report a problem" and a link to fix anything else on Here's My Church. import * as React from "react" @@ -13,12 +14,14 @@ import { Checkbox } from "@/components/ui/checkbox" import { cn } from "@/lib/utils" import { changeFor, + consentBadge, consentDiff, contributable, createLookup, fieldValue, isStale, mergeAddress, + resultText, stringsFor, suggestUrl, type ChurchRecord, @@ -42,7 +45,7 @@ export interface ChurchConsentProps { client?: string baseUrl?: string lookup?: Lookup - onShared?: (results: { field: string; status: FieldStatus; message?: string }[], sandbox: boolean) => void + onShared?: (results: { field: string; status: FieldStatus; message?: string; reviewBy?: "church" }[], sandbox: boolean) => void /** Text language, such as "es". Defaults to the page's. Load other languages with @/lib/lookup-strings. */ lang?: string /** Override any text. */ @@ -50,7 +53,7 @@ export interface ChurchConsentProps { className?: string } -type Result = { status: FieldStatus; message?: string } +type Result = { status: FieldStatus; message?: string; reviewBy?: "church" } const REPORTS = ["reportClosed", "reportDuplicate", "reportRelocated"] as const export function ChurchConsent({ record, values, labels = {}, client, baseUrl, lookup: own, onShared, lang, strings, className }: ChurchConsentProps) { @@ -152,7 +155,7 @@ export function ChurchConsent({ record, values, labels = {}, client, baseUrl, lo if (!picked.length) return const changes = picked.map(changeFor) setBusy(true) - let out: { sandbox?: boolean; results: { field: string; status: FieldStatus; message?: string }[] } + let out: { sandbox?: boolean; results: { field: string; status: FieldStatus; message?: string; reviewBy?: "church" }[] } try { out = await lookup.contribute(record!.id, changes) } catch { @@ -215,9 +218,8 @@ export function ChurchConsent({ record, values, labels = {}, client, baseUrl, lo const soon = r.rule.status === "coming_soon" const id = `${uid}-${r.field}` const label = r.parts ? t.address : r.label - const badge = res - ? res.status === "rejected" && res.message ? `${t.st.rejected}: ${res.message}` : t.st[res.status] - : soon ? t.soon : r.rule.review === "moderated" ? t.reviewed : t.goesLive + const before = consentBadge(t, r, soon, record.claimed) + const badge = res ? resultText(t, res) : before.text return (
  • {r.was || "—"} {sent.get(r.field) ?? r.value.trim()} - {badge} + {badge}
  • ) })} diff --git a/registry/lib/lookup-core.ts b/registry/lib/lookup-core.ts index 5f01f4c..ce9e29f 100644 --- a/registry/lib/lookup-core.ts +++ b/registry/lib/lookup-core.ts @@ -127,6 +127,8 @@ export interface ChurchRecord { hints: { nearestPlace: string | null }; /** The church's page on Here's My Church, where people can fix anything else. Add ?suggest=1 to open the form. */ links?: { heresMyChurch: string | null }; + /** The church has claimed its listing on Here's My Church. Others' changes go to the church first. */ + claimed?: boolean; attribution: string; } @@ -135,7 +137,8 @@ export type FieldStatus = "live" | "in_review" | "not_applied" | "rejected" | "t export interface ContributionResult { churchId: string; sandbox?: boolean; - results: { field: string; status: FieldStatus; message?: string }[]; + /** reviewBy "church": the change is held for the church itself to review (a claimed listing). */ + results: { field: string; status: FieldStatus; message?: string; reviewBy?: "church" }[]; } /** A church to add: record field names. Name, city and region (a code or name) are required. */ export interface NewChurch { @@ -148,7 +151,8 @@ export interface AddResult { status: "live" | "similar" | "rejected" | "try_agai export interface ConfirmResult { churchId: string; sandbox?: boolean; status: "confirmed" | FieldStatus; message?: string; lastVerified?: number } export interface Meta { fields: string[]; - contributableFields: Record; + /** `checks`: "automatic" fields are decided by Here's My Church's checks; "automatic-then-reviewer" ones go to a person when the checks can't decide; "reviewer" always does. */ + contributableFields: Record; completenessWeights: Record; /** Whether addChurch() takes new churches right now. */ addEnabled?: boolean; @@ -291,7 +295,14 @@ export interface Strings { share: string; notNow: string; goesLive: string; + /** No longer shown: replacements say `checked`. Kept so existing overrides still type-check. */ reviewed: string; + /** A replacement, which Here's My Church checks automatically. */ + checked: string; + /** Any change on a listing the church has claimed. */ + churchReviews: string; + /** After sending, a change held for the church to review. */ + sentToChurch: string; soon: string; st: { live: string; in_review: string; not_applied: string; rejected: string; try_again: string; coming_soon: string }; shared: (n: number) => string; @@ -354,6 +365,9 @@ export const EN: Strings = { notNow: "Not now", goesLive: "Goes live", reviewed: "A moderator reviews it", + checked: "Checked automatically", + churchReviews: "The church reviews this", + sentToChurch: "Sent to the church", soon: "Coming soon", st: { live: "Live now", in_review: "Sent for review", not_applied: "Not changed: Here's My Church kept the listed value", rejected: "Not accepted", try_again: "Couldn't send. Try again shortly.", coming_soon: "Coming soon" }, shared: (n) => `Shared ${n} ${n === 1 ? "change" : "changes"}.`, @@ -792,6 +806,24 @@ export function mergeAddress(rows: T[]): (T & { parts?: Re return rows.flatMap((r) => (r === parts[0] ? [address] : parts.includes(r) ? [] : [r])); } +/** Lookup always holds these, even into a blank field: a host form can hold someone's personal details. */ +const ALWAYS_HELD = ["email", "pastorName"]; + +/** + * What a consent row's badge says before sending: coming soon, the church reviews it (a claimed + * listing), goes live (a blank field), or checked automatically (a replacement). + */ +export function consentBadge(t: Strings, r: { field: string; was: string }, soon: boolean, claimed?: boolean): { text: string; live: boolean } { + const live = !soon && !claimed && !r.was.trim() && !ALWAYS_HELD.includes(r.field); + return { text: soon ? t.soon : claimed ? t.churchReviews : live ? t.goesLive : t.checked, live }; +} + +/** A sent field's outcome, as the badge shows it. */ +export function resultText(t: Strings, r: { status: FieldStatus; message?: string; reviewBy?: string }): string { + if (r.status === "rejected" && r.message) return `${t.st.rejected}: ${r.message}`; + return r.status === "in_review" && r.reviewBy === "church" ? t.sentToChurch : t.st[r.status]; +} + /** The change to send for a consent row: an address goes as its parts. */ export const changeFor = (r: ConsentRow & { parts?: Record }) => ({ field: r.field, value: r.parts ?? r.value.trim() }); diff --git a/registry/lib/lookup-strings.ts b/registry/lib/lookup-strings.ts index fca415a..ad5fa89 100644 --- a/registry/lib/lookup-strings.ts +++ b/registry/lib/lookup-strings.ts @@ -32,6 +32,9 @@ import { registerStrings, type Strings } from "@/lib/lookup-core" notNow: "Ahora no", goesLive: "Se publica", reviewed: "Lo revisa un moderador", + checked: "Se revisa automáticamente", + churchReviews: "La iglesia lo revisa", + sentToChurch: "Enviado a la iglesia", soon: "Próximamente", st: { live: "Publicado", in_review: "Enviado a revisión", not_applied: "Sin cambios: Here's My Church mantuvo el dato publicado", rejected: "No aceptado", try_again: "No se pudo enviar. Inténtalo en un momento.", coming_soon: "Próximamente" }, shared: (n) => `${n} ${n === 1 ? "cambio compartido" : "cambios compartidos"}.`, @@ -88,6 +91,9 @@ import { registerStrings, type Strings } from "@/lib/lookup-core" notNow: "Pas maintenant", goesLive: "Publié aussitôt", reviewed: "Un modérateur vérifie", + checked: "Vérifié automatiquement", + churchReviews: "L'église le vérifie", + sentToChurch: "Envoyé à l'église", soon: "Bientôt", st: { live: "Publié", in_review: "Envoyé pour vérification", not_applied: "Inchangé : Here's My Church a gardé la valeur publiée", rejected: "Non accepté", try_again: "Envoi impossible. Réessayez dans un instant.", coming_soon: "Bientôt" }, shared: (n) => `${n} ${n === 1 ? "modification partagée" : "modifications partagées"}.`, @@ -144,6 +150,9 @@ import { registerStrings, type Strings } from "@/lib/lookup-core" notNow: "Nicht jetzt", goesLive: "Sofort sichtbar", reviewed: "Wird moderiert", + checked: "Wird automatisch geprüft", + churchReviews: "Die Gemeinde prüft das", + sentToChurch: "An die Gemeinde gesendet", soon: "Bald verfügbar", st: { live: "Jetzt sichtbar", in_review: "Zur Prüfung gesendet", not_applied: "Nicht geändert: Here's My Church behält den bisherigen Wert", rejected: "Nicht angenommen", try_again: "Senden fehlgeschlagen. Bitte gleich noch einmal versuchen.", coming_soon: "Bald verfügbar" }, shared: (n) => `${n} ${n === 1 ? "Änderung" : "Änderungen"} geteilt.`, @@ -200,6 +209,9 @@ import { registerStrings, type Strings } from "@/lib/lookup-core" notNow: "Agora não", goesLive: "Publicado na hora", reviewed: "Um moderador revisa", + checked: "Verificado automaticamente", + churchReviews: "A igreja revisa isto", + sentToChurch: "Enviado para a igreja", soon: "Em breve", st: { live: "Publicado", in_review: "Enviado para revisão", not_applied: "Sem mudança: o Here's My Church manteve o dado publicado", rejected: "Não aceito", try_again: "Não foi possível enviar. Tente de novo em instantes.", coming_soon: "Em breve" }, shared: (n) => `${n} ${n === 1 ? "mudança compartilhada" : "mudanças compartilhadas"}.`, @@ -258,6 +270,9 @@ import { registerStrings, type Strings } from "@/lib/lookup-core" notNow: "Nie teraz", goesLive: "Od razu widoczne", reviewed: "Sprawdza moderator", + checked: "Sprawdzane automatycznie", + churchReviews: "Sprawdza kościół", + sentToChurch: "Wysłano do kościoła", soon: "Wkrótce", st: { live: "Widoczne", in_review: "Wysłano do sprawdzenia", not_applied: "Bez zmian: Here's My Church zachował obecną wartość", rejected: "Nie przyjęto", try_again: "Nie udało się wysłać. Spróbuj za chwilę.", coming_soon: "Wkrótce" }, shared: (n) => `Udostępniono zmiany: ${n}.`, diff --git a/scripts/build-index.ts b/scripts/build-index.ts index 4d1d02c..59a4450 100644 --- a/scripts/build-index.ts +++ b/scripts/build-index.ts @@ -110,8 +110,8 @@ function writeInserts(prefix: string, head: string, values: Iterable, ro writeFileSync(`${outDir}/000-schema.sql`, readFileSync(new URL("../worker/schema.sql", import.meta.url), "utf8")); const counts: Record = {}; counts.church = writeInserts("100-church", - "INSERT INTO church (rowid,id,short_id,name,street,city,near,postal_code,region,country,lat,lng,phone,email,website,denomination,service_times,languages,ministries,pastor_name,last_verified,completeness,doc_hash,embed_hash) VALUES", - docs.map((d, i) => `(${i + 1},${q(d.id)},${q(d.shortId)},${q(d.name)},${q(d.street)},${q(d.city)},${q(d.near)},${q(d.postalCode)},${q(d.region)},${q(d.country)},${n(d.lat)},${n(d.lng)},${q(d.phone)},${q(d.email)},${q(d.website)},${q(d.denomination)},${q(d.serviceTimes)},${list(d.languages)},${list(d.ministries)},${q(d.pastorName)},${n(d.lastVerified)},${d.completeness},${q(d.docHash)},${q(d.embedHash)})`)); + "INSERT INTO church (rowid,id,short_id,name,street,city,near,postal_code,region,country,lat,lng,phone,email,website,denomination,service_times,languages,ministries,pastor_name,last_verified,completeness,doc_hash,embed_hash,claimed) VALUES", + docs.map((d, i) => `(${i + 1},${q(d.id)},${q(d.shortId)},${q(d.name)},${q(d.street)},${q(d.city)},${q(d.near)},${q(d.postalCode)},${q(d.region)},${q(d.country)},${n(d.lat)},${n(d.lng)},${q(d.phone)},${q(d.email)},${q(d.website)},${q(d.denomination)},${q(d.serviceTimes)},${list(d.languages)},${list(d.ministries)},${q(d.pastorName)},${n(d.lastVerified)},${d.completeness},${q(d.docHash)},${q(d.embedHash)},${d.claimed ? 1 : 0})`)); counts.church_fts = writeInserts("200-fts", "INSERT INTO church_fts (rowid,name,loc,geo) VALUES", docs.map((d, i) => `(${i + 1},${q(tokenize(d.name).join(" "))},${q(tokenize(d.loc).join(" "))},${q(d.geo)})`)); const places = [...placeMap.values()].sort((a, b) => b.n - a.n); diff --git a/worker/migrations-m4.sql b/worker/migrations-m4.sql new file mode 100644 index 0000000..3ce7846 --- /dev/null +++ b/worker/migrations-m4.sql @@ -0,0 +1,2 @@ +-- Claimed listings: 1 when the church has verified its listed inbox on Here's My Church. +ALTER TABLE church ADD COLUMN claimed INTEGER NOT NULL DEFAULT 0; diff --git a/worker/schema.sql b/worker/schema.sql index 97dd5c6..590a8df 100644 --- a/worker/schema.sql +++ b/worker/schema.sql @@ -22,7 +22,8 @@ CREATE TABLE church ( last_verified INTEGER, completeness INTEGER NOT NULL, doc_hash TEXT NOT NULL, - embed_hash TEXT NOT NULL + embed_hash TEXT NOT NULL, + claimed INTEGER NOT NULL DEFAULT 0 ); CREATE INDEX church_region ON church(region); CREATE VIRTUAL TABLE church_fts USING fts5(name, loc, geo, prefix='1 2 3 4 5 6 7 8', tokenize='unicode61 remove_diacritics 2'); diff --git a/worker/src/contribute.ts b/worker/src/contribute.ts index af23590..ebf3a99 100644 --- a/worker/src/contribute.ts +++ b/worker/src/contribute.ts @@ -1,13 +1,16 @@ // Contributions and confirmations: people's corrections flow back to Here's My Church through its // internal Lookup routes. Every field gets its own status so the widget can say exactly what happened: -// live applied now (fields that go live on one vote) -// in_review waits for a Here's My Church moderator +// live applied now (a blank field filled, or a change Here's My Church's checks approved at once) +// in_review held: checked automatically, or by the church when it has claimed its listing, with a +// Here's My Church reviewer for whatever the checks can't decide // not_applied accepted, but the stored value didn't change (consensus kept the old one) // rejected Here's My Church refused it (a 4xx), with its reason // try_again a temporary problem (maintenance, rate limit, outage): nothing was lost or refused // coming_soon a field Lookup will accept once Here's My Church does (name, until it deploys) // A change that goes live comes back with the updated church, which is written straight into D1 so // search and the record show it before the next sync. Adding a church works the same way. +// A held result can carry reviewBy: "church" when the church itself reviews it (a claimed listing). +// That's purely additive: the status is still in_review. import type { ExportChurch } from "./project.ts"; import { tokenize } from "./project.ts"; import { CONTRIBUTABLE_FIELDS } from "./record.ts"; @@ -31,7 +34,9 @@ export interface ContributeEnv { } export type FieldStatus = "live" | "in_review" | "not_applied" | "rejected" | "try_again" | "coming_soon"; -export interface FieldResult { field: string; status: FieldStatus; message?: string } +/** Who reviews a held change, when Here's My Church says. Only "church" so far: a claimed listing. */ +export type ReviewBy = "church"; +export interface FieldResult { field: string; status: FieldStatus; message?: string; reviewBy?: ReviewBy } const HMC = "https://api.heresmychurch.com/internal/lookup"; const CLIENT_RE = /^[a-z0-9][a-z0-9-]{1,39}$/; @@ -56,7 +61,7 @@ export const nameOpen = (env: ContributeEnv) => env.NAME_CONTRIBUTIONS === "true /** The contributable-field table for /v1/meta, with name marked coming soon until it's accepted. */ export function contributableFields(env: ContributeEnv) { - const out: Record = {}; + const out: Record = {}; for (const [k, v] of Object.entries(CONTRIBUTABLE_FIELDS)) out[k] = k === "name" && !nameOpen(env) ? { ...v, status: "coming_soon" } : { ...v }; return out; } @@ -87,12 +92,15 @@ async function errorText(res: Response): Promise { try { const b = (await res.json()) as { error?: string }; return b.error ?? `HTTP ${res.status}`; } catch { return `HTTP ${res.status}`; } } -/** Map one Here's My Church response to a field status. 503 and 429 are never "rejected". */ -export async function statusFrom(res: Response): Promise<{ status: FieldStatus; message?: string; church?: ExportChurch }> { +/** + * Map one Here's My Church response to a field status. 503 and 429 are never "rejected". + * `reviewBy` passes through when Here's My Church names who reviews a held change ("church"). + */ +export async function statusFrom(res: Response): Promise<{ status: FieldStatus; message?: string; reviewBy?: ReviewBy; church?: ExportChurch }> { if (res.ok) { - const b = (await res.json().catch(() => ({}))) as { applied?: boolean; needsModeration?: boolean; church?: ExportChurch }; + const b = (await res.json().catch(() => ({}))) as { applied?: boolean; needsModeration?: boolean; reviewBy?: unknown; church?: ExportChurch }; const status: FieldStatus = b.needsModeration ? "in_review" : b.applied ? "live" : "not_applied"; - return { status, ...(status === "live" && isExport(b.church) ? { church: b.church } : {}) }; + return { status, ...(b.reviewBy === "church" ? { reviewBy: "church" as const } : {}), ...(status === "live" && isExport(b.church) ? { church: b.church } : {}) }; } if (res.status === 503 || res.status === 429 || res.status >= 500) { return { status: "try_again", message: res.status === 429 ? "Too many changes right now. Try again later." : "Here's My Church is busy for a moment. Try again shortly." }; @@ -237,7 +245,8 @@ export async function contribute(env: ContributeEnv, id: string, ip: string, inp if (p.result) continue; const review = CONTRIBUTABLE_FIELDS[p.hmcField].review; // The demo client is checked like any other but never reaches Here's My Church. - if (sandbox) { p.result = { status: review === "moderated" ? "in_review" : "live" }; continue; } + // On a claimed listing everything goes to the church first, as Here's My Church would hold it. + if (sandbox) { p.result = row.claimed ? { status: "in_review", reviewBy: "church" } : { status: review === "moderated" ? "in_review" : "live" }; continue; } try { const res = await postHmc(env, "/suggestions", { client, ipHash: hash, churchId: id, field: p.hmcField, value: p.value }, wait); const { church, ...status } = await statusFrom(res); diff --git a/worker/src/project.ts b/worker/src/project.ts index 88a9ce5..181664f 100644 --- a/worker/src/project.ts +++ b/worker/src/project.ts @@ -24,6 +24,8 @@ export interface ExportChurch { listingStatus?: string; relocatedTo?: string; relocatedFrom?: string; + /** Present and true when the church has verified its listed inbox. Absent otherwise. */ + claimed?: boolean; } export interface RegionInfo { @@ -52,6 +54,7 @@ export interface ProjectedChurch { ministries: string[]; pastorName: string | null; lastVerified: number | null; + claimed: boolean; completeness: number; loc: string; geo: string; @@ -291,12 +294,15 @@ export function project(c: ExportChurch, region: string, info: RegionInfo, near: pastorName: clean(c.pastorName), lastVerified: Number.isFinite(c.lastVerified) ? (c.lastVerified as number) : null, }; + const claimed = c.claimed === true; return { ...base, + claimed, completeness: completeness(base), loc: locText(base, info), geo: geoText(c.lat, c.lng, c.country, region), - docHash: hash64(JSON.stringify(base)), + // Only a claimed row hashes the flag, so unclaimed rows keep the hashes they had before it existed. + docHash: hash64(JSON.stringify(claimed ? { ...base, claimed } : base)), embedHash: hash64(embedText(base, info)), }; } diff --git a/worker/src/record.ts b/worker/src/record.ts index 768bf7c..fd67b71 100644 --- a/worker/src/record.ts +++ b/worker/src/record.ts @@ -9,6 +9,8 @@ export interface ChurchRow { region: string; country: string; lat: number; lng: number; phone: string | null; email: string | null; website: string | null; denomination: string | null; service_times: string | null; languages: string | null; ministries: string | null; pastor_name: string | null; last_verified: number | null; completeness: number; + /** 1 when the church has verified its listed inbox on Here's My Church. Absent before the m4 migration. */ + claimed?: number | null; } const list = (v: string | null): string[] => { @@ -52,6 +54,8 @@ export function toRecord(r: ChurchRow) { missing, completeness: r.completeness, freshness: { lastVerified: r.last_verified }, + // The church has claimed its listing (verified its listed inbox). Others' changes go to the church first. + claimed: r.claimed === 1, // The church's page, where people can fix anything Lookup doesn't take. Add ?suggest=1 to open the form. links: { heresMyChurch: r.short_id ? `${HMC_SITE}/${r.country}/${r.region}/${encodeURIComponent(r.short_id)}` : null }, // Values that aren't facts about the listing. A host must never fill `city` from nearestPlace. @@ -60,26 +64,42 @@ export function toRecord(r: ChurchRow) { } /** - * What a person can update through Lookup, and how it's reviewed. "live" goes live on one vote; - * "moderated" waits for a Here's My Church moderator. Email and pastor name are always moderated, - * since a host form can hold someone's personal details. `address` is street, city and postal code - * sent together. The report* fields flag a listing as closed, a duplicate or moved, and never go - * live without a moderator. `name` needs NAME_CONTRIBUTIONS before contributions accept it. + * What a person can update through Lookup, and how Here's My Church checks it. `address` is street, + * city and postal code sent together; `name` needs NAME_CONTRIBUTIONS before contributions accept it. + * + * On a claimed listing (`claimed: true` on the record), everyone else's changes go to the church + * first, and the answer says reviewBy: "church". Otherwise: + * - A blank field goes live on one vote, with an automatic spam check afterwards. Email and pastor + * name sent from Lookup are the exception: they're always held, since a host form can hold + * someone's personal details. + * - Replacing a filled value is held and checked automatically. Phone and service times are approved + * when they appear on the church's website, when two or more independent people send the same + * value, or after three quiet days. Denomination, languages and ministries (additions only) follow + * agreement, the name rules or three quiet days. + * - Name, website, address, email and pastor name need evidence (the church's website, a small name + * fix, an address within 150 m of the pin) or else a Here's My Church reviewer. + * - Closed and duplicate reports can hide a listing, reversibly, and only on strong evidence. Moves + * always go to a reviewer. + * + * `checks` says that: "automatic" fields are decided by the checks above; "automatic-then-reviewer" + * fields go to a person whenever the checks can't decide; "reviewer" (moves) always goes to one. `review` is kept as it was for hosts that + * read it: "live" for fields that can change without a person, "moderated" for the others. It no + * longer means a moderator sees every change. */ export const CONTRIBUTABLE_FIELDS = { - name: { countries: "all", review: "moderated" }, - serviceTimes: { countries: "all", review: "live" }, - denomination: { countries: "all", review: "live" }, - languages: { countries: "all", review: "live" }, - ministries: { countries: "all", review: "live" }, - phone: { countries: "all", review: "live" }, - website: { countries: "all", review: "moderated" }, - address: { countries: "all", review: "moderated" }, - email: { countries: "all", review: "moderated" }, - pastorName: { countries: "all", review: "moderated" }, - reportClosed: { countries: "all", review: "moderated" }, - reportDuplicate: { countries: "all", review: "moderated" }, - reportRelocated: { countries: "all", review: "moderated" }, + name: { countries: "all", review: "moderated", checks: "automatic-then-reviewer" }, + serviceTimes: { countries: "all", review: "live", checks: "automatic" }, + denomination: { countries: "all", review: "live", checks: "automatic" }, + languages: { countries: "all", review: "live", checks: "automatic" }, + ministries: { countries: "all", review: "live", checks: "automatic" }, + phone: { countries: "all", review: "live", checks: "automatic" }, + website: { countries: "all", review: "moderated", checks: "automatic-then-reviewer" }, + address: { countries: "all", review: "moderated", checks: "automatic-then-reviewer" }, + email: { countries: "all", review: "moderated", checks: "automatic-then-reviewer" }, + pastorName: { countries: "all", review: "moderated", checks: "automatic-then-reviewer" }, + reportClosed: { countries: "all", review: "moderated", checks: "automatic-then-reviewer" }, + reportDuplicate: { countries: "all", review: "moderated", checks: "automatic-then-reviewer" }, + reportRelocated: { countries: "all", review: "moderated", checks: "reviewer" }, } as const; export const RECORD_FIELDS = ["name", "street", "city", "region", "regionName", "postalCode", "country", "countryName", "latitude", "longitude", "phone", "email", "website", "denomination", "serviceTimes", "languages", "ministries", "pastorName"]; diff --git a/worker/src/sync.ts b/worker/src/sync.ts index 9de9824..0c19f0a 100644 --- a/worker/src/sync.ts +++ b/worker/src/sync.ts @@ -73,10 +73,10 @@ async function nearestPlaces(db: D1Database, rows: ExportChurch[]): Promise (v.length ? JSON.stringify(v) : null); function churchStmt(db: D1Database, rid: number, d: ProjectedChurch): D1PreparedStatement { - return db.prepare(`INSERT OR REPLACE INTO church (rowid,id,short_id,name,street,city,near,postal_code,region,country,lat,lng,phone,email,website,denomination,service_times,languages,ministries,pastor_name,last_verified,completeness,doc_hash,embed_hash) - VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`).bind( + return db.prepare(`INSERT OR REPLACE INTO church (rowid,id,short_id,name,street,city,near,postal_code,region,country,lat,lng,phone,email,website,denomination,service_times,languages,ministries,pastor_name,last_verified,completeness,doc_hash,embed_hash,claimed) + VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`).bind( rid, d.id, d.shortId, d.name, d.street, d.city, d.near, d.postalCode, d.region, d.country, d.lat, d.lng, d.phone, d.email, - d.website, d.denomination, d.serviceTimes, list(d.languages), list(d.ministries), d.pastorName, d.lastVerified, d.completeness, d.docHash, d.embedHash); + d.website, d.denomination, d.serviceTimes, list(d.languages), list(d.ministries), d.pastorName, d.lastVerified, d.completeness, d.docHash, d.embedHash, d.claimed ? 1 : 0); } /** The church row and its FTS row, replaced together. */ diff --git a/worker/test/api.test.ts b/worker/test/api.test.ts index fa7e2f6..e808f66 100644 --- a/worker/test/api.test.ts +++ b/worker/test/api.test.ts @@ -199,6 +199,7 @@ describe("churches", () => { expect(body.missing).toContain("phone"); expect(body.missing).not.toContain("website"); expect(body.fields.regionName).toBe("Texas"); + expect(body.claimed).toBe(false); }); it("reports moved ids", async () => expect((await get("/v1/churches/OLD-1")).body.movedTo).toBe("R-0")); it("404s unknown ids", async () => { @@ -212,10 +213,12 @@ describe("meta and routing", () => { it("serves meta", async () => { const { body } = await get("/v1/meta"); expect(body.completenessWeights.serviceTimes).toBe(25); - expect(body.contributableFields.email).toEqual({ countries: "all", review: "moderated" }); + expect(body.contributableFields.email).toEqual({ countries: "all", review: "moderated", checks: "automatic-then-reviewer" }); expect(body.contributableFields.pastorName.review).toBe("moderated"); expect(body.contributableFields.phone.countries).toBe("all"); - expect(body.contributableFields.address).toEqual({ countries: "all", review: "moderated" }); + expect(body.contributableFields.address).toEqual({ countries: "all", review: "moderated", checks: "automatic-then-reviewer" }); + expect(body.contributableFields.phone.checks).toBe("automatic"); + expect(body.contributableFields.reportRelocated.checks).toBe("reviewer"); expect(body.contributableFields.reportClosed.review).toBe("moderated"); expect(body.addEnabled).toBe(false); expect(body.contributableFields.name.review).toBe("moderated"); diff --git a/worker/test/contribute.test.ts b/worker/test/contribute.test.ts index 399fb8d..0fc2d5c 100644 --- a/worker/test/contribute.test.ts +++ b/worker/test/contribute.test.ts @@ -86,6 +86,27 @@ describe("contributions", () => { expect((still.body as any).results[0].status).toBe("try_again"); expect(b.calls).toHaveLength(2); }); + it("keeps a maintenance 503 as try again, even with a claimed-listing answer around it", async () => { + const { fetcher } = hmcStub(maintenance(), maintenance(), Response.json({ success: true, applied: false, needsModeration: true, reviewBy: "church" })); + const out = await contribute(makeEnv(fetcher), "R-0", "ip", { client: "acme", changes: [{ field: "denomination", value: "Anglican" }, { field: "ministries", value: "Choir" }] }, noWait); + const results = (out.body as any).results; + expect(results.map((r: any) => r.status)).toEqual(["try_again", "in_review"]); + expect(results[0].reviewBy).toBeUndefined(); + expect(results[0].message).toContain("busy"); + }); + it("passes reviewBy through when the church reviews a held change", async () => { + const { fetcher } = hmcStub( + Response.json({ success: true, applied: false, needsModeration: true, reviewBy: "church" }), + Response.json({ success: true, applied: false, needsModeration: true }), + Response.json({ success: true, applied: false, needsModeration: true, reviewBy: "someone-else" }), + ); + const out = await contribute(makeEnv(fetcher), "R-0", "ip", { client: "acme", changes: [{ field: "denomination", value: "Anglican" }, { field: "website", value: "https://w.example" }, { field: "ministries", value: "Choir" }] }, noWait); + expect((out.body as any).results).toEqual([ + { field: "denomination", status: "in_review", reviewBy: "church" }, + { field: "website", status: "in_review" }, + { field: "ministries", status: "in_review" }, + ]); + }); it("treats rate limits and outages as try again", async () => { const { fetcher } = hmcStub(Response.json({ error: "Too many" }, { status: 429 }), new Response("boom", { status: 502 })); const out = await contribute(makeEnv(fetcher), "R-0", "ip", { client: "acme", changes: [{ field: "denomination", value: "A" }, { field: "ministries", value: "Youth" }] }, noWait); @@ -175,6 +196,12 @@ describe("contributions", () => { expect((out.body as any).results.map((r: any) => r.status)).toEqual(["live", "in_review", "coming_soon"]); expect(calls).toHaveLength(0); }); + it("sandboxes a claimed listing as the church's to review", async () => { + await env.DB.prepare("UPDATE church SET claimed = 1 WHERE id = 'R-1'").run(); + const out = await contribute(makeEnv(), "R-1", "ip", { client: "lookup-demo", changes: [{ field: "denomination", value: "Baptist" }] }, noWait); + expect((out.body as any).results).toEqual([{ field: "denomination", status: "in_review", reviewBy: "church" }]); + await env.DB.prepare("UPDATE church SET claimed = 0 WHERE id = 'R-1'").run(); + }); }); describe("confirm", () => { diff --git a/worker/test/project.test.ts b/worker/test/project.test.ts index 0921a38..06b3460 100644 --- a/worker/test/project.test.ts +++ b/worker/test/project.test.ts @@ -114,6 +114,15 @@ describe("project", () => { expect(renamed.embedHash).not.toBe(a.embedHash); expect(project(base, "TX", info).docHash).toBe(a.docHash); }); + it("carries claimed, hashing it only when true so unclaimed rows keep their hashes", () => { + const a = project(base, "TX", info); + const claimed = project({ ...base, claimed: true }, "TX", info); + expect(a.claimed).toBe(false); + expect(claimed.claimed).toBe(true); + expect(claimed.docHash).not.toBe(a.docHash); + expect(claimed.embedHash).toBe(a.embedHash); + expect(project({ ...base, claimed: false }, "TX", info).docHash).toBe(a.docHash); + }); }); describe("geo", () => { diff --git a/worker/test/sync.test.ts b/worker/test/sync.test.ts index 0d450fa..bf82bdd 100644 --- a/worker/test/sync.test.ts +++ b/worker/test/sync.test.ts @@ -1,6 +1,7 @@ import { env } from "cloudflare:test"; import { beforeAll, describe, expect, it } from "vitest"; -import { pickRegions, tick } from "../src/sync.ts"; +import { toRecord, type ChurchRow } from "../src/record.ts"; +import { pickRegions, tick, writeChurch } from "../src/sync.ts"; import { seed } from "./seed.ts"; import schema from "../schema.sql?raw"; @@ -90,6 +91,25 @@ describe("tick", () => { expect(again.regions[0], JSON.stringify(again.regions[0])).toMatchObject({ inserted: 0, updated: 0, deleted: 0, embedQueued: 0 }); expect(upserts.flat()).toEqual([]); }); + it("carries claimed from the export into D1 and the record, and clears it when it's gone", async () => { + const exportTx = [ + tx("R-0", "Grace Community Church", { website: "https://grace.example", address: "1 Main, 75201", postcode: "75201", serviceTimes: "Sun 10:30 AM" }), + tx("R-2", "First Baptist Church of Dallas"), tx("R-4", "Saint Mary's Catholic Church"), tx("R-7", "Church at the Cross", { claimed: true }), + ]; + await tick(fakeEnv({ TX: exportTx }), ["TX"]); + const row = (id: string) => env.DB.prepare("SELECT * FROM church WHERE id = ?").bind(id).first(); + expect((await row("R-7"))!.claimed).toBe(1); + expect(toRecord((await row("R-7"))!).claimed).toBe(true); + expect(toRecord((await row("R-0"))!).claimed).toBe(false); + // Unclaimed: the field is simply absent from the export. + exportTx[3] = tx("R-7", "Church at the Cross"); + const again = await tick(fakeEnv({ TX: exportTx }), ["TX"]); + expect(again.regions[0]).toMatchObject({ updated: 1, embedQueued: 0 }); + expect(toRecord((await row("R-7"))!).claimed).toBe(false); + // A church written back after a contribution carries it too. + await writeChurch(env, tx("R-2", "First Baptist Church of Dallas", { claimed: true }) as never, "TX"); + expect(toRecord((await row("R-2"))!).claimed).toBe(true); + }); it("skips deletes when a region shrinks by more than half", async () => { const out = await tick(fakeEnv({ TX: [tx("R-0", "Grace Community Church")] }), ["TX"]); expect(out.regions[0]).toMatchObject({ deleted: 0, deletesSkipped: 4 });