v1.14.0-profiles: profile accounts, drafts, page management, Planning Center #32
12 changed files with 607 additions and 7 deletions
|
|
@ -41,6 +41,7 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu
|
|||
- Security headers: the API sends them (Hono `secureHeaders()`, plus a CSRF check on `/api` writes); nginx sends HSTS on everything and must pass `Host` and `X-Forwarded-For` to the API: `docs/security-headers.md`.
|
||||
- Request form (`/request`): files go to the "Requests" folder of a Google shared drive and new-request emails go out through Gmail, both via a service account (`server/src/googleService.js`). `driveUpload(folder, ...)` finds or makes the named folder in the shared drive, so other uses get their own folder. Tools → Media → Files uploads to "Media" and shares each file as anyone-with-the-link (`server/src/routes/files.js`, migration 048); link fields with `files: true` pick from it ("Choose a file"), and link cards take its first-page preview. Needs a `/api/admin/files` nginx block (51m). Off until `GOOGLE_SERVICE_ACCOUNT` plus `GOOGLE_SHARED_DRIVE` (the bare id, not a URL) / `GOOGLE_MAIL_FROM` are set. Needs its own nginx block. Setup: `docs/google-drive-and-mail.md`.
|
||||
- Profile accounts (migration 076): admins invite an email (Data → Profile accounts), the person sets a password from the link or signs in with any Google account under that email, claims their People record (an admin approves), then edits it and hides parts at `/account`. Public reads of people go through the `v_people_public` view, never `people`. Discord linking is off until `DISCORD_CLIENT_ID` and `DISCORD_CLIENT_SECRET` are set: `docs/profile-accounts.md`.
|
||||
- Planning Center (migration 085): Data → Planning Center compares a Planning Center People list (Site settings → Planning Center) with the site's people and applies what an admin picks: link (`people.pco_id`), update the name and private email and phone, or add unpublished. Off until `PCO_APP_ID` and `PCO_SECRET` are set: `docs/planning-center.md`.
|
||||
- Google sign-in for @nextgenerationofunity.org admin accounts: on when `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` are set on the service. Accounts made by admin-cli get in; with access groups set (Site settings → Access, plus `GOOGLE_DIRECTORY_AS`), anyone in one gets a Google-only account whose role follows the group, rechecked at sign-in, hourly and by Panel → Re-sync now (`server/src/accessGroups.js`); superadmins and admin-cli accounts are never changed by groups. Passwords still work. Setup: `docs/google-sign-in.md`.
|
||||
|
||||
## Git workflow
|
||||
|
|
|
|||
10
TODO.md
10
TODO.md
|
|
@ -78,12 +78,6 @@
|
|||
## Admin
|
||||
|
||||
## Data
|
||||
- [ ] **Planning Center sync to People**: Planning Center People into the site's people records.
|
||||
- [ ] One way (Planning Center → site), or both? Answer: to site only
|
||||
- [ ] Who gets synced: everyone, or a Planning Center list or tag (eg. "Website")? Most people in Planning Center shouldn't have a public page. Answer:a specific list
|
||||
- [ ] Which fields: name, photo, email, phone, birthday? Which win when both sides differ? Answer: planning center. but show the comparasin (reconcile) for each user. Fields (2026-10-16): name, and email and phone into the private fields. Matching: suggested by email or name, an admin confirms, then remembered by Planning Center's id.
|
||||
- [ ] How often: a button in Data, hourly, nightly? Answer: manually only
|
||||
- [ ] Is there a Planning Center API app (personal access token) we can use, and which account owns it? Answer: use the API
|
||||
- [ ] **New Thought young adult directory**: the tabs are built (Part 2, Page features). Content: make the People tags (eg. Authors, Creators), tag people, and set Community's Directories section to them.
|
||||
|
||||
## Navigation
|
||||
|
|
@ -117,7 +111,9 @@
|
|||
|
||||
|
||||
# Part 2: Done
|
||||
## Page management (branch `page-management`, on top of `page-features`, no PR yet; migrations 080 to 084, back up the database before deploying)
|
||||
## Page management (branch `page-management`, on top of `page-features`, no PR yet; migrations 080 to 085, back up the database before deploying)
|
||||
- [x] **Planning Center sync** (Data, migration 085, `docs/planning-center.md`): Data → Planning Center (admins and up) fetches one Planning Center People list (Site settings → Planning Center) and compares each member with the site: linked, or suggested by the same email, else the same name, with the fields that would change (name, sort name, private email and phone) side by side. For each: link (and update; Planning Center wins), link to someone else, make a new unpublished person, or skip; Apply writes it all at once. One way, by hand. Off until `PCO_APP_ID` and `PCO_SECRET` are on the service. Tested against a stand-in for Planning Center's API only.
|
||||
- [ ] Check with the real list: the token, a list number, a compare, an apply.
|
||||
- [x] **Rotating words** (Sections, migration 084): text typed as `{Next|Now|Rising}` cycles through its choices, in the hero's headline, section titles (bands' too), headings, paragraphs, callouts and quotes, eg. `{Next|Now} Generation of {Unity|New Thought}`. Five motions (slide, flip like a card, fade, type letter by letter, mirror turning round), from the top or the bottom, a number of seconds per word: defaults in Site settings → Animated words, and a hero or a block can set its own. Each word's space is the longest's, so the line doesn't jump. Less motion (the system's setting, or reading mode) shows the first word, still, and screen readers always get the first; menus, tab titles, search descriptions and newsletters use the first word too (`src/components/RotatingWords.tsx`, `src/lib/words.ts`).
|
||||
- [ ] Check in a browser: each motion and direction, a group in a section title and a paragraph, the space it keeps on a phone, reduced motion.
|
||||
- [x] **Section types with their own settings, and the front page as sections** (migration 083): the front page is Home in Page management, a page of sections like the others: its hero first, then its bands in their old order (hidden ones stay hidden), each a section type that can go on any page with content of its own: Hero (words, buttons, photos, video, livestream or event), Event countdown, Event calendar, Numbers, Featured cards, Connect nav, and a Timeline shown as the rail of featured moments. The Community blog's slots, pinned posts and feeds moved into its section, so it can go on any page too. Any section can be Hidden. The Front page editor is gone (its fields are each section's), and so are its tables and the Community page's. On the front page the bands look as they did and any other section is a band in the same style; on other pages a band brings its own heading. The National Retreats band became an Events section with an All retreats button. The newsletter's "featured cards" come from the front page's featured card sections. Admin engine: a child collection can have its own side tables and gated nested collections.
|
||||
|
|
|
|||
46
docs/planning-center.md
Normal file
46
docs/planning-center.md
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
# Planning Center
|
||||
|
||||
Admin → Data → Planning Center (admins and up) brings one Planning
|
||||
Center People list into the site's people, by hand (migration 085).
|
||||
One way: nothing is sent to Planning Center.
|
||||
|
||||
## Setup
|
||||
|
||||
1. In Planning Center, make (or pick) a People **list** of the people who
|
||||
should be on the site, eg. "Website". Its number is in its address:
|
||||
`people.planningcenteronline.com/lists/1234567`.
|
||||
2. Admin → Panel → Site settings → **Planning Center → People list**: that
|
||||
number.
|
||||
3. A personal access token: https://api.planningcenteronline.com/oauth/applications
|
||||
→ Personal Access Tokens → New, as an account that can see that list.
|
||||
Put its two halves on the service (`systemctl edit ngu-api`):
|
||||
|
||||
```
|
||||
[Service]
|
||||
Environment=PCO_APP_ID=...
|
||||
Environment=PCO_SECRET=...
|
||||
```
|
||||
|
||||
then `systemctl restart ngu-api`. (`PCO_BASE` overrides the API's
|
||||
address, for testing.)
|
||||
|
||||
## Using it
|
||||
|
||||
**Compare with Planning Center** fetches the list. Each member shows:
|
||||
|
||||
- the site person they're **linked** to, or one **suggested** by the
|
||||
same email (private or public), else the same name;
|
||||
- for that person, each field that would change: name, sort name
|
||||
("Last, First"), private email and private phone, the site's value
|
||||
beside Planning Center's.
|
||||
|
||||
For each, choose **Link to** the suggestion (and whether to update it
|
||||
from Planning Center), link to **someone else**, **make a new person**
|
||||
(unpublished, to fill in and publish later), or **Skip**. **Apply**
|
||||
writes what you chose, all at once; nothing changes before. Planning
|
||||
Center wins where both have a value; a blank in Planning Center leaves
|
||||
the site's. Once linked, a person is matched by Planning Center's id
|
||||
from then on, whatever their name or email becomes.
|
||||
|
||||
Code: `server/src/planningCenter.js` (the API, the comparison, the
|
||||
writes), `server/src/routes/pco.js`, `src/pages/admin/AdminPco.tsx`.
|
||||
|
|
@ -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;
|
||||
|
|
@ -81,6 +81,7 @@ const AdminVideoFrames = lazyPage(() => import("./pages/admin/AdminVideoFrames.t
|
|||
const AdminNewsletter = lazyPage(() => import("./pages/admin/AdminNewsletter.tsx"))
|
||||
const AdminProfiles = lazyPage(() => import("./pages/admin/AdminProfiles.tsx"))
|
||||
const AdminConvert = lazyPage(() => import("./pages/admin/AdminConvert.tsx"))
|
||||
const AdminPco = lazyPage(() => import("./pages/admin/AdminPco.tsx"))
|
||||
const EntityList = lazyPage(() => import("./pages/admin/EntityList.tsx"))
|
||||
const EntityEdit = lazyPage(() => import("./pages/admin/EntityEdit.tsx"))
|
||||
|
||||
|
|
@ -145,6 +146,7 @@ export default function App() {
|
|||
<Route element={<RequireRole role="admin" />}>
|
||||
<Route path="clips" element={<AdminClips />} />
|
||||
<Route path="profiles" element={<AdminProfiles />} />
|
||||
<Route path="pco" element={<AdminPco />} />
|
||||
</Route>
|
||||
<Route path=":entity" element={<EntityList />} />
|
||||
<Route path=":entity/:id" element={<EntityEdit />} />
|
||||
|
|
|
|||
|
|
@ -159,6 +159,16 @@ export const siteSettings = {
|
|||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
legend: "Planning Center",
|
||||
fields: [
|
||||
{
|
||||
path: "pco_list_id",
|
||||
label: "People list",
|
||||
help: "The Planning Center list Data → Planning Center brings in: its number, from the list's address in Planning Center People, eg. 1234567. Needs PCO_APP_ID and PCO_SECRET on the server (docs/planning-center.md).",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
legend: "Animated words",
|
||||
note: WORD_HELP + " Works in the hero's headline, section titles, headings and paragraphs. These are the defaults; a hero or a block can set its own. Visitors who ask for less motion see the first word, still.",
|
||||
|
|
|
|||
240
src/pages/admin/AdminPco.tsx
Normal file
240
src/pages/admin/AdminPco.tsx
Normal file
|
|
@ -0,0 +1,240 @@
|
|||
/* ═══════════════════════════════════════════════════════════════
|
||||
ADMIN: PLANNING CENTER (Data → Planning Center, admins and up)
|
||||
|
||||
One Planning Center People list into the site's people, by hand
|
||||
(server/src/planningCenter.js). Compare fetches the list and shows
|
||||
each member: the site person they're linked to, or the one
|
||||
suggested (same email, else same name), and the fields that would
|
||||
change, Planning Center's value winning. For each, choose: link
|
||||
(and update), another person, a new unpublished person, or skip.
|
||||
Nothing is written until Apply.
|
||||
═══════════════════════════════════════════════════════════════ */
|
||||
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
|
||||
import { ApiError, get, post } from "../../lib/api.ts";
|
||||
|
||||
const MUTED = "var(--color-muted)";
|
||||
const button =
|
||||
"btn border border-brand px-4 py-2 text-sm text-link transition-colors hover:bg-tint disabled:cursor-default disabled:opacity-50";
|
||||
const primary =
|
||||
"btn bg-action px-5 py-2.5 text-white transition-colors hover:bg-action-hover disabled:bg-muted/25";
|
||||
const input =
|
||||
"border border-muted/25 bg-surface px-2 py-1.5 text-sm text-body outline-none focus:border-brand focus:ring-2 focus:ring-brand/25";
|
||||
|
||||
type Member = { id: string; first: string; last: string; name: string; email: string | null; phone: string | null };
|
||||
type Row = {
|
||||
pco: Member;
|
||||
match: { person_id: string; name: string; how: "linked" | "email" | "name" } | null;
|
||||
changes: { field: string; label: string; site: string | null; pco: string }[];
|
||||
};
|
||||
/* What the admin picked for a member: a person id, "new", or "" (skip). */
|
||||
type Choice = { target: string; update: boolean };
|
||||
|
||||
const HOW: Record<string, string> = {
|
||||
linked: "Linked",
|
||||
email: "Suggested: same email",
|
||||
name: "Suggested: same name",
|
||||
};
|
||||
|
||||
const message = (err: unknown) => (err instanceof ApiError ? err.message : "Couldn't reach the server.");
|
||||
|
||||
export default function AdminPco() {
|
||||
const [status, setStatus] = useState<{ ready: boolean; list_id: string | null } | null>(null);
|
||||
const [rows, setRows] = useState<Row[] | null>(null);
|
||||
const [people, setPeople] = useState<{ id: string; label: string }[]>([]);
|
||||
const [choices, setChoices] = useState<Record<string, Choice>>({});
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [done, setDone] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
get("/admin/pco", { ttl: 0 }).then(setStatus).catch((err) => setError(message(err)));
|
||||
get("/admin/options?only=people", { ttl: 0 })
|
||||
.then((body) => setPeople(body.options.people))
|
||||
.catch(() => setPeople([]));
|
||||
}, []);
|
||||
|
||||
async function compare() {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
setDone(null);
|
||||
try {
|
||||
const body = await post("/admin/pco/compare", {});
|
||||
setRows(body.rows);
|
||||
// Linked or suggested: that person, updated; else skip.
|
||||
setChoices(
|
||||
Object.fromEntries(
|
||||
body.rows.map((row: Row) => [row.pco.id, { target: row.match?.person_id ?? "", update: Boolean(row.match) }]),
|
||||
),
|
||||
);
|
||||
} catch (err) {
|
||||
setError(message(err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function applyAll() {
|
||||
if (!rows) return;
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
const decisions = rows
|
||||
.map((row) => ({ row, choice: choices[row.pco.id] }))
|
||||
.filter(({ choice }) => choice?.target)
|
||||
.map(({ row, choice }) =>
|
||||
choice.target === "new"
|
||||
? { pco_id: row.pco.id, action: "create" }
|
||||
: { pco_id: row.pco.id, action: "link", person_id: choice.target, update: choice.update },
|
||||
);
|
||||
const body = await post("/admin/pco/apply", { decisions });
|
||||
setDone(`Done: ${body.counts.linked} linked, ${body.counts.updated} updated, ${body.counts.created} new (unpublished).`);
|
||||
await compare();
|
||||
} catch (err) {
|
||||
setError(message(err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
const counts = useMemo(() => {
|
||||
const picked = Object.values(choices);
|
||||
return {
|
||||
link: picked.filter((c) => c.target && c.target !== "new").length,
|
||||
create: picked.filter((c) => c.target === "new").length,
|
||||
};
|
||||
}, [choices]);
|
||||
|
||||
const setChoice = (id: string, next: Partial<Choice>) =>
|
||||
setChoices((current) => ({ ...current, [id]: { ...current[id], ...next } }));
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex flex-wrap items-baseline gap-3">
|
||||
<h1 className="text-2xl font-bold text-link">Planning Center</h1>
|
||||
<p className="text-sm" style={{ color: MUTED }}>
|
||||
Bring a Planning Center People list into the site's people. Planning Center wins; you review each person first.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<section className="mt-6 bg-raised p-5 shadow-md">
|
||||
{!status ? (
|
||||
<p className="text-sm" style={{ color: MUTED }}>Checking…</p>
|
||||
) : !status.ready ? (
|
||||
<p className="text-sm text-body">
|
||||
Not set up on the server: it needs PCO_APP_ID and PCO_SECRET (docs/planning-center.md).
|
||||
</p>
|
||||
) : !status.list_id ? (
|
||||
<p className="text-sm text-body">
|
||||
Pick the list in <Link to="/admin/site_settings" className="text-link underline">Site settings → Planning Center</Link> (superadmins).
|
||||
</p>
|
||||
) : (
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<button type="button" className={primary} disabled={busy} onClick={compare}>
|
||||
{busy && !rows ? "Fetching…" : rows ? "Compare again" : "Compare with Planning Center"}
|
||||
</button>
|
||||
<span className="text-sm" style={{ color: MUTED }}>
|
||||
List {status.list_id}. Name, and email and phone into the private fields.
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
{error && <p className="mt-3 text-sm text-danger">{error}</p>}
|
||||
{done && <p className="mt-3 text-sm text-body">{done}</p>}
|
||||
</section>
|
||||
|
||||
{rows && (
|
||||
<>
|
||||
<div className="mt-6 flex flex-wrap items-center gap-3">
|
||||
<button type="button" className={primary} disabled={busy || counts.link + counts.create === 0} onClick={applyAll}>
|
||||
{busy ? "Applying…" : `Apply: ${counts.link} linked, ${counts.create} new`}
|
||||
</button>
|
||||
<span className="text-sm" style={{ color: MUTED }}>
|
||||
{rows.length} on the list. Skipped ones aren't touched.
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<ul className="mt-4 space-y-3">
|
||||
{rows.map((row) => {
|
||||
const choice = choices[row.pco.id] ?? { target: "", update: false };
|
||||
const sameAsMatch = choice.target && choice.target === row.match?.person_id;
|
||||
return (
|
||||
<li key={row.pco.id} className="bg-raised p-4 shadow-sm">
|
||||
<div className="flex flex-wrap items-start justify-between gap-3">
|
||||
<div>
|
||||
<p className="font-semibold text-body">{row.pco.name || "(no name)"}</p>
|
||||
<p className="text-xs" style={{ color: MUTED }}>
|
||||
{[row.pco.email, row.pco.phone].filter(Boolean).join(" · ") || "No email or phone"}
|
||||
</p>
|
||||
<p className="mt-1 text-xs text-body">
|
||||
{row.match ? `${HOW[row.match.how]}: ${row.match.name}` : "No match on the site"}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<label className="sr-only" htmlFor={`pco-${row.pco.id}`}>
|
||||
What to do with {row.pco.name}
|
||||
</label>
|
||||
<select
|
||||
id={`pco-${row.pco.id}`}
|
||||
value={choice.target}
|
||||
onChange={(e) => setChoice(row.pco.id, { target: e.target.value, update: e.target.value !== "new" })}
|
||||
className={input}
|
||||
>
|
||||
<option value="">Skip</option>
|
||||
<option value="new">Make a new person (unpublished)</option>
|
||||
{row.match && <option value={row.match.person_id}>Link to {row.match.name}</option>}
|
||||
<optgroup label="Link to someone else">
|
||||
{people
|
||||
.filter((p) => p.id !== row.match?.person_id)
|
||||
.map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{p.label}
|
||||
</option>
|
||||
))}
|
||||
</optgroup>
|
||||
</select>
|
||||
{choice.target && choice.target !== "new" && (
|
||||
<label className="flex items-center gap-2 text-sm text-body">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={choice.update}
|
||||
onChange={(e) => setChoice(row.pco.id, { update: e.target.checked })}
|
||||
/>
|
||||
Update from Planning Center
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{sameAsMatch && row.changes.length > 0 && (
|
||||
<table className="mt-3 w-full text-left text-sm">
|
||||
<thead className="text-xs uppercase tracking-wider" style={{ color: MUTED }}>
|
||||
<tr>
|
||||
<th className="py-1 pr-4 font-medium">Field</th>
|
||||
<th className="py-1 pr-4 font-medium">On the site</th>
|
||||
<th className="py-1 font-medium">Planning Center</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{row.changes.map((change) => (
|
||||
<tr key={change.field} className="border-t border-muted/10">
|
||||
<td className="py-1 pr-4 text-body">{change.label}</td>
|
||||
<td className="py-1 pr-4" style={{ color: MUTED }}>{change.site ?? "-"}</td>
|
||||
<td className="py-1 text-body">{change.pco}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
{sameAsMatch && row.changes.length === 0 && (
|
||||
<p className="mt-2 text-xs" style={{ color: MUTED }}>Already the same.</p>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -101,6 +101,12 @@ export const DATA_NAV = {
|
|||
blurb: "Invite people to make a profile account, approve their claims to a People record, and link their Discord.",
|
||||
minRole: "admin",
|
||||
},
|
||||
{
|
||||
to: "/admin/pco",
|
||||
label: "Planning Center",
|
||||
blurb: "Bring a Planning Center People list into People: compare each person, then link, update or add them.",
|
||||
minRole: "admin",
|
||||
},
|
||||
{
|
||||
to: "/admin/blog_posts",
|
||||
label: "Blog posts",
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue