Planning Center: compare a People list with the site's people and apply what an admin picks
Migration 085 adds people.pco_id and Site settings' list. Data -> Planning Center fetches the list, suggests matches (linked, same email, same name), shows each field that would change (Planning Center wins), and applies the chosen links, updates and new unpublished people in one transaction. Needs PCO_APP_ID and PCO_SECRET. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
a10ff6d75f
commit
e8aab4d7ec
12 changed files with 607 additions and 7 deletions
|
|
@ -40,6 +40,8 @@ export const siteSettings = {
|
|||
enumeration("word_motion", ["slide", "flip", "fade", "type", "mirror"]),
|
||||
enumeration("word_direction", ["top", "bottom"]),
|
||||
int("word_seconds"),
|
||||
// Data → Planning Center's list (085).
|
||||
text("pco_list_id"),
|
||||
],
|
||||
|
||||
children: [
|
||||
|
|
|
|||
|
|
@ -33,6 +33,7 @@ import requests from "./routes/requests.js";
|
|||
import auth from "./routes/auth.js";
|
||||
import account from "./routes/account.js";
|
||||
import profiles from "./routes/profiles.js";
|
||||
import pco from "./routes/pco.js";
|
||||
import admin from "./routes/admin.js";
|
||||
import panel from "./routes/panel.js";
|
||||
import adminEntities from "./routes/admin-entities.js";
|
||||
|
|
@ -223,6 +224,7 @@ app.use("/api/account/photo", rateLimit({ windowMs: 15 * 60_000, max: 20 }));
|
|||
app.route("/api/account", account);
|
||||
app.route("/api/admin", admin);
|
||||
app.route("/api/admin", profiles);
|
||||
app.route("/api/admin", pco);
|
||||
// Before the entity routes, whose /:entity would claim /media.
|
||||
app.route("/api/admin", media);
|
||||
app.route("/api/admin", imports);
|
||||
|
|
|
|||
17
server/src/migrations/085_planning_center.sql
Normal file
17
server/src/migrations/085_planning_center.sql
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
-- ═══════════════════════════════════════════════════════════════
|
||||
-- 085 PLANNING CENTER
|
||||
--
|
||||
-- Data → Planning Center brings one Planning Center People list into
|
||||
-- the site's people, by hand (planningCenter.js, routes/pco.js):
|
||||
--
|
||||
-- people.pco_id the Planning Center person a record is
|
||||
-- linked to, once an admin confirms the
|
||||
-- match; one record each
|
||||
-- site_settings.pco_list_id which list (Site settings → Planning
|
||||
-- Center), eg. 1234567
|
||||
-- ═══════════════════════════════════════════════════════════════
|
||||
|
||||
ALTER TABLE people ADD COLUMN pco_id TEXT;
|
||||
CREATE UNIQUE INDEX people_pco_id_idx ON people (pco_id) WHERE pco_id IS NOT NULL;
|
||||
|
||||
ALTER TABLE site_settings ADD COLUMN pco_list_id TEXT;
|
||||
199
server/src/planningCenter.js
Normal file
199
server/src/planningCenter.js
Normal file
|
|
@ -0,0 +1,199 @@
|
|||
/* ═══════════════════════════════════════════════════════════════
|
||||
PLANNING CENTER
|
||||
|
||||
One Planning Center People list into the site's people, by hand:
|
||||
Data → Planning Center (routes/pco.js) asks for the comparison,
|
||||
an admin reviews it, and only what they apply is written. Planning
|
||||
Center wins where both sides have a value. One way only: nothing
|
||||
is sent back.
|
||||
|
||||
name → people.display_name, and sort_name ("Last, First")
|
||||
email → person_private.private_email (the primary one)
|
||||
phone → person_private.private_phone (the primary one)
|
||||
|
||||
A person is matched by the Planning Center id it was linked to
|
||||
(people.pco_id, 085), else suggested by the same private or public
|
||||
email, else the same name; an admin confirms each suggestion, picks
|
||||
another person, or makes a new one, unpublished.
|
||||
|
||||
PCO_APP_ID a personal access token's application id
|
||||
PCO_SECRET and its secret (api.planningcenteronline.com →
|
||||
Personal Access Tokens); never in the repo
|
||||
PCO_BASE default https://api.planningcenteronline.com
|
||||
|
||||
The list is Site settings → Planning Center. Setup:
|
||||
docs/planning-center.md.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
const BASE = () => (process.env.PCO_BASE ?? "https://api.planningcenteronline.com").replace(/\/$/, "");
|
||||
const MAX_PAGES = 50; // 100 a page: a list of 5,000 is plenty
|
||||
|
||||
export const pcoReady = () => Boolean(process.env.PCO_APP_ID && process.env.PCO_SECRET);
|
||||
|
||||
export class PcoError extends Error {}
|
||||
|
||||
async function call(url) {
|
||||
const auth = Buffer.from(`${process.env.PCO_APP_ID}:${process.env.PCO_SECRET}`).toString("base64");
|
||||
let res;
|
||||
try {
|
||||
res = await fetch(url, { headers: { Authorization: `Basic ${auth}`, Accept: "application/json" }, signal: AbortSignal.timeout(20_000) });
|
||||
} catch {
|
||||
throw new PcoError("Couldn't reach Planning Center.");
|
||||
}
|
||||
if (res.status === 401) throw new PcoError("Planning Center refused the token (PCO_APP_ID and PCO_SECRET).");
|
||||
if (res.status === 404) throw new PcoError("Planning Center has no such list. Check Site settings → Planning Center.");
|
||||
if (!res.ok) throw new PcoError(`Planning Center answered ${res.status}.`);
|
||||
return res.json();
|
||||
}
|
||||
|
||||
/* Everyone on the list: { id, first, last, name, email, phone }. */
|
||||
export async function listPeople(listId) {
|
||||
if (!pcoReady()) throw new PcoError("Planning Center isn't set up on the server (PCO_APP_ID, PCO_SECRET).");
|
||||
if (!/^\d+$/.test(String(listId ?? ""))) throw new PcoError("Pick a list in Site settings → Planning Center (its number).");
|
||||
|
||||
const people = [];
|
||||
let url = `${BASE()}/people/v2/lists/${listId}/people?include=emails,phone_numbers&per_page=100`;
|
||||
for (let page = 0; url && page < MAX_PAGES; page++) {
|
||||
const body = await call(url);
|
||||
const included = new Map((body.included ?? []).map((row) => [`${row.type}:${row.id}`, row]));
|
||||
for (const row of body.data ?? []) {
|
||||
const pick = (type, key) => {
|
||||
const rows = (row.relationships?.[key]?.data ?? []).map((ref) => included.get(`${type}:${ref.id}`)).filter(Boolean);
|
||||
const main = rows.find((r) => r.attributes?.primary) ?? rows[0];
|
||||
return main?.attributes ?? null;
|
||||
};
|
||||
const a = row.attributes ?? {};
|
||||
const first = (a.nickname || a.first_name || "").trim();
|
||||
const last = (a.last_name || "").trim();
|
||||
people.push({
|
||||
id: String(row.id),
|
||||
first,
|
||||
last,
|
||||
name: [first, last].filter(Boolean).join(" ") || (a.name ?? "").trim(),
|
||||
email: pick("Email", "emails")?.address?.trim().toLowerCase() || null,
|
||||
phone: pick("PhoneNumber", "phone_numbers")?.number?.trim() || null,
|
||||
});
|
||||
}
|
||||
url = body.links?.next ?? null;
|
||||
}
|
||||
return people;
|
||||
}
|
||||
|
||||
const norm = (value) => String(value ?? "").trim().toLowerCase().replace(/\s+/g, " ");
|
||||
|
||||
/* The comparison: each list member with its match (linked, or a
|
||||
suggestion) and the fields that would change. */
|
||||
export function compare(db, members) {
|
||||
const site = db
|
||||
.prepare(
|
||||
`SELECT p.id, p.display_name, p.sort_name, p.public_email, p.pco_id,
|
||||
v.private_email, v.private_phone
|
||||
FROM people p LEFT JOIN person_private v ON v.person_id = p.id`,
|
||||
)
|
||||
.all();
|
||||
const byPco = new Map(site.filter((p) => p.pco_id).map((p) => [p.pco_id, p]));
|
||||
const byEmail = new Map();
|
||||
for (const p of site) {
|
||||
for (const email of [p.private_email, p.public_email]) if (email) byEmail.set(norm(email), p);
|
||||
}
|
||||
const byName = new Map(site.map((p) => [norm(p.display_name), p]));
|
||||
|
||||
return members.map((member) => {
|
||||
let person = byPco.get(member.id);
|
||||
let how = person ? "linked" : null;
|
||||
if (!person && member.email && byEmail.get(norm(member.email))) {
|
||||
person = byEmail.get(norm(member.email));
|
||||
how = "email";
|
||||
}
|
||||
if (!person && byName.get(norm(member.name))) {
|
||||
person = byName.get(norm(member.name));
|
||||
how = "name";
|
||||
}
|
||||
// A suggestion that's already some other Planning Center person's isn't one.
|
||||
if (person && how !== "linked" && person.pco_id && person.pco_id !== member.id) {
|
||||
person = null;
|
||||
how = null;
|
||||
}
|
||||
|
||||
const sortName = member.last ? `${member.last}, ${member.first}`.replace(/, $/, "") : null;
|
||||
const changes = person
|
||||
? [
|
||||
["display_name", "Name", person.display_name, member.name],
|
||||
["sort_name", "Sort name", person.sort_name, sortName],
|
||||
["private_email", "Private email", person.private_email, member.email],
|
||||
["private_phone", "Private phone", person.private_phone, member.phone],
|
||||
]
|
||||
.filter(([, , now, next]) => next && norm(now) !== norm(next))
|
||||
.map(([field, label, now, next]) => ({ field, label, site: now ?? null, pco: next }))
|
||||
: [];
|
||||
|
||||
return {
|
||||
pco: member,
|
||||
match: person ? { person_id: person.id, name: person.display_name, how } : null,
|
||||
changes,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
const slug = (text) =>
|
||||
String(text ?? "")
|
||||
.toLowerCase()
|
||||
.normalize("NFKD")
|
||||
.replace(/[^\w\s-]/g, "")
|
||||
.trim()
|
||||
.replace(/[\s_]+/g, "-")
|
||||
.replace(/-+/g, "-")
|
||||
.slice(0, 60) || "person";
|
||||
|
||||
function freeId(db, base) {
|
||||
let id = base;
|
||||
for (let n = 2; db.prepare(`SELECT 1 FROM people WHERE id = ?`).get(id); n++) id = `${base}-${n}`;
|
||||
return id;
|
||||
}
|
||||
|
||||
/* Writes what the admin chose, in one transaction (the caller's):
|
||||
each decision is { pco: member, action: 'link' | 'create',
|
||||
person_id, update }. Returns counts. */
|
||||
export function apply(db, decisions) {
|
||||
const counts = { linked: 0, created: 0, updated: 0 };
|
||||
const upsertPrivate = db.prepare(
|
||||
`INSERT INTO person_private (person_id, private_email, private_phone) VALUES (?, ?, ?)
|
||||
ON CONFLICT (person_id) DO UPDATE
|
||||
SET private_email = COALESCE(excluded.private_email, private_email),
|
||||
private_phone = COALESCE(excluded.private_phone, private_phone),
|
||||
updated_at = datetime('now')`,
|
||||
);
|
||||
|
||||
for (const d of decisions) {
|
||||
const m = d.pco;
|
||||
const sortName = m.last ? `${m.last}, ${m.first}`.replace(/, $/, "") : null;
|
||||
let personId = d.person_id;
|
||||
|
||||
if (d.action === "create") {
|
||||
personId = freeId(db, slug(m.name));
|
||||
db.prepare(
|
||||
`INSERT INTO people (id, display_name, sort_name, is_published, is_listed, pco_id) VALUES (?, ?, ?, 0, 1, ?)`,
|
||||
).run(personId, m.name || "Unnamed", sortName, m.id);
|
||||
upsertPrivate.run(personId, m.email, m.phone);
|
||||
counts.created += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (d.action !== "link" || !personId) continue;
|
||||
// A link moves: whoever had this Planning Center person lets go.
|
||||
db.prepare(`UPDATE people SET pco_id = NULL WHERE pco_id = ? AND id <> ?`).run(m.id, personId);
|
||||
db.prepare(`UPDATE people SET pco_id = ? WHERE id = ?`).run(m.id, personId);
|
||||
counts.linked += 1;
|
||||
|
||||
if (d.update) {
|
||||
db.prepare(
|
||||
`UPDATE people SET display_name = COALESCE(?, display_name), sort_name = COALESCE(?, sort_name),
|
||||
updated_at = datetime('now')
|
||||
WHERE id = ?`,
|
||||
).run(m.name || null, sortName, personId);
|
||||
upsertPrivate.run(personId, m.email, m.phone);
|
||||
counts.updated += 1;
|
||||
}
|
||||
}
|
||||
return counts;
|
||||
}
|
||||
79
server/src/routes/pco.js
Normal file
79
server/src/routes/pco.js
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
/* ═══════════════════════════════════════════════════════════════
|
||||
PLANNING CENTER ROUTES: Data → Planning Center, mounted under
|
||||
/api/admin, admins and up (planningCenter.js)
|
||||
|
||||
GET /pco whether it's set up, and the list's id
|
||||
POST /pco/compare the list, each member with its match and what
|
||||
would change; nothing is written
|
||||
POST /pco/apply { decisions: [{ pco, action, person_id, update }] }
|
||||
what the admin chose, in one transaction
|
||||
|
||||
The comparison is fetched again for apply's members rather than
|
||||
trusting the browser's copy of Planning Center's values: only the
|
||||
choices (which person, link or create, update or not) come from it.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { Hono } from "hono";
|
||||
|
||||
import { requireRole } from "../auth.js";
|
||||
import { tx } from "../db.js";
|
||||
import { PcoError, apply, compare, listPeople, pcoReady } from "../planningCenter.js";
|
||||
import { NO_STORE } from "../shape.js";
|
||||
|
||||
const pco = new Hono();
|
||||
|
||||
pco.use("/pco", requireRole("admin"));
|
||||
pco.use("/pco/*", requireRole("admin"));
|
||||
|
||||
const listId = (db) => db.prepare(`SELECT pco_list_id FROM site_settings WHERE id = 'site'`).get()?.pco_list_id ?? null;
|
||||
|
||||
pco.get("/pco", (c) => c.json({ ready: pcoReady(), list_id: listId(c.get("db")) }, 200, NO_STORE));
|
||||
|
||||
pco.post("/pco/compare", async (c) => {
|
||||
const db = c.get("db");
|
||||
try {
|
||||
const members = await listPeople(listId(db));
|
||||
return c.json({ rows: compare(db, members) }, 200, NO_STORE);
|
||||
} catch (err) {
|
||||
if (err instanceof PcoError) return c.json({ error: err.message }, 502, NO_STORE);
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
pco.post("/pco/apply", async (c) => {
|
||||
const db = c.get("db");
|
||||
let body;
|
||||
try {
|
||||
body = (await c.req.json()) ?? {};
|
||||
} catch {
|
||||
return c.json({ error: "Expected a JSON body." }, 400);
|
||||
}
|
||||
const chosen = Array.isArray(body.decisions) ? body.decisions : [];
|
||||
|
||||
let members;
|
||||
try {
|
||||
members = await listPeople(listId(db));
|
||||
} catch (err) {
|
||||
if (err instanceof PcoError) return c.json({ error: err.message }, 502, NO_STORE);
|
||||
throw err;
|
||||
}
|
||||
const byId = new Map(members.map((m) => [m.id, m]));
|
||||
const known = new Set(db.prepare(`SELECT id FROM people`).all().map((r) => r.id));
|
||||
|
||||
const decisions = chosen
|
||||
.map((d) => ({
|
||||
pco: byId.get(String(d?.pco_id ?? "")),
|
||||
action: d?.action === "create" ? "create" : d?.action === "link" ? "link" : null,
|
||||
person_id: d?.person_id && known.has(String(d.person_id)) ? String(d.person_id) : null,
|
||||
update: Boolean(d?.update),
|
||||
}))
|
||||
.filter((d) => d.pco && d.action && (d.action === "create" || d.person_id));
|
||||
|
||||
const counts = tx(db, () => apply(db, decisions));
|
||||
console.log(
|
||||
`pco sync by ${c.get("user").email}: ${counts.linked} linked, ${counts.updated} updated, ${counts.created} created`,
|
||||
);
|
||||
return c.json({ counts }, 200, NO_STORE);
|
||||
});
|
||||
|
||||
export default pco;
|
||||
Loading…
Add table
Add a link
Reference in a new issue