9 Commits
Author SHA1 Message Date
davidandClaude Opus 5.5 7da7c5fd9c Phase 6 part 5, step 3: theme updates by pull request
The theme carries a MANIFEST of its files' SHA-256s. A site's Theme card
shows its copy's version against Supermarket's and any files changed by
hand; Update the theme opens a pull request that writes new and changed
files, removes retired ones, rebuilds, and lists what it replaces.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 15:30:48 -07:00
davidandClaude Opus 5.5 2a605ac265 Sidebar: fold each module's pages
A chevron beside each module folds or unfolds its pages. The current
module is always open; the others keep the state you left them in; a
folded module shows its pages' counts added up.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 15:27:22 -07:00
davidandClaude Opus 5.5 9ca09c1ffa Phase 6 part 5, step 2: start a new site
Sites → New site fills an empty Gitea repository with the theme, a
hugo.toml in the site's brand and a starter home page: checked that the
repository is empty and builds with Hugo, then the first commit is pushed
to its default branch. The site joins the profile, and a First pages card
builds its Home, About, Contact and product pages with the page builder;
About and Contact join the top menu.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 15:27:22 -07:00
davidandClaude Opus 5.5 5d7db5c5bf Phase 6 part 5, step 1: a shared site theme
internal/theme embeds a Hugo theme from federated-website's look and the
13 section types both sites share, with the header, footer, colors, font
and logo set per site in hugo.toml, and a README of each type's fields.
The catalogue reader reads themes' sections and READMEs after the site's
own; lead forms know a theme site needs only the Lead Capture address.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 15:14:24 -07:00
davidandClaude Opus 5.5 98913971ea Phase 6 part 4: post as the LinkedIn company page
A second LinkedIn app (Community Management API) with its own sign-in on
Settings → Social accounts: the pages the member may post for are listed
and one chosen, new LinkedIn drafts default to the page or to you, and
each draft can switch before it's published. Schema 25.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 15:05:30 -07:00
davidandClaude Opus 5.5 2c42857419 Phase 6 part 3: website lead forms into EspoCRM
Sites → Lead forms sets up the site's forms to create EspoCRM Leads
through its Lead Capture: the address saved and tested with a CORS
preflight, and a pull request adding a script that maps the form's fields
onto a Lead (campaign, page and form in the description). Plausible's
Lead goal is imported per signal as interested.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 14:54:26 -07:00
davidandClaude Opus 5.5 fa4792e0fe Phase 6 part 2: restore from a backup
A restore is staged (checked, the current database backed up) and swapped
in when the app next starts. Settings → Backups restores with a
self-restart, cancels a waiting restore, and takes uploads; supermarket
restore takes a backup name or a file; supermarket backup --with-secrets
makes an archive with the keys, for moving machines.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 14:46:36 -07:00
davidandClaude Opus 5.5 5313369328 Phase 6 part 1: database backups
Backups with SQLite's VACUUM INTO into <data>/backups: on request
(Settings → Backups, supermarket backup [note]), before every schema
migration, and daily, keeping 7 dailies and 4 weeklies. Listed with size
and schema; downloadable and deletable. The old app.db.pre-* copies are
moved in, with their -wal files folded in first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 14:38:23 -07:00
davidandClaude Opus 5.5 c425f49c93 PLAN: Phase 5 merged into main
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 14:28:49 -07:00
88 changed files with 7344 additions and 112 deletions
+212 -4
View File
@@ -1209,7 +1209,8 @@ into `main`. **Parts 1 to 6 built, and merged into `main` on 2026-11-22**
merge, and checks the live site afterwards to confirm it changed.
**Started 2026-11-22** on branch `phase5-sites`, after Phase 4 was merged
into `main`.
into `main`. **Merged into `main` on 2026-11-22** (fast-forward to
e2a72d5).
**Decisions (the user, 2026-11-22):**
- **Pages are built from each site's own sections**, not a new shared
@@ -1347,11 +1348,216 @@ under Sections and pages.
**Phase 5 is complete** (parts 1–5). Not yet tried for real: building a
page (a paid AI call) and pushing it to the real repository.
### Phase 6: Backups, lead forms, the LinkedIn page, new sites
**Started 2026-11-22** on branch `phase6`, after Phase 5 was merged into
`main`. Phases 0–5 had covered the plan; the user chose to make Phase 6
of four further pieces: the first three future enhancements below, and a
shared theme for new sites (deferred in Phase 5).
**Parts, in order, a commit after each:**
1. **Backups.** As designed under Future enhancements, item 2: SQLite's own
backup (`VACUUM INTO`), into `backups/`; made on request (Settings →
Backups, `supermarket backup [note]`), before every schema migration,
and daily; kept 7 daily and 4 weekly, the rest until deleted; listed
with size and schema, downloadable and deletable; the old
`app.db.pre-*` copies moved in.
2. **Restore.** From a backup in the list, an uploaded one, or `supermarket
restore <file>`: checked (integrity, schema not newer), the current
database backed up first, then swapped in and the app restarted.
`supermarket backup --with-secrets` for moving machines.
3. **Inbound lead forms.** The sites' `form` sections post to EspoCRM's own
lead capture (Supermarket is local-only, so it can't take the posts
itself), with the buying signal from the page's campaign tag. Supermarket
sets the capture up, puts its address in the site's settings by pull
request, and counts the leads in the funnel.
4. **The LinkedIn company page.** As designed under Future enhancements,
item 1: the second app's keys, choosing the page, and posting as the
page or the profile per draft. Built against LinkedIn's documented API;
used for real once LinkedIn approves the app.
5. **New sites from a shared theme.** Decided with the user (2026-11-22):
the theme is *copied into* each new site (`themes/supermarket/`), not a
submodule, so each site stands alone; *the user creates* the empty
Gitea repository (the `write:repository` token stays enough); the theme
has *federated-website's look*, with each site's colors, fonts and logo
as settings. In three steps, a commit after each:
1. **The theme**, embedded in Supermarket: base layouts, header and
footer, the section types both sites share (hero, text, features,
cards, steps, checklist, split, stats, table, faq, callout,
final-cta) plus federated-website's lead `form`, the stylesheet with
brand variables, and a README documenting each type and its fields
(which the catalogue reader and the page builder then use).
2. **A new site**: Sites → New site takes the empty repository, the
site's address, name and brand (colors, font, logo); the first
commit (the theme, `hugo.toml`, a starter home page) goes straight to
the empty repository's `main`, the one exception to "always a pull
request", since there's nothing published yet; then the site is added
to the profile, read, and previewed, and its first pages (home,
about, a product page, contact with a lead form) are built with the
page builder as pull requests.
3. **Theme updates**: the theme carries a version; a site whose copy is
older gets a pull request copying the new one in.
**Step 1 built (2026-11-22; no schema change).** `internal/theme` embeds
the theme (version 1): federated-website's base layout (its reveal and
sticky-header script; not its agent view or pricing script), a generic
head (title, description, canonical and Open Graph tags, favicon, the
brand font from Google Fonts, Plausible when `[params.plausible]` is
set), a header and footer driven by `hugo.toml` (logo or the site's
name, `main` menu with dropdowns, `[params.header] ctas`, footer
groups, social and legal menus, copyright), the 13 shared section types
(the hero without Federated's layer panel; the form posting through
`supermarket-leads.js`, now the theme's file and the one Part 3 uses),
pages that render sections then any Markdown body, a 404, and the
stylesheet with every brand color as a variable (the fixed violet,
lime and navy tints turned into `color-mix` of the brand variables).
`[params.brand]` sets dark, dark2, primary, accent (and hovers), font,
logo and favicon. The README documents each type's real fields; the
catalogue reader now reads `themes/*/` sections and READMEs after the
site's own (the site's win), and treats types `render-sections` picks
by name as types even before a page uses them; Lead forms knows a theme
site needs only the address. Tested with Hugo building every section.
**Step 2 built (2026-11-22; no schema change).** Sites → New site takes
the empty repository (owner/name), the site's address (https), name,
tagline, contact email, and brand (dark, primary and accent colors with
color pickers, a font from a short list of Google Fonts, an optional
logo). It checks the values (a control character, a bad color, a
non-https address are refused), checks on Gitea that the repository is
*empty* (Gitea's `empty` flag) and the token can push, builds the files
with Hugo, and only then makes the first commit (`InitPush`: git init,
commit, push to the default branch) in the site's working copy: the
theme, `hugo.toml` (brand, header button to /contact/, footer, an empty
`[params.leads] action` with the email), a starter home page (hero and
closing band), a README and a .gitignore. The site is added to the
profile and marked read. Its Sections and pages shows a *First pages*
card: Home page, About page, Contact page and a product page per
profile product, each one click to the page builder (a paid AI call;
nothing is spent until clicked). New page kinds: *home* (replaces the
site's home page, at /), *about* and *contact* (both join the top menu
through `menus: main` in their front matter; contact is built around
the form). Commits are by the Core's user "via Supermarket"
(`commitAuthor`). Deploying the new site is still the user's Gitea hook.
**Step 3 built (2026-11-22; no schema change).** The theme carries a
`MANIFEST` (each file's SHA-256) beside its `VERSION`, so a site's copy
can be checked for files changed by hand. Sites → Sections and pages
shows a *Theme* card on sites using it: their version against
Supermarket's, the files changed by hand, and *Update the theme* when
Supermarket's is newer. The update (`supermarket/theme-<n>`) writes the
new and changed files, removes the ones the theme no longer has,
rebuilds, and opens a pull request listing what changed, was added and
removed, and which hand-edited files it replaces (changes belong in the
site's own `layouts/` or `static/`, which win over the theme). To ship a
theme change: edit `internal/theme/files/`, raise `theme.Version`.
**Part 5 is complete**, and with it Phase 6's plan. Not tried for real: a
new site on the real Gitea (the user creates the empty repository).
**Part 1 built (2026-11-22; no schema change).** `internal/backup` makes
backups with `VACUUM INTO` (to a `.part` file, then renamed; mode 0600)
into `<data>/backups`, named `app-<yyyymmdd>-<hhmmss>-<kind>[-<note>].db`
(kinds: manual, migration, daily, restore, legacy). `db.BeforeMigrate`
backs up an existing database before any pending migration
(`before-schema-<n>`; a failed backup stops the migration); a new database
isn't backed up. The app makes the daily backup at start and then hourly
checks whether one is due, pruning dailies to the newest 7 plus the newest
of each of the 4 weeks before. Settings → Backups lists them (when, why,
size, schema; unreadable files are flagged), makes one with a note,
downloads and deletes; only names from the list are served. `supermarket
backup [note]` and `supermarket backups` run the binary in the container
with `docker exec`; it opens the database beside the app without
migrating it. On start, the old `app.db.pre-*` copies are moved in as
*legacy* backups dated by their file time, with any `-wal` folded in
first; one that fails the integrity check is left in place. Live: all 23
moved. Some show an older schema than the database had when they were
taken (pre-phase5-part5 is at 22, not 23): plain `cp` missed writes still
in the WAL, as feared. The live database is 60 MB (mostly Stripe objects),
so the backups folder holds about 620 MB; old legacy copies can be deleted
from the page.
**Part 2 built (2026-11-22; no schema change).** A restore is staged,
then applied on the next start, since a running app can't swap its own
database: `backup.Stage` checks the file (integrity, a Supermarket
database, schema no newer than the app's), backs up the current database
(kind *restore*), and leaves `restore-pending.db` (plus
`restore-pending.json`); `ApplyPending` runs in `main` before anything
opens the database, re-checks it, removes the old `-wal`/`-shm`, renames
it over `app.db`, and records `restore-done.json`; migrations then run as
usual. From Settings → Backups, *Restore* (asks first) stages it and
stops the app (`Server.Restart`, the signal context's cancel); Docker's
`restart: unless-stopped` starts it again within a second, and the page
reloads (a `Refresh` header). A staged restore can be cancelled until
then. *Upload* takes a `.db` file, checks it and adds it to the list as
one of the user's backups. `supermarket restore <name or file>` copies a
host file into the data folder, stages it in the container, and restarts
the app. `supermarket backup --with-secrets` writes a mode-0600
`app-<time>-with-secrets.tar.gz` (app.db, secrets.json, mcp-token) to the
backups folder, not listed on the page; restoring one replaces
secrets.json too (the old one kept in the backups folder), while this
machine's mcp-token stays. Tried live both ways (the command line and the
page) by restoring a backup taken seconds before.
**Part 3 built (2026-11-22; no schema change).** EspoCRM's Lead Capture
(docs: docs.espocrm.com/administration/web-to-lead/) takes a JSON `POST
<crm>/api/v1/LeadCapture/<api key>` without a login, allows other sites
by default (`leadCaptureAllowOrigin`, "*"), and has one fixed Campaign per
Lead Capture: a per-submission campaign can't be passed. So the signal
travels in the Lead's description, and Plausible counts it. Sites → Lead
forms:
- shows how the site's forms post now (`[params.leads] action`), which
pages have a form, and whether this site's form section can be
connected;
- gives the EspoCRM steps (a Lead Capture whose Payload Fields are First
Name, Last Name, Email, Account Name, Phone, Description);
- saves its API URL (checked: https, `/api/v1/LeadCapture/<key>`) and
tests it with a CORS preflight from the site's origin (nothing created);
- opens a pull request (`supermarket/lead-forms`): `[params.leads]
action` in `hugo.toml`, `static/js/supermarket-leads.js` defining
`window.leadPost(form, data)`, and the form partial loading it and
calling it in place of its own `fetch(form.action, …)` (patched only if
that call is there; matched on federated-website's). The script maps
name (split), email, organization/company, phone onto the Lead; the
form's name, other answers (by label), the page, the visit's UTM tags
and the referrer go in the description. Checked with a build: a page
with a form loads the script and posts to the Lead Capture.
- counts form leads: the forms already send Plausible a `Lead` event, so
the daily Plausible import also reads the `Lead` goal by the visit's
UTM tags and records them as *interested* on the signal's funnel (or
says to add the goal in Plausible).
Tested with Node running the script on a form's data. Not done for real:
creating the Lead Capture in EspoCRM, and the pull request on the real
site.
**Part 4 built (2026-11-22; schema 25: `drafts.linkedin_as`).** From
LinkedIn's docs (Microsoft Learn, community-management): posting as a page
is the same `POST /rest/posts` with `author: urn:li:organization:<id>` and
`w_organization_social`, for members with an approved ADMINISTRATOR,
CONTENT_ADMIN(ISTRATOR) or DIRECT_SPONSORED_CONTENT_POSTER role;
`GET /rest/organizationAcls?q=roleAssignee&state=APPROVED` lists the
member's roles (the docs name the field `organizationTarget` or
`organization`: both are read), and `GET
/rest/organizationsLookup?ids=List(…)` names the pages without needing
admin. The docs don't say which scope the role list needs.
- Settings → Social accounts has a **LinkedIn page** card: the second app's
client ID and secret, its own sign-in (`/auth/linkedin-page/…`, its own
redirect URL), the scopes it asks for (default `w_organization_social
r_organization_admin`, editable to match the approved app), the pages
listed after sign-in to choose from (or a page number typed in, from its
admin address, when they can't be listed), and whether new LinkedIn
drafts default to the page. The only page is chosen automatically. Its
60-day expiry is reminded like LinkedIn's.
- Each LinkedIn draft in Posts has *Post as: You / <the page>*; the
publisher posts with the page's token and URN, or the member's, and says
which sign-in is missing or expired.
Not tried for real: it waits on LinkedIn approving the page app.
### Future enhancements
Not in any phase yet; picked up when the user asks.
1. **Post to the LinkedIn company page** (deferred 2026-11-21). Today posts
1. **Post to the LinkedIn company page** (deferred 2026-11-21; Phase 6,
part 4). Today posts
go to the signed-in member's profile (`w_member_social`). Posting as the
Federated Computer page needs LinkedIn's **Community Management API**,
which LinkedIn approves by hand.
@@ -1373,7 +1579,7 @@ Not in any phase yet; picked up when the user asks.
and .../community-management/community-management-overview.
2. **Back up the database and restore from a backup** (asked for
2026-11-21). Today backups are copies made by hand before risky changes
2026-11-21; Phase 6, parts 1 and 2). Today backups are copies made by hand before risky changes
(`app.db.pre-phase1`, `app.db.pre-dedupe`, …) in the data folder. A plain
`cp` of a running database in WAL mode can miss recent writes, so
backups must use SQLite's own backup (`VACUUM INTO` or the online backup
@@ -1451,7 +1657,9 @@ Phase 0 (incl. Hermes bridge test) ──► Phase 1 (content)
│ mail on the Core, Plausible, Stripe key
├──► Phase 3 (SEO) ──────── needs: Google OAuth (Search Console), Gitea token
├──► Phase 4 (metrics) ──── needs: Stripe key; CRM reads for pipeline
└──► Phase 5 (sites) ────── needs: Gitea token
├──► Phase 5 (sites) ────── needs: Gitea token
└──► Phase 6 (backups; lead forms ─ needs: EspoCRM lead capture;
LinkedIn page ─ needs: LinkedIn's approval; new sites)
```
Phases 1, 3, 5 and the Stripe half of 4 depend only on Phase 0.
+103
View File
@@ -43,6 +43,12 @@ Throughout, also notice:
- [ ] Its Setup list (AI, social accounts, Core, Hermes and so on) matches
what you've set up, and each missing step links to where to do it.
- [ ] In the sidebar, each module (Content, Prospects, SEO, Metrics, Sites)
has a chevron that folds or unfolds its pages. The module you're in
is always unfolded; the others stay as you left them, across pages
and restarts of the browser. A folded module shows its pages' counts
added up (e.g. Prospects' Review and Outreach).
## 3. Settings
### Profile
@@ -62,6 +68,23 @@ Throughout, also notice:
- [ ] LinkedIn shows when its 60-day sign-in runs out.
- [ ] Removing a key (the *remove* box, then Save) removes it.
### LinkedIn page
- [ ] Settings → Social accounts has a *LinkedIn page* card with its own
redirect URL (…/auth/linkedin-page/callback).
- [ ] Once LinkedIn approves the page app (Community Management API), save
its client ID and secret and *Connect LinkedIn page*: the pages you
administer are listed (the only one is chosen).
- [ ] If they aren't listed (a permission missing), type the page's number
from linkedin.com/company/<number>/admin and save.
- [ ] Choose "New LinkedIn drafts post as: The company page": new LinkedIn
drafts in Posts show *Post as: <the page>*; switch one to *You* and
save.
- [ ] Publish a draft as the page: it appears on the company page, not your
profile; one as you still goes to your profile.
- [ ] Two weeks before the page sign-in expires, the Overview and Posts
remind you.
### Core & Hermes
- [ ] It shows your Core's domain, email and name from `core.conf`.
@@ -97,6 +120,40 @@ Throughout, also notice:
saves and is used.
- [ ] With an OpenAI-compatible server, *List its models* lists them.
### Backups
- [ ] Settings → Backups lists the backups, newest first, with when, why
(by you, daily, before an update, before a restore, an older copy),
size and schema.
- [ ] *Back up now* with a note adds one at the top, named with the note.
- [ ] *Download* saves a file that opens with `sqlite3` (`.tables` lists
Supermarket's tables); there's no `secrets.json` content in it.
- [ ] *Delete* asks first, then removes it from the list and the folder.
- [ ] A daily backup appears once a day while the app runs, never twice
on one day; after more than a week, older dailies thin out to one a
week.
- [ ] Updating Supermarket to a version with a database change makes a
"Before an update" backup first.
- [ ] `supermarket backup "a note"` and `supermarket backups` work from a
terminal; with the app stopped they say to start it.
- [ ] The old `app.db.pre-*` files are gone from the data folder and listed
as "An older copy".
- [ ] *Restore* on a backup asks first; then the page says it's restarting
and reloads by itself within about ten seconds, showing "Restored
from …" and the backup of what was there before. Data made after the
backup is gone; data from before it is back.
- [ ] A backup from a newer Supermarket (a higher schema) has no *Restore*
button; `supermarket restore` refuses it with a reason.
- [ ] *Upload* a downloaded `.db`: it's checked and listed ("uploaded …");
a file that isn't a Supermarket database is refused.
- [ ] `supermarket restore <name>` (a name from `supermarket backups`) and
`supermarket restore ~/Downloads/<file>.db` both work and restart the
app.
- [ ] `supermarket backup --with-secrets` makes a `.tar.gz` in the backups
folder (only you can read it) and warns about it; on another computer
`supermarket restore <file>.tar.gz` brings back the data and the keys
(Settings show them as saved).
## 4. Inventory
- [ ] Add a partner and a competitor by hand, with websites, feeds, X
@@ -586,6 +643,52 @@ Throughout, also notice:
- [ ] A page that went live, or was removed, shows up in SEO → Search
engines' IndexNow log (when IndexNow is set up).
### Lead forms
- [ ] Sites → Lead forms says how the forms send today (an email), and
lists the pages with a form (/churches/, /partners/, /saas-savings/).
- [ ] Following the steps, create a Lead Capture in EspoCRM with the
payload fields listed; paste its API URL and *Save and test*: it
says the site may post to it, and no Lead appears in EspoCRM.
- [ ] A wrong address (not …/api/v1/LeadCapture/…) is refused.
- [ ] *Open the pull request*: on Gitea it changes `hugo.toml`, the form
section and adds `static/js/supermarket-leads.js`; preview it under
Sites → Previews.
- [ ] After merging, send a form on the live site from a link tagged with a
signal (`?utm_campaign=<signal>`): EspoCRM gets a Lead with the name
split, the email and organization, and the form, page and campaign
in its description. The page says "Connected".
- [ ] With a `Lead` goal added in Plausible, the next day's import counts
it as *interested* on the signal; Lead forms lists it.
### A new site
- [ ] Create an empty repository in Gitea (no README). On Sites → New site,
fill in the repository, address, name, tagline, email, colors, font;
*Start the site*.
- [ ] A repository that isn't empty, a non-https address or a bad color is
refused with a reason, and nothing is pushed.
- [ ] On Gitea, the repository has one commit: `themes/supermarket/`,
`hugo.toml` with your brand, `content/_index.md`, a README.
- [ ] The site appears in Settings → Profile's websites and on Sites, with
a *First pages* card and the theme's 13 section types.
- [ ] Sites → Previews → build `main`: the starter home page shows in your
colors and font, with your name (or logo) in the top bar.
- [ ] *Contact page* writes a page with a form; open its pull request,
preview it: Contact appears in the top menu. *About page* likewise.
- [ ] *Home page* replaces the starter home page (its file, at /).
- [ ] Connect the contact form under Lead forms: the pull request only sets
the Lead Capture address (the theme's form is ready).
- [ ] After adding your Gitea deploy hook and merging, the site is live at
its address, and Publishing confirms each page.
- [ ] A site made with the theme shows a *Theme* card: "version 1: the
latest". After a Supermarket update with a newer theme, it offers
*Update the theme*; the pull request lists the changed, added and
removed files and builds.
- [ ] Edit a file under `themes/supermarket/` by hand and read the site
again: the Theme card names it as changed by hand, and the update's
pull request says it will be replaced.
## 9. Search
- [ ] Searching for an inventory entry, a fetched item, a post, a prospect
+42
View File
@@ -19,6 +19,12 @@ Usage: supermarket [command]
hermes Set up, or repair, Hermes' connection to your Core's MCP hub
token Print the token agents use to reach Supermarket's MCP endpoint
data Print where its data is kept
backup [note] Back up the database now (it also backs up daily)
backup --with-secrets The same, with your keys and tokens, for moving
to another computer (keep the file safe)
backups List the backups
restore <backup or file> Put a backup back (a name from \`backups\`, or
a file), after backing up what's there now; then restarts
Updates come with CoreDesktop's \`update\`.
EOF
@@ -57,6 +63,42 @@ case "${1:-open}" in
logs) compose logs -f --tail 200 ;;
hermes) shift; bash "$REPO/hermes/setup.sh" "$@" ;;
token) cat "$DATA/mcp-token" ;;
backup|backups)
if ! docker exec supermarket true 2> /dev/null; then
echo "Supermarket isn't running: start it first (supermarket start)."
exit 1
fi
docker exec supermarket supermarket "$@"
;;
restore)
if [ -z "$2" ]; then
echo "Usage: supermarket restore <backup name or file>"
exit 1
fi
if ! docker exec supermarket true 2> /dev/null; then
echo "Supermarket isn't running: start it first (supermarket start)."
exit 1
fi
target="$2"
staged=""
if [ -f "$target" ]; then
# A file on this computer: the container only sees the data folder.
case "$target" in
*.tar.gz|*.tgz) staged="$DATA/restore-upload.tar.gz" ;;
*) staged="$DATA/restore-upload.db" ;;
esac
install -m 600 "$target" "$staged" || exit 1
target="/data/$(basename "$staged")"
fi
if docker exec supermarket supermarket restore "$target"; then
[ -n "$staged" ] && rm -f "$staged"
echo "Restarting Supermarket to apply it..."
compose restart
else
[ -n "$staged" ] && rm -f "$staged"
exit 1
fi
;;
data) echo "$DATA" ;;
-h|--help|help) usage ;;
*) usage; exit 1 ;;
+103
View File
@@ -15,6 +15,7 @@ package main
import (
"context"
"crypto/rand"
"database/sql"
"encoding/hex"
"errors"
"fmt"
@@ -28,6 +29,7 @@ import (
"time"
"supermarket/internal/ai"
"supermarket/internal/backup"
"supermarket/internal/content"
"supermarket/internal/core"
"supermarket/internal/crm"
@@ -47,6 +49,13 @@ func main() {
fmt.Println(version)
return
}
if len(os.Args) > 1 && (os.Args[1] == "backup" || os.Args[1] == "backups" || os.Args[1] == "restore") {
if err := backupCommand(os.Args[1], os.Args[2:]); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
return
}
log := slog.New(slog.NewTextHandler(os.Stdout, nil))
if err := run(log); err != nil {
log.Error("stopped", "err", err)
@@ -76,6 +85,26 @@ func run(log *slog.Logger) error {
if err := os.MkdirAll(dataDir, 0700); err != nil {
return err
}
// A restore staged before the restart is swapped in before the
// database opens.
if r, err := backup.ApplyPending(dataDir, time.Now()); err != nil {
log.Error("backups: the restore wasn't applied", "err", err)
} else if r != nil {
log.Info("backups: restored", "from", r.From, "secrets", r.Secrets, "previous database", r.Backup)
}
// Old hand-made copies (app.db.pre-*) join the backups.
if n := backup.AdoptLegacy(dataDir, func(name string, err error) {
log.Warn("backups: an old copy was left where it is", "file", name, "err", err)
}); n > 0 {
log.Info("backups: moved old copies into the backups folder", "count", n)
}
db.BeforeMigrate = func(d *sql.DB, from, to int) error {
b, err := backup.Make(d, backup.Dir(dataDir), backup.Migration, fmt.Sprintf("before-schema-%d", to), time.Now())
if err == nil {
log.Info("backups: backed up before migrating", "from", from, "to", to, "file", b.Name)
}
return err
}
database, err := db.Open(filepath.Join(dataDir, "app.db"))
if err != nil {
return err
@@ -148,6 +177,9 @@ func run(log *slog.Logger) error {
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
// A restore from the browser stops the app; Docker starts it again
// (restart: unless-stopped), and the restore is applied on the way up.
srv.Restart = stop
errCh := make(chan error, 2)
go func() {
@@ -162,6 +194,7 @@ func run(log *slog.Logger) error {
go srv.RunTracking(ctx)
go srv.RunSEO(ctx)
go srv.RunMetrics(ctx)
go srv.RunBackups(ctx)
// A sync falls due, and a claim times out, without anything being
// written: refresh the state file each minute.
go func() {
@@ -220,3 +253,73 @@ func mcpToken(path string) (string, error) {
}
return t, nil
}
// backupCommand runs `supermarket backup [note]` and `supermarket backups`
// (inside the container: the host's command runs them with docker exec).
// It reads the database beside the running app, which WAL allows; it
// never migrates it.
func backupCommand(cmd string, args []string) error {
dataDir := env("SUPERMARKET_DATA", "/data")
dir := backup.Dir(dataDir)
if cmd == "backups" {
bs, err := backup.List(dir)
if err != nil {
return err
}
if len(bs) == 0 {
fmt.Println("No backups yet.")
return nil
}
for _, b := range bs {
schema := fmt.Sprintf("schema %d", b.Schema)
if b.Schema < 0 {
schema = "unreadable"
}
fmt.Printf("%-60s %8.1f MB %s\n", b.Name, float64(b.Size)/(1<<20), schema)
}
return nil
}
path := filepath.Join(dataDir, "app.db")
if _, err := os.Stat(path); err != nil {
return fmt.Errorf("no database at %s", path)
}
d, err := sql.Open("sqlite", "file:"+path+"?_pragma=busy_timeout(10000)")
if err != nil {
return err
}
defer d.Close()
if cmd == "restore" {
if len(args) != 1 {
return errors.New("usage: supermarket restore <backup name or file>")
}
src := args[0]
if !filepath.IsAbs(src) {
src = filepath.Join(dir, src)
}
r, err := backup.Stage(d, dataDir, src, db.Schema(), time.Now())
if err != nil {
return err
}
fmt.Printf("Ready to restore %s; the current database is backed up as %s.\n", r.From, r.Backup)
if r.Secrets {
fmt.Println("Its secrets.json (keys and tokens) will replace this one; the current one is kept in the backups folder.")
}
fmt.Println("It's applied when Supermarket restarts.")
return nil
}
if len(args) > 0 && args[0] == "--with-secrets" {
p, err := backup.Archive(d, dataDir, time.Now())
if err != nil {
return err
}
fmt.Printf("Backed up, with secrets, to backups/%s\n", filepath.Base(p))
fmt.Println("It holds your keys and tokens: keep it as safe as they are, and delete it once you've moved.")
return nil
}
b, err := backup.Make(d, dir, backup.Manual, strings.Join(args, " "), time.Now())
if err != nil {
return err
}
fmt.Printf("Backed up to %s (%.1f MB)\n", b.Name, float64(b.Size)/(1<<20))
return nil
}
+1
View File
@@ -96,6 +96,7 @@ type Repo struct {
DefaultBranch string `json:"default_branch"`
CloneURL string `json:"clone_url"`
HTMLURL string `json:"html_url"`
Empty bool `json:"empty"` // no commits yet
Permissions struct {
Push bool `json:"push"`
} `json:"permissions"`
+112
View File
@@ -198,3 +198,115 @@ func fallbackTitle(u string) string {
}
return u
}
// --- Company pages (the Community Management API) ---
// Org is a LinkedIn company page the signed-in member may post for.
type Org struct {
URN string `json:"urn"` // urn:li:organization:<id>
ID string `json:"id"`
Name string `json:"name"`
Vanity string `json:"vanity"` // linkedin.com/company/<vanity>
Role string `json:"role"`
}
// postingRoles may post on a page's behalf (w_organization_social). The
// docs name the content role both ways.
var postingRoles = map[string]bool{"ADMINISTRATOR": true, "CONTENT_ADMIN": true, "CONTENT_ADMINISTRATOR": true,
"DIRECT_SPONSORED_CONTENT_POSTER": true}
// get sends a versioned REST GET, stepping back a version on 426 as
// PostUpdate does, and decodes the JSON answer.
func (c *Client) get(ctx context.Context, path string, out any) error {
var (
res *http.Response
raw []byte
)
for attempt := 0; ; attempt++ {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, apiBase+path, nil)
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+c.accessToken)
req.Header.Set("LinkedIn-Version", version(c.now(), versionLag+attempt))
req.Header.Set("X-Restli-Protocol-Version", "2.0.0")
res, err = c.http.Do(req)
if err != nil {
return err
}
raw, _ = io.ReadAll(io.LimitReader(res.Body, 4<<20))
res.Body.Close()
if res.StatusCode == http.StatusUpgradeRequired && attempt+1 < versionAttempts {
continue
}
break
}
switch {
case res.StatusCode == http.StatusUnauthorized:
return ErrUnauthorized
case res.StatusCode == http.StatusForbidden:
return fmt.Errorf("LinkedIn refused (403): the app may lack the permission for this (%s)", strings.TrimSpace(string(raw[:min(len(raw), 300)])))
case res.StatusCode != http.StatusOK:
return fmt.Errorf("linkedin HTTP %d: %s", res.StatusCode, raw[:min(len(raw), 300)])
}
return json.Unmarshal(raw, out)
}
// Organizations lists the company pages the member has an approved role on
// that may post (administrator, content admin, sponsored content poster),
// with their names.
func (c *Client) Organizations(ctx context.Context) ([]Org, error) {
var acls struct {
Elements []struct {
Role string `json:"role"`
State string `json:"state"`
Organization string `json:"organization"`
OrganizationTarget string `json:"organizationTarget"`
} `json:"elements"`
}
if err := c.get(ctx, "/rest/organizationAcls?q=roleAssignee&state=APPROVED&count=100", &acls); err != nil {
return nil, err
}
var orgs []Org
seen := map[string]bool{}
for _, e := range acls.Elements {
urn := e.OrganizationTarget
if urn == "" {
urn = e.Organization
}
id := strings.TrimPrefix(urn, "urn:li:organization:")
if id == urn || id == "" || e.State != "APPROVED" || !postingRoles[e.Role] || seen[id] {
continue
}
seen[id] = true
orgs = append(orgs, Org{URN: urn, ID: id, Role: e.Role})
}
if len(orgs) == 0 {
return nil, nil
}
ids := make([]string, len(orgs))
for i, o := range orgs {
ids[i] = o.ID
}
var look struct {
Results map[string]struct {
LocalizedName string `json:"localizedName"`
VanityName string `json:"vanityName"`
} `json:"results"`
}
// organizationsLookup doesn't need the administrator role; a page
// whose name can't be read is still listed, by its ID.
if err := c.get(ctx, "/rest/organizationsLookup?ids=List("+strings.Join(ids, ",")+")", &look); err == nil {
for i := range orgs {
if r, ok := look.Results[orgs[i].ID]; ok {
orgs[i].Name, orgs[i].Vanity = r.LocalizedName, r.VanityName
}
}
}
for i := range orgs {
if orgs[i].Name == "" {
orgs[i].Name = "Page " + orgs[i].ID
}
}
return orgs, nil
}
+69
View File
@@ -100,3 +100,72 @@ func TestPostSendsTheArticleTitle(t *testing.T) {
t.Error("a post without a link has no content")
}
}
func TestOrganizations(t *testing.T) {
var paths []string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
paths = append(paths, r.URL.RequestURI())
if r.Header.Get("Authorization") != "Bearer page-tok" || r.Header.Get("X-Restli-Protocol-Version") != "2.0.0" || r.Header.Get("LinkedIn-Version") == "" {
t.Errorf("headers: %v", r.Header)
}
switch r.URL.Path {
case "/rest/organizationAcls":
w.Write([]byte(`{"elements":[
{"role":"ADMINISTRATOR","state":"APPROVED","organizationTarget":"urn:li:organization:111"},
{"role":"CONTENT_ADMIN","state":"APPROVED","organization":"urn:li:organization:222"},
{"role":"ANALYST","state":"APPROVED","organizationTarget":"urn:li:organization:333"},
{"role":"ADMINISTRATOR","state":"REQUESTED","organizationTarget":"urn:li:organization:444"},
{"role":"DIRECT_SPONSORED_CONTENT_POSTER","state":"APPROVED","organizationTarget":"urn:li:organization:111"}]}`))
case "/rest/organizationsLookup":
w.Write([]byte(`{"results":{"111":{"localizedName":"Federated Computer","vanityName":"federated-computer"}},"statuses":{"111":200,"222":404}}`))
default:
http.NotFound(w, r)
}
}))
defer srv.Close()
old := apiBase
apiBase = srv.URL
defer func() { apiBase = old }()
orgs, err := New("page-tok", "").Organizations(context.Background())
if err != nil {
t.Fatal(err)
}
if len(orgs) != 2 || orgs[0].URN != "urn:li:organization:111" || orgs[0].Name != "Federated Computer" || orgs[0].Vanity != "federated-computer" ||
orgs[0].Role != "ADMINISTRATOR" || orgs[1].ID != "222" || orgs[1].Name != "Page 222" {
t.Errorf("orgs: %+v", orgs)
}
if !strings.Contains(paths[0], "q=roleAssignee") || !strings.Contains(paths[0], "state=APPROVED") || paths[1] != "/rest/organizationsLookup?ids=List(111,222)" {
t.Errorf("paths: %v", paths)
}
}
func TestOrganizationsRefused(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusForbidden)
w.Write([]byte(`{"message":"Not enough permissions to access: organizationAcls"}`))
}))
defer srv.Close()
old := apiBase
apiBase = srv.URL
defer func() { apiBase = old }()
if _, err := New("t", "").Organizations(context.Background()); err == nil || !strings.Contains(err.Error(), "may lack the permission") {
t.Errorf("err: %v", err)
}
}
func TestPostAsAPage(t *testing.T) {
var body map[string]any
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
json.NewDecoder(r.Body).Decode(&body)
w.Header().Set("X-RestLi-Id", "urn:li:share:9")
w.WriteHeader(http.StatusCreated)
}))
defer srv.Close()
old := apiBase
apiBase = srv.URL
defer func() { apiBase = old }()
u, err := New("t", "urn:li:organization:111").PostUpdate(context.Background(), "Hello", nil)
if err != nil || u != "https://www.linkedin.com/feed/update/urn:li:share:9/" || body["author"] != "urn:li:organization:111" {
t.Errorf("%s %v %v", u, err, body)
}
}
+410
View File
@@ -0,0 +1,410 @@
// Package backup makes and keeps copies of Supermarket's database. Each
// backup is one consistent SQLite file made with SQLite's own VACUUM INTO,
// so it's safe while the app is writing (a plain copy of a database in WAL
// mode can miss recent writes). Secrets aren't in the database, so they're
// never in a backup.
//
// Backups live in <data>/backups, named
// app-<yyyymmdd>-<hhmmss>-<kind>[-<note>].db, so the folder alone says what
// each one is.
package backup
import (
"database/sql"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"time"
_ "modernc.org/sqlite"
)
// Kinds of backup.
const (
Manual = "manual" // made by the user
Migration = "migration" // made before a schema migration
Daily = "daily" // made once a day
Restore = "restore" // made before a restore
Legacy = "legacy" // an old hand-made app.db.pre-* copy
)
// Kept says whether a kind is kept until the user deletes it.
func Kept(kind string) bool { return kind != Daily }
// Backup is one backup file.
type Backup struct {
Name string
Path string
At time.Time
Kind string
Note string
Size int64
Schema int // the database's schema version; -1 if it can't be read
Err string // why it can't be read, if it can't
}
// Dir is where a data folder's backups go.
func Dir(dataDir string) string { return filepath.Join(dataDir, "backups") }
var (
nameRe = regexp.MustCompile(`^app-(\d{8})-(\d{6})-(manual|migration|daily|restore|legacy)(?:-([a-z0-9-]+))?\.db$`)
nonSlug = regexp.MustCompile(`[^a-z0-9]+`)
stampFmt = "20060102-150405"
)
// Slug makes a note fit a file name: "Before the big import!" becomes
// "before-the-big-import".
func Slug(note string) string {
s := strings.Trim(nonSlug.ReplaceAllString(strings.ToLower(note), "-"), "-")
if len(s) > 60 {
s = strings.TrimRight(s[:60], "-")
}
return s
}
// Parse reads a backup's name; ok is false for files that aren't backups.
func Parse(name string) (b Backup, ok bool) {
m := nameRe.FindStringSubmatch(name)
if m == nil {
return b, false
}
at, err := time.ParseInLocation(stampFmt, m[1]+"-"+m[2], time.Local)
if err != nil {
return b, false
}
return Backup{Name: name, At: at, Kind: m[3], Note: m[4]}, true
}
func fileName(at time.Time, kind, note string) string {
n := "app-" + at.Format(stampFmt) + "-" + kind
if s := Slug(note); s != "" {
n += "-" + s
}
return n + ".db"
}
// Make backs up the open database into dir.
func Make(d *sql.DB, dir, kind, note string, now time.Time) (*Backup, error) {
if err := os.MkdirAll(dir, 0o700); err != nil {
return nil, err
}
name := fileName(now, kind, note)
for n := 2; ; n++ {
if _, err := os.Stat(filepath.Join(dir, name)); errors.Is(err, os.ErrNotExist) {
break
}
name = fileName(now.Add(time.Duration(n-1)*time.Second), kind, note)
}
path := filepath.Join(dir, name)
tmp := filepath.Join(dir, "."+name+".part")
os.Remove(tmp)
if _, err := d.Exec(`VACUUM INTO ?`, tmp); err != nil {
os.Remove(tmp)
return nil, fmt.Errorf("backing up: %w", err)
}
if err := os.Chmod(tmp, 0o600); err != nil {
os.Remove(tmp)
return nil, err
}
if err := os.Rename(tmp, path); err != nil {
os.Remove(tmp)
return nil, err
}
b, _ := Parse(name)
b.Path = path
b.read()
return &b, nil
}
// read fills in the size and schema.
func (b *Backup) read() {
if st, err := os.Stat(b.Path); err == nil {
b.Size = st.Size()
}
b.Schema = -1
v, err := SchemaOf(b.Path)
if err != nil {
b.Err = err.Error()
return
}
b.Schema = v
}
// open opens a database file read-only, without touching it.
func open(path string) (*sql.DB, error) {
d, err := sql.Open("sqlite", "file:"+path+"?mode=ro&_pragma=busy_timeout(5000)")
if err != nil {
return nil, err
}
d.SetMaxOpenConns(1)
return d, nil
}
// SchemaOf reads a database file's schema version.
func SchemaOf(path string) (int, error) {
d, err := open(path)
if err != nil {
return 0, err
}
defer d.Close()
var v int
if err := d.QueryRow(`PRAGMA user_version`).Scan(&v); err != nil {
return 0, fmt.Errorf("not a database Supermarket can read: %w", err)
}
return v, nil
}
// Check checks a database file: SQLite's integrity check, and that it's a
// Supermarket database (it has the settings table).
func Check(path string) error {
d, err := open(path)
if err != nil {
return err
}
defer d.Close()
var res string
if err := d.QueryRow(`PRAGMA integrity_check`).Scan(&res); err != nil {
return fmt.Errorf("not a database Supermarket can read: %w", err)
}
if res != "ok" {
return fmt.Errorf("the database is damaged: %s", res)
}
var n int
if err := d.QueryRow(`SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name = 'settings'`).Scan(&n); err != nil || n == 0 {
return errors.New("that isn't a Supermarket database")
}
return nil
}
// List lists the backups in dir, newest first.
func List(dir string) ([]Backup, error) {
entries, err := os.ReadDir(dir)
if errors.Is(err, os.ErrNotExist) {
return nil, nil
}
if err != nil {
return nil, err
}
var out []Backup
for _, e := range entries {
b, ok := Parse(e.Name())
if !ok || e.IsDir() {
continue
}
b.Path = filepath.Join(dir, e.Name())
b.read()
out = append(out, b)
}
sort.Slice(out, func(i, j int) bool {
if !out[i].At.Equal(out[j].At) {
return out[i].At.After(out[j].At)
}
return out[i].Name > out[j].Name
})
return out, nil
}
// Find finds a backup by name; only names from the list are accepted.
func Find(dir, name string) (*Backup, error) {
bs, err := List(dir)
if err != nil {
return nil, err
}
for i := range bs {
if bs[i].Name == name {
return &bs[i], nil
}
}
return nil, os.ErrNotExist
}
// Delete deletes a backup.
func Delete(dir, name string) error {
b, err := Find(dir, name)
if err != nil {
return err
}
return os.Remove(b.Path)
}
// Keep says which daily backups to keep: the newest 7, then the newest of
// each of the 4 weeks before them. Other kinds are always kept.
func Keep(bs []Backup) map[string]bool {
keep := map[string]bool{}
var daily []Backup
for _, b := range bs {
if Kept(b.Kind) {
keep[b.Name] = true
} else {
daily = append(daily, b)
}
}
sort.Slice(daily, func(i, j int) bool { return daily[i].At.After(daily[j].At) })
weeks := map[string]bool{}
for i, b := range daily {
if i < 7 {
keep[b.Name] = true
continue
}
y, w := b.At.ISOWeek()
wk := fmt.Sprintf("%d-%02d", y, w)
if len(weeks) < 4 && !weeks[wk] {
weeks[wk] = true
keep[b.Name] = true
}
}
return keep
}
// Prune deletes the daily backups Keep doesn't keep.
func Prune(dir string) (int, error) {
bs, err := List(dir)
if err != nil {
return 0, err
}
keep := Keep(bs)
n := 0
for _, b := range bs {
if !keep[b.Name] {
if err := os.Remove(b.Path); err != nil {
return n, err
}
n++
}
}
return n, nil
}
// DueDaily says whether today's daily backup hasn't been made yet.
func DueDaily(dir string, now time.Time) (bool, error) {
bs, err := List(dir)
if err != nil {
return false, err
}
today := now.Format("20060102")
for _, b := range bs {
if b.Kind == Daily && b.At.Format("20060102") == today {
return false, nil
}
}
return true, nil
}
// AdoptLegacy moves the old hand-made copies (app.db.pre-<note>) from the
// data folder into the backups, as legacy backups dated by when they were
// made. A copy taken with its -wal file has it folded in first; each copy
// is checked before its leftovers are removed, and one that fails the
// check is left where it is. It returns how many it moved.
func AdoptLegacy(dataDir string, log func(string, error)) int {
matches, _ := filepath.Glob(filepath.Join(dataDir, "app.db.pre-*"))
dir := Dir(dataDir)
moved := 0
for _, path := range matches {
base := filepath.Base(path)
if strings.HasSuffix(base, "-wal") || strings.HasSuffix(base, "-shm") {
continue
}
st, err := os.Stat(path) // when it was made, before folding in changes it
if err != nil {
log(base, err)
continue
}
if _, err := os.Stat(path + "-wal"); err == nil {
if err := checkpoint(path); err != nil {
log(base, err)
continue
}
}
if err := Check(path); err != nil {
log(base, err)
continue
}
if err := os.MkdirAll(dir, 0o700); err != nil {
log(base, err)
return moved
}
name := fileName(st.ModTime(), Legacy, strings.TrimPrefix(base, "app.db.pre-"))
if _, err := os.Stat(filepath.Join(dir, name)); err == nil {
log(base, errors.New("a backup with its name is already there"))
continue
}
if err := moveFile(path, filepath.Join(dir, name)); err != nil {
log(base, err)
continue
}
os.Remove(path + "-wal")
os.Remove(path + "-shm")
moved++
}
return moved
}
// checkpoint folds a copy's -wal file into it.
func checkpoint(path string) error {
d, err := sql.Open("sqlite", "file:"+path+"?_pragma=busy_timeout(5000)")
if err != nil {
return err
}
defer d.Close()
d.SetMaxOpenConns(1)
if _, err := d.Exec(`PRAGMA wal_checkpoint(TRUNCATE)`); err != nil {
return fmt.Errorf("folding in its -wal file: %w", err)
}
_, err = d.Exec(`PRAGMA journal_mode = DELETE`)
return err
}
// moveFile renames, or copies and removes across file systems.
func moveFile(from, to string) error {
if err := os.Rename(from, to); err == nil {
return nil
}
in, err := os.Open(from)
if err != nil {
return err
}
defer in.Close()
out, err := os.OpenFile(to, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)
if err != nil {
return err
}
if _, err := io.Copy(out, in); err != nil {
out.Close()
os.Remove(to)
return err
}
if err := out.Close(); err != nil {
os.Remove(to)
return err
}
return os.Remove(from)
}
// Adopt moves a checked database file into the backups as one the user
// made (an upload, say).
func Adopt(path, dir, note string, now time.Time) (*Backup, error) {
if err := os.MkdirAll(dir, 0o700); err != nil {
return nil, err
}
name := fileName(now, Manual, note)
for n := 1; ; n++ {
if _, err := os.Stat(filepath.Join(dir, name)); errors.Is(err, os.ErrNotExist) {
break
}
name = fileName(now.Add(time.Duration(n)*time.Second), Manual, note)
}
to := filepath.Join(dir, name)
if err := moveFile(path, to); err != nil {
return nil, err
}
os.Chmod(to, 0o600)
b, _ := Parse(name)
b.Path = to
b.read()
return &b, nil
}
+192
View File
@@ -0,0 +1,192 @@
package backup
import (
"database/sql"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
func newDB(t *testing.T, path string) *sql.DB {
t.Helper()
d, err := sql.Open("sqlite", "file:"+path+"?_pragma=journal_mode(WAL)")
if err != nil {
t.Fatal(err)
}
d.SetMaxOpenConns(1)
for _, q := range []string{`CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT)`, `INSERT INTO settings VALUES ('a', '1')`, `PRAGMA user_version = 7`} {
if _, err := d.Exec(q); err != nil {
t.Fatal(err)
}
}
return d
}
func TestMakeListFind(t *testing.T) {
dir := t.TempDir()
d := newDB(t, filepath.Join(dir, "app.db"))
defer d.Close()
bdir := Dir(dir)
now := time.Date(2026, 11, 22, 18, 30, 5, 0, time.Local)
b, err := Make(d, bdir, Manual, "Before the big import!", now)
if err != nil {
t.Fatal(err)
}
if b.Name != "app-20261122-183005-manual-before-the-big-import.db" || b.Schema != 7 || b.Size == 0 || b.Note != "before-the-big-import" {
t.Errorf("made: %+v", b)
}
if st, _ := os.Stat(b.Path); st.Mode().Perm() != 0o600 {
t.Errorf("mode: %v", st.Mode())
}
// Written after the backup: not in it.
d.Exec(`INSERT INTO settings VALUES ('b', '2')`)
cp, _ := sql.Open("sqlite", "file:"+b.Path+"?mode=ro")
var n int
cp.QueryRow(`SELECT count(*) FROM settings`).Scan(&n)
cp.Close()
if n != 1 {
t.Errorf("rows in the backup: %d", n)
}
if err := Check(b.Path); err != nil {
t.Errorf("check: %v", err)
}
// Same second: a different name.
b2, err := Make(d, bdir, Manual, "Before the big import!", now)
if err != nil || b2.Name == b.Name {
t.Errorf("second: %v %v", b2, err)
}
daily, _ := Make(d, bdir, Daily, "", now.Add(time.Hour))
os.WriteFile(filepath.Join(bdir, "notes.txt"), []byte("x"), 0o600)
os.WriteFile(filepath.Join(bdir, "app-20261101-000000-manual.db"), []byte("not a database"), 0o600)
bs, err := List(bdir)
if err != nil || len(bs) != 4 || bs[0].Name != daily.Name || bs[3].Schema != -1 || bs[3].Err == "" {
t.Fatalf("list: %+v %v", bs, err)
}
if err := Check(bs[3].Path); err == nil {
t.Error("a bad file passed the check")
}
if _, err := Find(bdir, "../app.db"); err == nil {
t.Error("found a file outside the list")
}
if err := Delete(bdir, daily.Name); err != nil {
t.Fatal(err)
}
if due, _ := DueDaily(bdir, now.Add(2*time.Hour)); !due {
t.Error("not due after deleting today's")
}
Make(d, bdir, Daily, "", now.Add(3*time.Hour))
if due, _ := DueDaily(bdir, now.Add(4*time.Hour)); due {
t.Error("due twice in a day")
}
if due, _ := DueDaily(bdir, now.Add(24*time.Hour)); !due {
t.Error("not due the next day")
}
}
func TestCheckNotSupermarket(t *testing.T) {
path := filepath.Join(t.TempDir(), "other.db")
d, _ := sql.Open("sqlite", "file:"+path)
d.Exec(`CREATE TABLE x (y)`)
d.Close()
if err := Check(path); err == nil || !strings.Contains(err.Error(), "isn't a Supermarket database") {
t.Errorf("check: %v", err)
}
}
func TestKeep(t *testing.T) {
var bs []Backup
start := time.Date(2026, 9, 1, 3, 0, 0, 0, time.Local)
for i := 0; i < 60; i++ { // 60 days of dailies
at := start.AddDate(0, 0, i)
bs = append(bs, Backup{Name: fileName(at, Daily, ""), At: at, Kind: Daily})
}
bs = append(bs, Backup{Name: "m", At: start, Kind: Manual}, Backup{Name: "g", At: start, Kind: Migration})
keep := Keep(bs)
var kept []string
for _, b := range bs {
if keep[b.Name] && b.Kind == Daily {
kept = append(kept, b.At.Format("01-02"))
}
}
// The newest 7 days, then the newest of each of 4 earlier weeks.
if len(kept) != 11 || !keep["m"] || !keep["g"] {
t.Errorf("kept %d dailies: %v", len(kept), kept)
}
last := start.AddDate(0, 0, 59)
for i := 0; i < 7; i++ {
if !keep[fileName(last.AddDate(0, 0, -i), Daily, "")] {
t.Errorf("day %d not kept", i)
}
}
}
func TestPrune(t *testing.T) {
dir := t.TempDir()
d := newDB(t, filepath.Join(dir, "app.db"))
defer d.Close()
bdir := Dir(dir)
start := time.Date(2026, 10, 1, 3, 0, 0, 0, time.Local)
for i := 0; i < 20; i++ {
if _, err := Make(d, bdir, Daily, "", start.AddDate(0, 0, i)); err != nil {
t.Fatal(err)
}
}
Make(d, bdir, Manual, "keep me", start)
n, err := Prune(bdir)
bs, _ := List(bdir)
if err != nil || n+len(bs) != 21 || len(bs) > 12 || !strings.Contains(bs[len(bs)-1].Name, "keep-me") {
t.Errorf("pruned %d, left %d: %v", n, len(bs), err)
}
}
func TestAdoptLegacy(t *testing.T) {
dir := t.TempDir()
// A copy taken with its -wal: its last rows are only in the -wal.
src := filepath.Join(t.TempDir(), "src.db")
d := newDB(t, src)
d.Exec(`PRAGMA wal_autocheckpoint = 0`)
d.Exec(`INSERT INTO settings VALUES ('only-in-wal', 'x')`)
for _, suffix := range []string{"", "-wal", "-shm"} {
raw, err := os.ReadFile(src + suffix)
if err != nil {
t.Fatal(err)
}
os.WriteFile(filepath.Join(dir, "app.db.pre-phase2-part3"+suffix), raw, 0o600)
}
d.Close()
// A broken one.
os.WriteFile(filepath.Join(dir, "app.db.pre-broken"), []byte("junk"), 0o600)
when := time.Date(2026, 11, 20, 9, 15, 0, 0, time.Local)
os.Chtimes(filepath.Join(dir, "app.db.pre-phase2-part3"), when, when)
var problems []string
n := AdoptLegacy(dir, func(name string, err error) { problems = append(problems, name+": "+err.Error()) })
if n != 1 || len(problems) != 1 || !strings.HasPrefix(problems[0], "app.db.pre-broken") {
t.Fatalf("moved %d; problems %v", n, problems)
}
bs, _ := List(Dir(dir))
if len(bs) != 1 || bs[0].Kind != Legacy || bs[0].Note != "phase2-part3" || !bs[0].At.Equal(when) {
t.Fatalf("adopted: %+v", bs)
}
cp, _ := sql.Open("sqlite", "file:"+bs[0].Path+"?mode=ro")
var v string
err := cp.QueryRow(`SELECT value FROM settings WHERE key = 'only-in-wal'`).Scan(&v)
cp.Close()
if err != nil {
t.Errorf("the -wal's rows were lost: %v", err)
}
for _, f := range []string{"app.db.pre-phase2-part3", "app.db.pre-phase2-part3-wal", "app.db.pre-phase2-part3-shm"} {
if _, err := os.Stat(filepath.Join(dir, f)); err == nil {
t.Errorf("%s is still there", f)
}
}
if _, err := os.Stat(filepath.Join(dir, "app.db.pre-broken")); err != nil {
t.Error("the broken copy was moved")
}
// Running again does nothing more.
if n := AdoptLegacy(dir, func(string, error) {}); n != 0 {
t.Errorf("second run moved %d", n)
}
}
+298
View File
@@ -0,0 +1,298 @@
package backup
import (
"archive/tar"
"compress/gzip"
"database/sql"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"time"
)
// Files a restore leaves in the data folder between staging it and the
// app's next start, when it's applied.
const (
pendingDB = "restore-pending.db"
pendingSecrets = "restore-pending-secrets.json"
pendingInfo = "restore-pending.json"
doneInfo = "restore-done.json"
)
// Restored says what the last restore put back.
type Restored struct {
From string `json:"from"` // the backup's name, or the file restored
Backup string `json:"backup"` // the backup of what was replaced
Secrets bool `json:"secrets,omitempty"` // secrets.json was replaced too
At time.Time `json:"at"`
}
// Stage prepares a restore from a backup file (a .db, or a .tar.gz made
// with secrets): it checks the file (SQLite's integrity check, a
// Supermarket database, a schema no newer than maxSchema), backs up the
// current database, and leaves the copy to be swapped in when the app
// next starts (ApplyPending). Secrets in an archive are swapped in too.
func Stage(current *sql.DB, dataDir, src string, maxSchema int, now time.Time) (*Restored, error) {
from := filepath.Base(src)
tmpDB := filepath.Join(dataDir, "."+pendingDB+".part")
tmpSecrets := ""
os.Remove(tmpDB)
defer os.Remove(tmpDB)
if strings.HasSuffix(src, ".tar.gz") || strings.HasSuffix(src, ".tgz") {
tmpSecrets = filepath.Join(dataDir, "."+pendingSecrets+".part")
defer os.Remove(tmpSecrets)
has, err := unpack(src, tmpDB, tmpSecrets)
if err != nil {
return nil, err
}
if !has {
tmpSecrets = ""
}
} else if err := copyFile(src, tmpDB); err != nil {
return nil, err
}
if err := Check(tmpDB); err != nil {
return nil, err
}
v, err := SchemaOf(tmpDB)
if err != nil {
return nil, err
}
if v > maxSchema {
return nil, fmt.Errorf("that backup is from a newer Supermarket (schema %d; this one knows %d): update Supermarket first", v, maxSchema)
}
if tmpSecrets != "" {
raw, err := os.ReadFile(tmpSecrets)
if err != nil {
return nil, err
}
var m map[string]any
if json.Unmarshal(raw, &m) != nil {
return nil, errors.New("the archive's secrets.json isn't readable")
}
}
b, err := Make(current, Dir(dataDir), Restore, "", now)
if err != nil {
return nil, fmt.Errorf("backing up the current database first: %w", err)
}
r := &Restored{From: from, Backup: b.Name, Secrets: tmpSecrets != "", At: now}
if err := os.Rename(tmpDB, filepath.Join(dataDir, pendingDB)); err != nil {
return nil, err
}
if tmpSecrets != "" {
if err := os.Rename(tmpSecrets, filepath.Join(dataDir, pendingSecrets)); err != nil {
os.Remove(filepath.Join(dataDir, pendingDB))
return nil, err
}
} else {
os.Remove(filepath.Join(dataDir, pendingSecrets))
}
raw, _ := json.Marshal(r)
if err := os.WriteFile(filepath.Join(dataDir, pendingInfo), raw, 0o600); err != nil {
os.Remove(filepath.Join(dataDir, pendingDB))
return nil, err
}
return r, nil
}
// Pending says whether a restore is waiting for the app to restart.
func Pending(dataDir string) bool {
_, err := os.Stat(filepath.Join(dataDir, pendingDB))
return err == nil
}
// Cancel drops a staged restore.
func Cancel(dataDir string) {
for _, f := range []string{pendingDB, pendingSecrets, pendingInfo} {
os.Remove(filepath.Join(dataDir, f))
}
}
// ApplyPending swaps a staged restore in, before the app opens its
// database: the database file replaced (its -wal and -shm removed) and,
// from an archive, secrets.json (the old one kept in the backups folder).
// It returns what was restored, or nil when nothing was staged.
func ApplyPending(dataDir string, now time.Time) (*Restored, error) {
pending := filepath.Join(dataDir, pendingDB)
if _, err := os.Stat(pending); errors.Is(err, os.ErrNotExist) {
return nil, nil
}
if err := Check(pending); err != nil {
Cancel(dataDir)
return nil, fmt.Errorf("the staged restore failed its check, so it was dropped: %w", err)
}
var r Restored
if raw, err := os.ReadFile(filepath.Join(dataDir, pendingInfo)); err == nil {
_ = json.Unmarshal(raw, &r)
}
db := filepath.Join(dataDir, "app.db")
for _, f := range []string{db + "-wal", db + "-shm"} {
if err := os.Remove(f); err != nil && !errors.Is(err, os.ErrNotExist) {
return nil, err
}
}
if err := os.Rename(pending, db); err != nil {
return nil, err
}
if secrets := filepath.Join(dataDir, pendingSecrets); r.Secrets {
cur := filepath.Join(dataDir, "secrets.json")
if _, err := os.Stat(cur); err == nil {
keep := filepath.Join(Dir(dataDir), "secrets-before-restore-"+now.Format(stampFmt)+".json")
if err := os.MkdirAll(Dir(dataDir), 0o700); err == nil {
_ = moveFile(cur, keep)
}
}
if err := os.Rename(secrets, cur); err != nil {
return nil, fmt.Errorf("the database was restored, but not the secrets: %w", err)
}
os.Chmod(cur, 0o600)
}
os.Remove(filepath.Join(dataDir, pendingInfo))
r.At = now
raw, _ := json.Marshal(r)
_ = os.WriteFile(filepath.Join(dataDir, doneInfo), raw, 0o600)
return &r, nil
}
// LastRestore is the last restore applied, if any.
func LastRestore(dataDir string) *Restored {
raw, err := os.ReadFile(filepath.Join(dataDir, doneInfo))
if err != nil {
return nil
}
var r Restored
if json.Unmarshal(raw, &r) != nil {
return nil
}
return &r
}
// Archive makes a backup with the app's secrets beside the database, for
// moving Supermarket to another machine: a mode-0600 .tar.gz in the
// backups folder holding app.db, secrets.json and mcp-token. It holds
// credentials: it must be kept as carefully as they are.
func Archive(d *sql.DB, dataDir string, now time.Time) (string, error) {
dir := Dir(dataDir)
if err := os.MkdirAll(dir, 0o700); err != nil {
return "", err
}
tmp := filepath.Join(dir, ".archive-"+now.Format(stampFmt)+".db")
os.Remove(tmp)
defer os.Remove(tmp)
if _, err := d.Exec(`VACUUM INTO ?`, tmp); err != nil {
return "", fmt.Errorf("backing up: %w", err)
}
path := filepath.Join(dir, "app-"+now.Format(stampFmt)+"-with-secrets.tar.gz")
f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)
if err != nil {
return "", err
}
gz := gzip.NewWriter(f)
tw := tar.NewWriter(gz)
add := func(name, from string) error {
in, err := os.Open(from)
if errors.Is(err, os.ErrNotExist) {
return nil
}
if err != nil {
return err
}
defer in.Close()
st, err := in.Stat()
if err != nil {
return err
}
if err := tw.WriteHeader(&tar.Header{Name: name, Mode: 0o600, Size: st.Size(), ModTime: now}); err != nil {
return err
}
_, err = io.Copy(tw, in)
return err
}
err = add("app.db", tmp)
if err == nil {
err = add("secrets.json", filepath.Join(dataDir, "secrets.json"))
}
if err == nil {
err = add("mcp-token", filepath.Join(dataDir, "mcp-token"))
}
for _, c := range []io.Closer{tw, gz, f} {
if cerr := c.Close(); err == nil {
err = cerr
}
}
if err != nil {
os.Remove(path)
return "", err
}
return path, nil
}
// unpack reads an archive made by Archive: its app.db to db, and its
// secrets.json, if there is one, to secrets.
func unpack(src, db, secrets string) (hasSecrets bool, err error) {
f, err := os.Open(src)
if err != nil {
return false, err
}
defer f.Close()
gz, err := gzip.NewReader(f)
if err != nil {
return false, fmt.Errorf("not an archive Supermarket made: %w", err)
}
tr := tar.NewReader(gz)
hasDB := false
for {
h, err := tr.Next()
if err == io.EOF {
break
}
if err != nil {
return false, fmt.Errorf("reading the archive: %w", err)
}
var to string
switch h.Name {
case "app.db":
to, hasDB = db, true
case "secrets.json":
to, hasSecrets = secrets, true
default:
continue // mcp-token and anything else stay as they are here
}
out, err := os.OpenFile(to, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o600)
if err != nil {
return false, err
}
_, err = io.Copy(out, io.LimitReader(tr, 16<<30))
if cerr := out.Close(); err == nil {
err = cerr
}
if err != nil {
return false, err
}
}
if !hasDB {
return false, errors.New("the archive has no app.db")
}
return hasSecrets, nil
}
func copyFile(from, to string) error {
in, err := os.Open(from)
if err != nil {
return err
}
defer in.Close()
out, err := os.OpenFile(to, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o600)
if err != nil {
return err
}
if _, err := io.Copy(out, in); err != nil {
out.Close()
return err
}
return out.Close()
}
+145
View File
@@ -0,0 +1,145 @@
package backup
import (
"database/sql"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
func value(t *testing.T, path, key string) string {
t.Helper()
d, err := sql.Open("sqlite", "file:"+path)
if err != nil {
t.Fatal(err)
}
defer d.Close()
var v string
d.QueryRow(`SELECT value FROM settings WHERE key = ?`, key).Scan(&v)
return v
}
func TestStageAndApply(t *testing.T) {
data := t.TempDir()
cur := newDB(t, filepath.Join(data, "app.db"))
now := time.Date(2026, 11, 22, 15, 0, 0, 0, time.Local)
old, err := Make(cur, Dir(data), Manual, "good", now.Add(-time.Hour))
if err != nil {
t.Fatal(err)
}
cur.Exec(`UPDATE settings SET value = 'changed' WHERE key = 'a'`)
// Too new, damaged and foreign files are refused, and nothing is staged.
newer := filepath.Join(t.TempDir(), "newer.db")
nd := newDB(t, newer)
nd.Exec(`PRAGMA user_version = 99`)
nd.Close()
junk := filepath.Join(t.TempDir(), "junk.db")
os.WriteFile(junk, []byte("junk"), 0o600)
for src, want := range map[string]string{newer: "newer Supermarket", junk: "not a database", "/nope.db": "no such file"} {
if _, err := Stage(cur, data, src, 24, now); err == nil || !strings.Contains(err.Error(), want) {
t.Errorf("%s: %v", src, err)
}
if Pending(data) {
t.Errorf("%s was staged", src)
}
}
r, err := Stage(cur, data, old.Path, 24, now)
if err != nil {
t.Fatal(err)
}
if r.From != old.Name || !strings.HasSuffix(r.Backup, "-restore.db") || r.Secrets || !Pending(data) {
t.Errorf("staged: %+v", r)
}
// What was there is backed up, with the change.
if v := value(t, filepath.Join(Dir(data), r.Backup), "a"); v != "changed" {
t.Errorf("safety backup: %q", v)
}
cur.Close()
os.WriteFile(filepath.Join(data, "app.db-wal"), []byte("stale"), 0o600)
got, err := ApplyPending(data, now.Add(time.Minute))
if err != nil || got == nil || got.From != old.Name {
t.Fatalf("applied: %+v %v", got, err)
}
if v := value(t, filepath.Join(data, "app.db"), "a"); v != "1" {
t.Errorf("restored value: %q", v)
}
if _, err := os.Stat(filepath.Join(data, "app.db-wal")); err == nil {
t.Error("the old -wal is still there")
}
if Pending(data) || LastRestore(data) == nil || LastRestore(data).From != old.Name {
t.Errorf("after: pending=%v last=%+v", Pending(data), LastRestore(data))
}
if r, err := ApplyPending(data, now); r != nil || err != nil {
t.Errorf("applied twice: %v %v", r, err)
}
}
func TestCancel(t *testing.T) {
data := t.TempDir()
cur := newDB(t, filepath.Join(data, "app.db"))
defer cur.Close()
b, _ := Make(cur, Dir(data), Manual, "", time.Now())
if _, err := Stage(cur, data, b.Path, 24, time.Now()); err != nil {
t.Fatal(err)
}
Cancel(data)
if Pending(data) {
t.Error("still pending")
}
if r, _ := ApplyPending(data, time.Now()); r != nil {
t.Error("applied a cancelled restore")
}
}
func TestArchiveWithSecrets(t *testing.T) {
// Machine one: a database, secrets and a token, archived.
one := t.TempDir()
d1 := newDB(t, filepath.Join(one, "app.db"))
d1.Exec(`UPDATE settings SET value = 'from-one' WHERE key = 'a'`)
os.WriteFile(filepath.Join(one, "secrets.json"), []byte(`{"stripe":"sk_one"}`), 0o600)
os.WriteFile(filepath.Join(one, "mcp-token"), []byte("token-one"), 0o600)
now := time.Date(2026, 11, 22, 16, 0, 0, 0, time.Local)
path, err := Archive(d1, one, now)
d1.Close()
if err != nil {
t.Fatal(err)
}
if st, _ := os.Stat(path); st.Mode().Perm() != 0o600 || !strings.HasSuffix(path, "-with-secrets.tar.gz") {
t.Errorf("archive: %s %v", path, st.Mode())
}
if bs, _ := List(Dir(one)); len(bs) != 0 {
t.Errorf("the archive is listed with the backups: %v", bs)
}
// Machine two: restored from it, secrets included; its own token stays.
two := t.TempDir()
d2 := newDB(t, filepath.Join(two, "app.db"))
os.WriteFile(filepath.Join(two, "secrets.json"), []byte(`{"stripe":"sk_two"}`), 0o600)
os.WriteFile(filepath.Join(two, "mcp-token"), []byte("token-two"), 0o600)
r, err := Stage(d2, two, path, 24, now)
d2.Close()
if err != nil || !r.Secrets {
t.Fatalf("staged: %+v %v", r, err)
}
if _, err := ApplyPending(two, now); err != nil {
t.Fatal(err)
}
if v := value(t, filepath.Join(two, "app.db"), "a"); v != "from-one" {
t.Errorf("database: %q", v)
}
raw, _ := os.ReadFile(filepath.Join(two, "secrets.json"))
tok, _ := os.ReadFile(filepath.Join(two, "mcp-token"))
if string(raw) != `{"stripe":"sk_one"}` || string(tok) != "token-two" {
t.Errorf("secrets %s, token %s", raw, tok)
}
kept, _ := filepath.Glob(filepath.Join(Dir(two), "secrets-before-restore-*.json"))
if len(kept) != 1 {
t.Fatalf("the old secrets weren't kept: %v", kept)
}
if old, _ := os.ReadFile(kept[0]); string(old) != `{"stripe":"sk_two"}` {
t.Errorf("kept: %s", old)
}
}
+60
View File
@@ -82,9 +82,11 @@ func TestItems(t *testing.T) {
type fakePub struct {
calls []string
err error
got Post // the last post
}
func (f *fakePub) Publish(_ context.Context, p Post) (string, error) {
f.got = p
call := p.Text + "|" + p.SourceURL
if p.Target != "" {
call = "r/" + p.Target + "|" + p.Title + "|" + call
@@ -366,3 +368,61 @@ func TestDraftsForSignal(t *testing.T) {
t.Errorf("prompt lacks the signal: %s", prompt)
}
}
func TestLinkedInAuthor(t *testing.T) {
d := openDB(t)
ctx := context.Background()
mk := func() (li, x Draft) {
if _, err := CreateDrafts(d, []Draft{{Channel: ChannelLinkedIn, Content: "Hello LinkedIn"}, {Channel: ChannelX, Content: "Hello X"}}); err != nil {
t.Fatal(err)
}
ds, _ := ListDrafts(d, 2, StatusDraft)
for _, dr := range ds {
if dr.Channel == ChannelLinkedIn {
li = dr
} else {
x = dr
}
}
return
}
li, x := mk()
if li.LinkedInAs != "" || x.LinkedInAs != "" {
t.Errorf("default: %q %q", li.LinkedInAs, x.LinkedInAs)
}
// With the page as the default, new LinkedIn drafts post as it; X's don't change.
d.PutJSON(LinkedInDefaultKey, AsPage)
DiscardDraft(d, li.ID)
DiscardDraft(d, x.ID)
li, x = mk()
if li.LinkedInAs != AsPage || x.LinkedInAs != "" {
t.Errorf("page default: %q %q", li.LinkedInAs, x.LinkedInAs)
}
if err := SetLinkedInAs(d, x.ID, AsPage); err == nil {
t.Error("an X draft took a LinkedIn author")
}
if err := SetLinkedInAs(d, li.ID, "someone"); err == nil {
t.Error("an unknown author was taken")
}
pub := &fakePub{}
if _, err := Publish(ctx, d, Publishers{ChannelLinkedIn: pub}, nil, li.ID); err != nil {
t.Fatal(err)
}
if !pub.got.AsPage {
t.Errorf("published as: %+v", pub.got)
}
// Switched back to you before publishing.
_, _ = mk()
ds, _ := ListDrafts(d, 5, StatusDraft)
for _, dr := range ds {
if dr.Channel == ChannelLinkedIn {
if err := SetLinkedInAs(d, dr.ID, ""); err != nil {
t.Fatal(err)
}
Publish(ctx, d, Publishers{ChannelLinkedIn: pub}, nil, dr.ID)
}
}
if pub.got.AsPage {
t.Error("published as the page after switching")
}
}
+36 -5
View File
@@ -80,8 +80,16 @@ type Draft struct {
PublishAt time.Time // when a scheduled draft goes out
SignalID int64 // the buying signal it was written for; 0: none
SignalSlug string // that signal's campaign tag
LinkedInAs string // LinkedIn: "" posts as you, AsPage as the company page
}
// AsPage is the LinkedIn author choice for the company page.
const AsPage = "page"
// LinkedInDefaultKey is the setting saying whether new LinkedIn drafts
// post as the company page ("page") or as you ("").
const LinkedInDefaultKey = "linkedin:post-as"
// Length is the draft's length as its channel counts it, including the
// source link on X.
func (d *Draft) Length() int {
@@ -157,6 +165,11 @@ func newBatchID() string {
// their items as used.
func CreateDrafts(d *db.DB, drafts []Draft) (string, error) {
batch := newBatchID()
// Read before the transaction: it holds the database's one connection.
var liDefault string
if _, err := d.GetJSON(LinkedInDefaultKey, &liDefault); err != nil {
return "", err
}
tx, err := d.Begin()
if err != nil {
return "", err
@@ -173,9 +186,16 @@ func CreateDrafts(d *db.DB, drafts []Draft) (string, error) {
if dr.SignalID != 0 {
sig = dr.SignalID
}
if _, err := tx.Exec(`INSERT INTO drafts (batch, inventory_name, kind, channel, title, target, content, source_url, item_ids, signal_id)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, batch, dr.InventoryName, dr.Kind, dr.Channel,
strings.TrimSpace(dr.Title), dr.Target, strings.TrimSpace(dr.Content), dr.SourceURL, string(ids), sig); err != nil {
as := dr.LinkedInAs
if dr.Channel == ChannelLinkedIn && as == "" {
as = liDefault
}
if dr.Channel != ChannelLinkedIn {
as = ""
}
if _, err := tx.Exec(`INSERT INTO drafts (batch, inventory_name, kind, channel, title, target, content, source_url, item_ids, signal_id, linkedin_as)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, batch, dr.InventoryName, dr.Kind, dr.Channel,
strings.TrimSpace(dr.Title), dr.Target, strings.TrimSpace(dr.Content), dr.SourceURL, string(ids), sig, as); err != nil {
return "", err
}
for _, id := range dr.ItemIDs {
@@ -200,7 +220,7 @@ func nonNil(s []string) []string {
const draftColumns = `id, batch, inventory_name, kind, channel, content, source_url, item_ids, status, error,
post_url, created_at, updated_at, COALESCE(published_at, ''), COALESCE(publish_at, ''), title, target,
COALESCE(signal_id, 0), COALESCE((SELECT slug FROM signals WHERE signals.id = drafts.signal_id), '')`
COALESCE(signal_id, 0), COALESCE((SELECT slug FROM signals WHERE signals.id = drafts.signal_id), ''), linkedin_as`
func scanDrafts(rows *sql.Rows) ([]Draft, error) {
defer rows.Close()
@@ -210,7 +230,7 @@ func scanDrafts(rows *sql.Rows) ([]Draft, error) {
var ids, created, updated, published, publishAt string
if err := rows.Scan(&dr.ID, &dr.Batch, &dr.InventoryName, &dr.Kind, &dr.Channel, &dr.Content,
&dr.SourceURL, &ids, &dr.Status, &dr.Error, &dr.PostURL, &created, &updated, &published, &publishAt, &dr.Title, &dr.Target,
&dr.SignalID, &dr.SignalSlug); err != nil {
&dr.SignalID, &dr.SignalSlug, &dr.LinkedInAs); err != nil {
return nil, err
}
_ = json.Unmarshal([]byte(ids), &dr.ItemIDs)
@@ -279,6 +299,17 @@ func UpdateDraft(d *db.DB, id int64, text string) error {
return oneRow(res, err)
}
// SetLinkedInAs chooses who a LinkedIn draft posts as: "" for you,
// AsPage for the company page.
func SetLinkedInAs(d *db.DB, id int64, as string) error {
if as != "" && as != AsPage {
return fmt.Errorf("unknown author %q", as)
}
res, err := d.Exec(`UPDATE drafts SET linkedin_as = ?, updated_at = ? WHERE id = ? AND channel = ? AND status IN (?, ?, ?)`,
as, formatTime(time.Now()), id, ChannelLinkedIn, StatusDraft, StatusFailed, StatusScheduled)
return oneRow(res, err)
}
// DiscardDraft drops a draft without publishing it.
func DiscardDraft(d *db.DB, id int64) error {
res, err := d.Exec(`UPDATE drafts SET status = ?, updated_at = ? WHERE id = ? AND status IN (?, ?)`,
+3 -1
View File
@@ -16,6 +16,7 @@ type Post struct {
SourceURL string // tagged, if it's the company's
Title string // Reddit
Target string // Reddit: the subreddit
AsPage bool // LinkedIn: post as the company page
}
// Publisher posts to one channel and returns the post's URL.
@@ -61,7 +62,8 @@ func Publish(ctx context.Context, d *db.DB, pubs Publishers, tags *utm.Tagger, i
}
text, src := Manual(dr, tags)
postURL, pubErr := pub.Publish(ctx, Post{Text: text, SourceURL: src, Title: dr.Title, Target: dr.Target})
postURL, pubErr := pub.Publish(ctx, Post{Text: text, SourceURL: src, Title: dr.Title, Target: dr.Target,
AsPage: dr.Channel == ChannelLinkedIn && dr.LinkedInAs == AsPage})
now := formatTime(time.Now())
if pubErr != nil {
if _, err := d.Exec(`UPDATE drafts SET status = ?, error = ?, updated_at = ? WHERE id = ?`,
+25
View File
@@ -609,6 +609,10 @@ ALTER TABLE site_pages ADD COLUMN live_at TEXT;
ALTER TABLE site_pages ADD COLUMN gone_at TEXT;
ALTER TABLE site_pages ADD COLUMN checked_at TEXT;
ALTER TABLE site_pages ADD COLUMN live_note TEXT NOT NULL DEFAULT '';
`,
// 25: a LinkedIn draft posts as the member ('') or the company page ('page').
`
ALTER TABLE drafts ADD COLUMN linkedin_as TEXT NOT NULL DEFAULT '';
`,
}
@@ -618,6 +622,14 @@ type DB struct {
}
// Open opens (creating if needed) the database at path and migrates it.
// BeforeMigrate, if set, runs before an existing database is migrated to
// a newer schema (from and to are the schema versions): the app backs it
// up. A new, empty database isn't backed up.
var BeforeMigrate func(d *sql.DB, from, to int) error
// Schema is the schema version this build migrates databases to.
func Schema() int { return len(migrations) }
func Open(path string) (*DB, error) {
// WAL lets the web UI read while a background job writes; busy_timeout
// waits out short write locks instead of failing.
@@ -634,6 +646,19 @@ func Open(path string) (*DB, error) {
return nil, fmt.Errorf("opening %s: %w", path, err)
}
d := &DB{sqldb}
if BeforeMigrate != nil {
var version int
if err := d.QueryRow(`PRAGMA user_version`).Scan(&version); err != nil {
sqldb.Close()
return nil, err
}
if version > 0 && version < len(migrations) {
if err := BeforeMigrate(sqldb, version, len(migrations)); err != nil {
sqldb.Close()
return nil, fmt.Errorf("backing up before migrating to schema %d: %w", len(migrations), err)
}
}
}
if err := d.migrate(); err != nil {
sqldb.Close()
return nil, err
+61
View File
@@ -0,0 +1,61 @@
package db
import (
"database/sql"
"errors"
"fmt"
"path/filepath"
"strings"
"testing"
)
func TestBeforeMigrate(t *testing.T) {
defer func() { BeforeMigrate = nil }()
var calls []string
BeforeMigrate = func(d *sql.DB, from, to int) error {
var n int
d.QueryRow(`PRAGMA user_version`).Scan(&n)
calls = append(calls, fmt.Sprintf("%d→%d at %d", from, to, n))
return nil
}
dir := t.TempDir()
// A new database: nothing to back up.
d, err := Open(filepath.Join(dir, "new.db"))
if err != nil {
t.Fatal(err)
}
d.Close()
// Already current: nothing either.
d, _ = Open(filepath.Join(dir, "new.db"))
d.Close()
if len(calls) != 0 {
t.Fatalf("called for a new or current database: %v", calls)
}
// One migration behind: backed up first, before the migration runs.
old := filepath.Join(dir, "old.db")
raw, _ := sql.Open("sqlite", "file:"+old)
for _, m := range migrations[:len(migrations)-1] {
if _, err := raw.Exec(m); err != nil {
t.Fatal(err)
}
}
raw.Exec(fmt.Sprintf(`PRAGMA user_version = %d`, len(migrations)-1))
raw.Close()
d, err = Open(old)
if err != nil {
t.Fatal(err)
}
d.Close()
want := fmt.Sprintf("%d→%d at %d", len(migrations)-1, len(migrations), len(migrations)-1)
if len(calls) != 1 || calls[0] != want || Schema() != len(migrations) {
t.Errorf("calls: %v, want %s", calls, want)
}
// A failed backup stops the migration.
raw, _ = sql.Open("sqlite", "file:"+old)
raw.Exec(fmt.Sprintf(`PRAGMA user_version = %d`, len(migrations)-1))
raw.Close()
BeforeMigrate = func(*sql.DB, int, int) error { return errors.New("disk full") }
if _, err := Open(old); err == nil || !strings.Contains(err.Error(), "disk full") {
t.Errorf("open: %v", err)
}
}
+52
View File
@@ -735,3 +735,55 @@ func hugoError(out string) string {
}
return pick
}
// InitPush makes the first commit of an empty repository: the files,
// committed on branch and pushed. The working copy is left at dir, ready
// for Sync. dir must not exist yet.
func InitPush(ctx context.Context, r *Repo, files map[string]string, message string) error {
if _, err := os.Stat(r.Dir); err == nil {
return fmt.Errorf("%s already exists", r.Dir)
}
if err := os.MkdirAll(r.Dir, 0o755); err != nil {
return err
}
ok := false
defer func() {
if !ok {
os.RemoveAll(r.Dir)
}
}()
if _, err := r.git(ctx, "init", "--quiet", "--initial-branch", r.Branch); err != nil {
return err
}
for rel, body := range files {
p, err := r.inside(rel)
if err != nil {
return err
}
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
return err
}
if err := os.WriteFile(p, []byte(body), 0o644); err != nil {
return err
}
}
for _, args := range [][]string{
{"add", "-A"},
{"commit", "--quiet", "-m", message},
{"remote", "add", "origin", r.CloneURL},
{"push", "--quiet", "origin", "HEAD:refs/heads/" + r.Branch},
{"fetch", "--quiet", "origin"},
} {
if _, err := r.git(ctx, args...); err != nil {
return err
}
}
ok = true
return nil
}
// BuildDir builds a Hugo site in dir into a temporary folder, returned for
// reading; the caller removes it.
func BuildDir(ctx context.Context, dir string) (string, error) {
return (&Repo{Dir: dir}).Build(ctx)
}
+23
View File
@@ -0,0 +1,23 @@
package oauth
import (
"net/url"
"testing"
)
func TestLinkedInStartScopes(t *testing.T) {
raw, p, err := LinkedInStartScopes("linkedin-page", "cid", "http://localhost:8470/auth/linkedin-page/callback", LinkedInPageScopes)
if err != nil {
t.Fatal(err)
}
u, _ := url.Parse(raw)
q := u.Query()
if q.Get("scope") != "w_organization_social r_organization_admin" || q.Get("client_id") != "cid" || q.Get("state") != p.State ||
p.Provider != "linkedin-page" || p.RedirectURI != "http://localhost:8470/auth/linkedin-page/callback" {
t.Errorf("%s %+v", raw, p)
}
raw, p, _ = LinkedInStart("cid", "http://x/cb")
if u, _ := url.Parse(raw); u.Query().Get("scope") != "w_member_social openid profile" || p.Provider != "linkedin" {
t.Errorf("member: %s", raw)
}
}
+13 -2
View File
@@ -113,9 +113,20 @@ const (
linkedInScopes = "w_member_social openid profile"
)
// LinkedInPageScopes are asked of the company page's app (the Community
// Management API): posting as the page, and listing the pages the member
// administers. The approved app's Auth tab shows what it may ask for.
const LinkedInPageScopes = "w_organization_social r_organization_admin"
// LinkedInStart begins LinkedIn's authorization-code flow (client secret,
// no PKCE).
func LinkedInStart(clientID, redirectURI string) (string, *Pending, error) {
return LinkedInStartScopes("linkedin", clientID, redirectURI, linkedInScopes)
}
// LinkedInStartScopes begins it for another LinkedIn app (the company
// page's), with its own provider name and scopes.
func LinkedInStartScopes(provider, clientID, redirectURI, scopes string) (string, *Pending, error) {
state, err := randomString()
if err != nil {
return "", nil, err
@@ -124,10 +135,10 @@ func LinkedInStart(clientID, redirectURI string) (string, *Pending, error) {
"response_type": {"code"},
"client_id": {clientID},
"redirect_uri": {redirectURI},
"scope": {linkedInScopes},
"scope": {scopes},
"state": {state},
}
p := &Pending{Provider: "linkedin", State: state, RedirectURI: redirectURI, Started: time.Now()}
p := &Pending{Provider: provider, State: state, RedirectURI: redirectURI, Started: time.Now()}
return linkedInAuthURL + "?" + params.Encode(), p, nil
}
+4
View File
@@ -29,6 +29,10 @@ const (
LinkedInClientSecret = "linkedin.client_secret"
LinkedInAccessToken = "linkedin.access_token"
LinkedInAuthorURN = "linkedin.author_urn"
// The company page's own LinkedIn app (Community Management API)
LinkedInPageClientID = "linkedin_page.client_id"
LinkedInPageClientSecret = "linkedin_page.client_secret"
LinkedInPageAccessToken = "linkedin_page.access_token"
YouTubeAPIKey = "youtube.api_key"
+36 -13
View File
@@ -82,25 +82,36 @@ var (
partialRef = regexp.MustCompile(`partial\s+"sections/([\w-]+)\.html"\s*(?:(\$s|\.)(?:\s|-?\}\}|\)))?`)
dollarS = regexp.MustCompile(`\$s\.([a-z]\w*)`)
bareDot = regexp.MustCompile(`(?:^|[\s(])\.([a-z]\w*)`)
typeTest = regexp.MustCompile(`eq \.type "([\w-]+)"`)
readmeList = regexp.MustCompile("^\\s*[-*]\\s+`([\\w-]+)`\\s+[—–-]+\\s+(.+)$")
readmeRow = regexp.MustCompile("^\\|\\s*`([\\w-]+)`\\s*\\|\\s*(.+?)\\s*\\|\\s*$")
)
// Read reads the catalogue from a working copy of the site.
func Read(dir string, pathOf PathFunc) (*Catalog, error) {
partDir := filepath.Join(dir, "layouts", "partials", "sections")
entries, err := os.ReadDir(partDir)
if err != nil && !os.IsNotExist(err) {
return nil, err
// The site's own layouts, then its themes' (the site's win, as in Hugo).
roots := []string{dir}
if themes, err := filepath.Glob(filepath.Join(dir, "themes", "*")); err == nil {
sort.Strings(themes)
roots = append(roots, themes...)
}
partials := map[string]string{}
for _, e := range entries {
if !e.IsDir() && strings.HasSuffix(e.Name(), ".html") {
for _, root := range roots {
partDir := filepath.Join(root, "layouts", "partials", "sections")
entries, err := os.ReadDir(partDir)
if err != nil && !os.IsNotExist(err) {
return nil, err
}
for _, e := range entries {
name := strings.TrimSuffix(e.Name(), ".html")
if e.IsDir() || !strings.HasSuffix(e.Name(), ".html") || partials[name] != "" {
continue
}
raw, err := os.ReadFile(filepath.Join(partDir, e.Name()))
if err != nil {
return nil, err
}
partials[strings.TrimSuffix(e.Name(), ".html")] = string(raw)
partials[name] = string(raw)
}
}
// Partials named by another partial, or by render-sections, are
@@ -115,9 +126,16 @@ func Read(dir string, pathOf PathFunc) (*Catalog, error) {
}
}
}
if raw, err := os.ReadFile(filepath.Join(dir, "layouts", "partials", "render-sections.html")); err == nil {
for _, m := range partialRef.FindAllStringSubmatch(string(raw), -1) {
referenced[m[1]] = true
dispatched := map[string]bool{} // types render-sections picks by name
for _, root := range roots {
if raw, err := os.ReadFile(filepath.Join(root, "layouts", "partials", "render-sections.html")); err == nil {
for _, m := range partialRef.FindAllStringSubmatch(string(raw), -1) {
referenced[m[1]] = true
}
for _, m := range typeTest.FindAllStringSubmatch(string(raw), -1) {
dispatched[m[1]] = true
}
break
}
}
@@ -135,7 +153,7 @@ func Read(dir string, pathOf PathFunc) (*Catalog, error) {
}
root := filepath.Join(dir, "content")
err = filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
if err != nil {
if os.IsNotExist(err) && p == root {
return fs.SkipDir
@@ -208,13 +226,18 @@ func Read(dir string, pathOf PathFunc) (*Catalog, error) {
}
for name := range partials {
if referenced[name] && uses[name] == nil {
if referenced[name] && uses[name] == nil && !dispatched[name] {
c.Helpers = append(c.Helpers, name)
continue
}
get(name)
}
docs := readmeDocs(dir)
docs := map[string]string{}
for i := len(roots) - 1; i >= 0; i-- { // the site's README wins
for k, v := range readmeDocs(roots[i]) {
docs[k] = v
}
}
for name, t := range uses {
_, has := partials[name]
t.Missing = !has
+32 -2
View File
@@ -8,6 +8,7 @@ import (
"os"
"regexp"
"slices"
"strconv"
"strings"
"time"
@@ -235,6 +236,9 @@ Rules:
out.Path = in.Path
}
out.Path = CleanPath(out.Path)
if in.Kind == "home" {
out.Path = "/"
}
return &out, nil
}
@@ -462,6 +466,12 @@ func tag(link, campaign, content string) string {
// FrontMatter is a page's content file: YAML front matter with its title,
// description and sections, and no body.
func FrontMatter(title, description, sectionsYAML string) (string, error) {
return frontMatter(title, description, sectionsYAML, "", 0)
}
// frontMatter is FrontMatter, with the page in a menu at weight when menu
// isn't "".
func frontMatter(title, description, sectionsYAML, menu string, weight int) (string, error) {
var secs yaml.Node
if err := yaml.Unmarshal([]byte(sectionsYAML), &secs); err != nil || len(secs.Content) == 0 {
return "", errors.New("the sections aren't valid YAML")
@@ -473,6 +483,11 @@ func FrontMatter(title, description, sectionsYAML string) (string, error) {
str("date"), str(time.Now().Format("2006-01-02")),
str("sections"), secs.Content[0],
}}
if menu != "" {
m.Content = append(m.Content[:6], append([]*yaml.Node{str("menus"), {Kind: yaml.MappingNode, Content: []*yaml.Node{
str(menu), {Kind: yaml.MappingNode, Content: []*yaml.Node{str("weight"), {Kind: yaml.ScalarNode, Tag: "!!int", Value: strconv.Itoa(weight)}}},
}}}, m.Content[6:]...)...)
}
var b strings.Builder
enc := yaml.NewEncoder(&b)
enc.SetIndent(2)
@@ -489,7 +504,10 @@ func FrontMatter(title, description, sectionsYAML string) (string, error) {
// with a build, and opens a pull request if pr is set and none is open.
// The page must have been checked and its claims confirmed.
func Push(ctx context.Context, d *db.DB, ap *seo.Applier, p *SitePage, pr bool) error {
if strings.TrimSpace(p.Title) == "" || p.Path == "" || p.Path == "/" {
if p.Kind == "home" {
p.Path = "/"
}
if strings.TrimSpace(p.Title) == "" || p.Path == "" || (p.Path == "/" && p.Kind != "home") {
return errors.New("give the page a title and an address")
}
p.Status, p.Error = PageWorking, ""
@@ -516,6 +534,14 @@ func push(ctx context.Context, ap *seo.Applier, p *SitePage, pr bool) error {
return err
}
defer wc.Release()
if p.File == "" && p.Kind == "home" {
// The home page replaces the site's own.
file, err := wc.FindContent("/")
if err != nil {
file = "content/_index.md"
}
p.File = file
}
if p.File == "" {
if file, err := wc.FindContent(p.Path); err == nil {
return fmt.Errorf("the site already has a page at %s (%s): choose another address", p.Path, file)
@@ -526,7 +552,11 @@ func push(ctx context.Context, ap *seo.Applier, p *SitePage, pr bool) error {
if err := wc.NewBranch(ctx, p.Branch); err != nil {
return err
}
body, err := FrontMatter(p.Title, p.Description, p.Sections)
menu := ""
if menuWeight(p.Kind) > 0 {
menu = "main"
}
body, err := frontMatter(p.Title, p.Description, p.Sections, menu, menuWeight(p.Kind))
if err != nil {
return err
}
+277
View File
@@ -0,0 +1,277 @@
package sites
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"os"
"regexp"
"strconv"
"strings"
"time"
"supermarket/internal/api/gitea"
"supermarket/internal/hugorepo"
"supermarket/internal/seo"
"supermarket/internal/theme"
)
// Lead forms: a site's `form` sections post to EspoCRM's Lead Capture
// (Administration → Lead Capture), which takes a JSON POST without a login
// at <crm>/api/v1/LeadCapture/<api key> and allows posts from other sites
// (leadCaptureAllowOrigin, "*" by default). Supermarket is local-only, so
// it can't take the posts itself. The site's form fields are the site's
// own (name, email, organization…), so a small script maps them onto the
// Lead's fields; what doesn't map, the page, the form's name and the visit's
// UTM tags go in the description, so the CRM shows which signal brought it.
// LeadScriptPath is where the script goes in the site.
const LeadScriptPath = "static/js/supermarket-leads.js"
// LeadPayloadFields are the Lead fields the script sends: the Lead
// Capture's "Payload Fields" must list them all.
var LeadPayloadFields = []string{"First Name", "Last Name", "Email", "Account Name", "Phone", "Description"}
// leadScript defines window.leadPost(form, data), which the form's own
// script calls in place of its fetch: it returns the fetch's promise. It's
// the theme's, so new sites have it from the start.
var leadScript = theme.LeadScript()
var (
captureURL = regexp.MustCompile(`^https://[^/\s]+/(?:[^\s?#]*/)?api/v1/LeadCapture/[A-Za-z0-9]+$`)
// The form partial's own post, which leadPost takes over.
formFetch = regexp.MustCompile(`fetch\(form\.action,\s*\{(?:[^{}]|\{[^{}]*\})*\bbody:\s*data\b(?:[^{}]|\{[^{}]*\})*\}\s*\)`)
leadsTable = regexp.MustCompile(`(?m)^\[params\.leads\][ \t]*$`)
actionLine = regexp.MustCompile(`(?m)^([ \t]*)action[ \t]*=[ \t]*("[^"\n]*"|'[^'\n]*')(.*)$`)
nextTable = regexp.MustCompile(`(?m)^\[`)
leadsAction = regexp.MustCompile(`(?ms)^\[params\.leads\][ \t]*$.*?^[ \t]*action[ \t]*=[ \t]*["']([^"'\n]*)["']`)
)
// CheckCaptureURL checks a Lead Capture address's shape: https, and the
// /api/v1/LeadCapture/<key> path EspoCRM shows on the Lead Capture.
func CheckCaptureURL(u string) error {
if !captureURL.MatchString(strings.TrimSpace(u)) {
return errors.New("that isn't a Lead Capture address: it looks like https://<your CRM>/api/v1/LeadCapture/<API key>, as shown on the Lead Capture in EspoCRM")
}
return nil
}
// TestCapture asks EspoCRM, the way a browser on the site would before
// posting (a CORS preflight), whether the site may post to the Lead
// Capture. Nothing is created.
func TestCapture(ctx context.Context, client *http.Client, capture, siteURL string) error {
if err := CheckCaptureURL(capture); err != nil {
return err
}
origin := strings.TrimRight(siteURL, "/")
if u, err := url.Parse(siteURL); err == nil {
origin = u.Scheme + "://" + u.Host
}
req, err := http.NewRequestWithContext(ctx, http.MethodOptions, capture, nil)
if err != nil {
return err
}
req.Header.Set("Origin", origin)
req.Header.Set("Access-Control-Request-Method", "POST")
req.Header.Set("Access-Control-Request-Headers", "content-type")
res, err := client.Do(req)
if err != nil {
return fmt.Errorf("couldn't reach the CRM: %w", err)
}
res.Body.Close()
if res.StatusCode >= 400 {
return fmt.Errorf("the CRM answered %d: check the address, and that Lead Capture is on (EspoCRM 7 or later)", res.StatusCode)
}
allow := res.Header.Get("Access-Control-Allow-Origin")
if allow != "*" && !strings.EqualFold(allow, origin) {
if allow == "" {
return fmt.Errorf("the CRM doesn't let %s post to it: set leadCaptureAllowOrigin in EspoCRM's data/config.php to \"*\" or to %s", origin, origin)
}
return fmt.Errorf("the CRM only lets %s post to it, not %s: set leadCaptureAllowOrigin in EspoCRM's data/config.php", allow, origin)
}
return nil
}
// SetLeadsAction sets [params.leads] action in a TOML config, adding the
// table if there isn't one.
func SetLeadsAction(cfg, capture string) string {
val := strconv.Quote(capture)
loc := leadsTable.FindStringIndex(cfg)
if loc == nil {
return strings.TrimRight(cfg, "\n") + "\n\n# Where the site's lead forms post: EspoCRM's Lead Capture (set by Supermarket).\n[params.leads]\n action = " + val + "\n"
}
body := cfg[loc[1]:]
end := len(body)
if n := nextTable.FindStringIndex(body[1:]); n != nil {
end = n[0] + 1
}
section := body[:end]
if m := actionLine.FindStringSubmatchIndex(section); m != nil {
indent := section[m[2]:m[3]]
section = section[:m[0]] + indent + "action = " + val + section[m[6]:m[7]] + section[m[1]:]
} else {
section = "\n action = " + val + section
}
return cfg[:loc[1]] + section + body[end:]
}
// LeadsAction reads [params.leads] action from a TOML config.
func LeadsAction(cfg string) string {
if m := leadsAction.FindStringSubmatch(cfg); m != nil {
return m[1]
}
return ""
}
// PatchFormPartial makes the form partial post through leadPost: the
// script is loaded at its top, and its fetch goes through leadPost when
// it's there. ok is false when the partial doesn't post the way
// Supermarket knows (it's left alone then).
func PatchFormPartial(src string) (out string, ok bool) {
if strings.Contains(src, "window.leadPost") {
return src, true // already done
}
call := formFetch.FindString(src)
if call == "" {
return src, false
}
src = strings.Replace(src, call, "(window.leadPost ? window.leadPost(form, data) : "+call+")", 1)
tag := `<script src="{{ "js/supermarket-leads.js" | relURL }}"></script>` + "\n"
// After the opening comment, if there is one, so the comment stays first.
if strings.HasPrefix(strings.TrimSpace(src), "{{/*") {
if i := strings.Index(src, "*/}}"); i >= 0 {
j := i + len("*/}}")
return src[:j] + "\n" + tag + strings.TrimLeft(src[j:], "\n"), true
}
}
return tag + src, true
}
// FormState is how a site's lead forms are set up, read from its working
// copy.
type FormState struct {
Action string // [params.leads] action: where the forms post now
Script bool // the mapping script is in the site
Patched bool // the form partial posts through it
Supported bool // the form partial posts in the way Supermarket knows
Config string // the config file
Pages []string // pages with a form section
}
// ReadForms reads a site's lead form set-up.
func ReadForms(wc *hugorepo.Repo, cat *Catalog) FormState {
st := FormState{Config: wc.ConfigFile()}
if st.Config != "" {
if raw, err := os.ReadFile(wc.Dir + "/" + st.Config); err == nil {
st.Action = LeadsAction(string(raw))
}
}
st.Script = wc.Exists(LeadScriptPath) || wc.Exists(theme.Dir+"/"+LeadScriptPath)
if raw, err := os.ReadFile(wc.Dir + "/layouts/partials/sections/form.html"); err == nil {
st.Patched = strings.Contains(string(raw), "window.leadPost")
_, st.Supported = PatchFormPartial(string(raw))
} else if raw, err := os.ReadFile(wc.Dir + "/" + theme.Dir + "/layouts/partials/sections/form.html"); err == nil {
// The theme's form already posts through the script.
st.Patched = strings.Contains(string(raw), "window.leadPost")
st.Supported = st.Patched
}
if cat != nil {
if t := cat.Type("form"); t != nil {
st.Pages = t.Pages
}
}
return st
}
// Connected says whether the forms post to this Lead Capture.
func (st FormState) Connected(capture string) bool {
return capture != "" && st.Action == capture && st.Script && st.Patched
}
// ConnectForms opens a pull request that points the site's lead forms at
// the Lead Capture: the address in the config, the mapping script, and the
// form partial posting through it. It's checked with a build: a page with
// a form must load the script.
func ConnectForms(ctx context.Context, ap *seo.Applier, capture string, formPage string) (*gitea.Pull, error) {
if err := CheckCaptureURL(capture); err != nil {
return nil, err
}
wc, full, published, err := ap.WorkingCopy(ctx)
if err != nil {
return nil, err
}
defer wc.Release()
cfg := wc.ConfigFile()
if !strings.HasSuffix(cfg, ".toml") {
return nil, errors.New("the site's settings aren't in a TOML file (hugo.toml), which is all Supermarket can change for now")
}
partial := "layouts/partials/sections/form.html"
var files []struct{ path, body string }
if raw, err := os.ReadFile(wc.Dir + "/" + partial); err == nil {
patched, ok := PatchFormPartial(string(raw))
if !ok {
return nil, errors.New("the site's form section doesn't post the way Supermarket knows (a fetch of form.action with the form's data), so it can't be connected automatically")
}
files = append(files, struct{ path, body string }{partial, patched}, struct{ path, body string }{LeadScriptPath, leadScript})
} else if raw, err := os.ReadFile(wc.Dir + "/" + theme.Dir + "/" + partial); err == nil && strings.Contains(string(raw), "window.leadPost") {
// Supermarket's theme: its form and script are ready; only the address is needed.
} else {
return nil, errors.New("the site has no form section (layouts/partials/sections/form.html)")
}
branch := "supermarket/lead-forms"
if err := wc.NewBranch(ctx, branch); err != nil {
return nil, err
}
cfgRaw, err := os.ReadFile(wc.Dir + "/" + cfg)
if err != nil {
return nil, err
}
files = append(files, struct{ path, body string }{cfg, SetLeadsAction(string(cfgRaw), capture)})
for _, f := range files {
if err := wc.WriteFile(f.path, f.body); err != nil {
return nil, err
}
}
note := "Not checked with a build: there's no Hugo in Supermarket's image."
if hugorepo.HugoVersion(ctx) != "" {
out, err := wc.Build(ctx)
if err != nil {
return nil, fmt.Errorf("with the forms connected, %w", err)
}
defer os.RemoveAll(out)
note = "Checked with a build: the site builds."
if formPage != "" {
html, err := hugorepo.BuiltFile(out, strings.Trim(formPage, "/")+"/index.html")
if err != nil || !strings.Contains(html, "supermarket-leads.js") || !strings.Contains(html, capture) {
return nil, fmt.Errorf("the site builds, but %s doesn't load the script or post to the Lead Capture", formPage)
}
note = "Checked with a build: the site builds, and " + formPage + " loads the script and posts to the Lead Capture."
}
}
subject := "Sites: send the lead forms to EspoCRM"
if err := wc.CommitAndPush(ctx, branch, subject); err != nil {
return nil, err
}
body := fmt.Sprintf(`Points the site's lead forms at EspoCRM's Lead Capture, so each one creates a Lead.
- `+"`%s`"+`: `+"`[params.leads] action`"+` is the Lead Capture's address.
- `+"`%s`"+`: maps the form's fields onto the Lead's (name → first and last name, email, organization → account name, phone); everything else, the form's name, the page and the visit's UTM tags go in the description, so the CRM shows which campaign brought it.
- `+"`%s`"+`: loads the script and posts through it.
The Lead Capture's Payload Fields must include: %s.
%s
Merging publishes it: test a form on the live site afterwards, and look for the Lead in EspoCRM.`,
cfg, LeadScriptPath, partial, strings.Join(LeadPayloadFields, ", "), note)
pull, err := ap.Gitea.OpenPull(ctx, full, branch, published, subject, body)
if err != nil {
return nil, err
}
return pull, nil
}
// TestClient is the HTTP client TestCapture uses in the app.
func TestClient() *http.Client { return &http.Client{Timeout: 20 * time.Second} }
+199
View File
@@ -0,0 +1,199 @@
package sites
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
func TestCheckCaptureURL(t *testing.T) {
for u, ok := range map[string]bool{
"https://espocrm.federated.computer/api/v1/LeadCapture/a1b2c3": true,
"https://crm.example.com/espo/api/v1/LeadCapture/ABC123": true,
"http://espocrm.example.com/api/v1/LeadCapture/abc": false,
"https://espocrm.example.com/api/v1/Lead": false,
"https://espocrm.example.com/api/v1/LeadCapture/": false,
"https://espocrm.example.com/api/v1/LeadCapture/abc?x=1": false,
"javascript:alert(1)": false,
} {
if err := CheckCaptureURL(u); (err == nil) != ok {
t.Errorf("%s: %v", u, err)
}
}
}
func TestSetLeadsAction(t *testing.T) {
const cap = "https://crm.example/api/v1/LeadCapture/k1"
fed := "title = 'Site'\n\n# where forms go\n[params.leads]\n action = \"\" # empty opens an email\n email = \"info@example.com\"\n\n[params.order]\n api = \"\"\n"
got := SetLeadsAction(fed, cap)
want := "title = 'Site'\n\n# where forms go\n[params.leads]\n action = \"https://crm.example/api/v1/LeadCapture/k1\" # empty opens an email\n email = \"info@example.com\"\n\n[params.order]\n api = \"\"\n"
if got != want {
t.Errorf("existing:\n%s\nwant\n%s", got, want)
}
if LeadsAction(got) != cap || LeadsAction(fed) != "" {
t.Errorf("read back: %q", LeadsAction(got))
}
// No action line in the table: added; no table: appended.
got = SetLeadsAction("[params.leads]\n email = \"x@y\"\n[other]\n action = \"keep\"\n", cap)
if !strings.HasPrefix(got, "[params.leads]\n action = \""+cap+"\"\n email") || !strings.Contains(got, "[other]\n action = \"keep\"") {
t.Errorf("no action line:\n%s", got)
}
got = SetLeadsAction("title = 'x'\n", cap)
if !strings.HasSuffix(got, "[params.leads]\n action = \""+cap+"\"\n") || LeadsAction(got) != cap {
t.Errorf("no table:\n%s", got)
}
}
const formPartial = `{{/*
A lead form.
*/}}
{{ $s := . }}
<div class="lead"><form class="lead-form" action="{{ site.Params.leads.action }}"></form></div>
<script>
(function () {
var form = document.currentScript.previousElementSibling.querySelector('form');
form.addEventListener('submit', function (e) {
var data = new FormData(form);
fetch(form.action, { method: 'POST', body: data, headers: { Accept: 'application/json' } })
.then(function (r) { if (!r.ok) throw new Error(r.status); });
});
})();
</script>
`
func TestPatchFormPartial(t *testing.T) {
out, ok := PatchFormPartial(formPartial)
if !ok {
t.Fatal("not patched")
}
if !strings.HasPrefix(out, "{{/*\n A lead form.\n*/}}\n<script src=\"{{ \"js/supermarket-leads.js\" | relURL }}\"></script>\n{{ $s := . }}") {
t.Errorf("script tag:\n%s", out)
}
if !strings.Contains(out, "(window.leadPost ? window.leadPost(form, data) : fetch(form.action, { method: 'POST', body: data, headers: { Accept: 'application/json' } }))") {
t.Errorf("fetch:\n%s", out)
}
// The form's script still follows the form's div directly.
if !strings.Contains(out, "</div>\n<script>\n (function") {
t.Error("something came between the form and its script")
}
again, ok := PatchFormPartial(out)
if !ok || again != out {
t.Error("patching twice changed it")
}
if _, ok := PatchFormPartial(`<form action="/x"></form>`); ok {
t.Error("an unknown form was patched")
}
if out, _ := PatchFormPartial(strings.TrimPrefix(formPartial, "{{/*\n A lead form.\n*/}}\n")); !strings.HasPrefix(out, "<script src=") {
t.Errorf("no comment: %s", out[:60])
}
}
func TestTestCapture(t *testing.T) {
allow := "*"
status := 200
var got *http.Request
srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
got = r
if allow != "" {
w.Header().Set("Access-Control-Allow-Origin", allow)
}
w.WriteHeader(status)
}))
defer srv.Close()
capture := srv.URL + "/api/v1/LeadCapture/abc123"
site := "https://www.site.example/"
if err := TestCapture(context.Background(), srv.Client(), capture, site); err != nil {
t.Fatal(err)
}
if got.Method != http.MethodOptions || got.Header.Get("Origin") != "https://www.site.example" || got.Header.Get("Access-Control-Request-Method") != "POST" {
t.Errorf("request: %s %v", got.Method, got.Header)
}
allow = "https://www.site.example"
if err := TestCapture(context.Background(), srv.Client(), capture, site); err != nil {
t.Errorf("exact origin: %v", err)
}
for _, c := range []struct {
allow string
status int
want string
}{{"https://other.example", 200, "only lets https://other.example"}, {"", 200, "doesn't let https://www.site.example"}, {"*", 404, "answered 404"}} {
allow, status = c.allow, c.status
if err := TestCapture(context.Background(), srv.Client(), capture, site); err == nil || !strings.Contains(err.Error(), c.want) {
t.Errorf("%+v: %v", c, err)
}
}
}
// TestLeadScript runs the mapping script in Node, with a form's data.
func TestLeadScript(t *testing.T) {
node, err := exec.LookPath("node")
if err != nil {
t.Skip("no node")
}
harness := `
globalThis.window = globalThis;
globalThis.location = { search: '?utm_campaign=churches&utm_source=email&utm_medium=outreach', origin: 'https://site.example' };
globalThis.document = { referrer: 'https://mail.example/' };
let sent;
globalThis.fetch = (url, opts) => { sent = { url, opts }; return Promise.resolve({ ok: true }); };
const labels = { users: 'How many people?' };
const form = {
action: 'https://crm.example/api/v1/LeadCapture/k1',
querySelector(sel) {
let m = sel.match(/name="([^"]+)"/);
if (m) return { id: 'lead-' + m[1] };
m = sel.match(/for="lead-([^"]+)"/);
if (m && labels[m[1]]) return { childNodes: [{ textContent: labels[m[1]] + ' ' }] };
return null;
}
};
` + leadScript + `
const data = new FormData();
data.append('source', 'Church cost comparison');
data.append('name', 'Mary Ann Smith');
data.append('email', 'mary@church.example');
data.append('organization', 'First Church');
data.append('users', '40');
data.append('notes', '');
data.append('page', '/churches/');
window.leadPost(form, data).then(r => {
console.log(JSON.stringify({ ok: r.ok, url: sent.url, method: sent.opts.method, type: sent.opts.headers['Content-Type'], body: JSON.parse(sent.opts.body) }));
});
`
path := filepath.Join(t.TempDir(), "harness.js")
os.WriteFile(path, []byte(harness), 0o600)
out, err := exec.Command(node, path).CombinedOutput()
if err != nil {
t.Fatalf("node: %v %s", err, out)
}
var got struct {
OK bool
URL string
Method string
Type string
Body map[string]any
}
if err := json.Unmarshal(out, &got); err != nil {
t.Fatalf("%v: %s", err, out)
}
if !got.OK || got.URL != "https://crm.example/api/v1/LeadCapture/k1" || got.Method != "POST" || got.Type != "application/json" {
t.Errorf("request: %+v", got)
}
want := map[string]any{"firstName": "Mary Ann", "lastName": "Smith", "emailAddress": "mary@church.example",
"accountName": "First Church", "phoneNumber": nil,
"description": "Form: Church cost comparison\nHow many people?: 40\nPage: https://site.example/churches/\nutm_campaign: churches\nutm_source: email\nutm_medium: outreach\nCame from: https://mail.example/"}
for k, v := range want {
if got.Body[k] != v {
t.Errorf("%s: %#v, want %#v", k, got.Body[k], v)
}
}
if len(got.Body) != len(want) {
t.Errorf("fields sent: %v", got.Body)
}
}
+209
View File
@@ -0,0 +1,209 @@
package sites
import (
"context"
"errors"
"fmt"
"net/url"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"unicode"
"supermarket/internal/api/gitea"
"supermarket/internal/hugorepo"
"supermarket/internal/theme"
)
// NewSite is what a new site starts from.
type NewSite struct {
Repo string // owner/name: an empty repository the user made
URL string // where it will be published, https://…
Title string
Tagline string
Email string // where lead forms send while they aren't connected
Dark string // #rrggbb
Primary string
Accent string
Font string // a Google Fonts family
Logo string // an image's address, or ""
}
var (
hexColor = regexp.MustCompile(`^#[0-9a-fA-F]{6}$`)
fontName = regexp.MustCompile(`^[A-Za-z0-9 ]{2,40}$`)
)
// Fonts are offered for a new site (any Google Fonts family works).
var Fonts = []string{"Inter", "IBM Plex Sans", "Manrope", "DM Sans", "Source Sans 3", "Work Sans", "Lato", "Merriweather Sans"}
// Defaults are the theme's own brand: Federated Computer's.
func Defaults() NewSite {
return NewSite{Dark: "#001a2b", Primary: "#e0ff4f", Accent: "#614efa", Font: "Inter"}
}
// Check checks a new site's settings and tidies them.
func (n *NewSite) Check() error {
n.Repo, n.URL, n.Title = strings.TrimSpace(n.Repo), strings.TrimRight(strings.TrimSpace(n.URL), "/"), strings.TrimSpace(n.Title)
n.Tagline, n.Email, n.Logo = strings.TrimSpace(n.Tagline), strings.TrimSpace(n.Email), strings.TrimSpace(n.Logo)
if _, full, err := gitea.ParseRepo(n.Repo); err != nil {
return fmt.Errorf("the repository: %v", err)
} else {
n.Repo = full
}
if u, err := url.Parse(n.URL); err != nil || u.Scheme != "https" || u.Host == "" || (u.Path != "" && u.Path != "/") {
return errors.New("the site's address must be like https://www.example.com")
}
if n.Title == "" {
return errors.New("give the site a name")
}
for _, v := range []string{n.Title, n.Tagline, n.Email, n.Logo} {
if strings.ContainsFunc(v, unicode.IsControl) {
return errors.New("the name, tagline, email and logo can't contain line breaks or tabs")
}
}
if n.Email != "" && !strings.Contains(n.Email, "@") {
return errors.New("that isn't an email address")
}
for _, c := range []*string{&n.Dark, &n.Primary, &n.Accent} {
*c = strings.TrimSpace(*c)
if !hexColor.MatchString(*c) {
return fmt.Errorf("%q isn't a color like #1d1238", *c)
}
}
n.Font = strings.TrimSpace(n.Font)
if !fontName.MatchString(n.Font) {
return errors.New("the font must be a Google Fonts family, like Inter")
}
if n.Logo != "" {
if u, err := url.Parse(n.Logo); err != nil || (u.Scheme != "https" && !strings.HasPrefix(n.Logo, "/")) {
return errors.New("the logo must be an https:// address, or a path on the site like /images/logo.svg")
}
}
return nil
}
func q(s string) string { return strconv.Quote(s) }
// Files are the new site's first commit: the theme, hugo.toml, a starter
// home page, a README and a .gitignore.
func (n NewSite) Files() map[string]string {
files := map[string]string{}
for p, body := range theme.Files() {
files[theme.Dir+"/"+p] = body
}
var b strings.Builder
fmt.Fprintf(&b, "baseURL = %s\nlanguageCode = \"en-us\"\ntitle = %s\ntheme = %s\n", q(n.URL+"/"), q(n.Title), q(theme.Name))
b.WriteString("disableKinds = [\"taxonomy\", \"term\"]\n\n[params]\n")
fmt.Fprintf(&b, " tagline = %s\n\n[params.brand]\n", q(n.Tagline))
fmt.Fprintf(&b, " dark = %s\n primary = %s\n accent = %s\n font = %s\n", q(n.Dark), q(n.Primary), q(n.Accent), q(n.Font))
if n.Logo != "" {
fmt.Fprintf(&b, " logo = %s\n", q(n.Logo))
}
b.WriteString("\n[params.header]\n ctas = [{ label = \"Contact us\", url = \"/contact/\", style = \"primary\" }]\n")
fmt.Fprintf(&b, "\n[params.footer]\n tagline = %s\n groups = [{ title = \"Company\", menu = \"footer_company\" }]\n", q(n.Tagline))
b.WriteString("\n# Where the lead forms post: EspoCRM's Lead Capture (Supermarket → Sites → Lead forms).\n")
fmt.Fprintf(&b, "[params.leads]\n action = \"\"\n email = %s\n", q(n.Email))
b.WriteString("\n[[menu.main]]\n name = \"Home\"\n url = \"/\"\n weight = 1\n")
files["hugo.toml"] = b.String()
tagline := n.Tagline
if tagline == "" {
tagline = "Welcome."
}
files["content/_index.md"] = fmt.Sprintf(`---
title: %s
description: %s
sections:
- type: hero
title: %s
subhead: %s
ctas:
- label: "Contact us"
url: "/contact/"
style: primary
- type: final-cta
headline: "Talk to us"
body: "Tell us what you need, and we'll get back to you."
ctas:
- label: "Contact us"
url: "/contact/"
style: primary
---
`, q(n.Title), q(tagline), q(n.Title), q(tagline))
files["README.md"] = fmt.Sprintf(`# %s
The website at %s, a [Hugo](https://gohugo.io/) site made with
Supermarket's theme (`+"`themes/supermarket`"+`; its README lists the section
types and the settings in `+"`hugo.toml`"+`).
Pages are in `+"`content/`"+`: each page's front matter has a `+"`sections:`"+` list.
Supermarket changes the site through pull requests; merging publishes.
Run `+"`hugo server`"+` to see it locally.
`, n.Title, n.URL)
files[".gitignore"] = "/public/\n/resources/_gen/\n.hugo_build.lock\n"
return files
}
// Create makes the site: it checks the repository is empty and Supermarket
// may push to it, builds the files with Hugo (when there is one) so nothing
// broken is pushed, then makes the first commit on the default branch and
// leaves the working copy at dir. It returns the branch.
func Create(ctx context.Context, g *gitea.Client, n NewSite, dir, author string) (string, error) {
if err := n.Check(); err != nil {
return "", err
}
if g == nil {
return "", errors.New("save a Gitea token under Settings → Search engines first")
}
repo, err := g.GetRepo(ctx, n.Repo)
if err != nil {
return "", fmt.Errorf("couldn't read %s on Gitea (create it first, empty): %w", n.Repo, err)
}
if !repo.Permissions.Push {
return "", fmt.Errorf("the Gitea token can't push to %s", n.Repo)
}
if !repo.Empty {
return "", fmt.Errorf("%s isn't empty: Supermarket only starts sites in an empty repository (create it without a README or license)", n.Repo)
}
branch := repo.DefaultBranch
if branch == "" {
branch = "main"
}
files := n.Files()
if hugorepo.HugoVersion(ctx) != "" {
tmp, err := os.MkdirTemp("", "supermarket-newsite-")
if err != nil {
return "", err
}
defer os.RemoveAll(tmp)
for rel, body := range files {
p := filepath.Join(tmp, rel)
os.MkdirAll(filepath.Dir(p), 0o755)
if err := os.WriteFile(p, []byte(body), 0o644); err != nil {
return "", err
}
}
out, err := hugorepo.BuildDir(ctx, tmp)
if err != nil {
return "", fmt.Errorf("the new site wouldn't build: %w", err)
}
os.RemoveAll(out)
}
wc := &hugorepo.Repo{Dir: dir, CloneURL: repo.CloneURL, Token: g.Token(), Branch: branch, Author: author}
wc.Acquire()
defer wc.Release()
if _, err := os.Stat(dir); err == nil {
// A copy left from before (an earlier attempt): the repository is
// empty, so there's nothing in it to keep.
if err := os.RemoveAll(dir); err != nil {
return "", err
}
}
if err := hugorepo.InitPush(ctx, wc, files, "Start the site with Supermarket's theme"); err != nil {
return "", err
}
return branch, nil
}
+69
View File
@@ -0,0 +1,69 @@
package sites
import (
"context"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"supermarket/internal/hugorepo"
)
func TestNewSiteFiles(t *testing.T) {
n := Defaults()
n.Repo, n.URL, n.Title, n.Tagline, n.Email = " https://gitea.example/Us/acme.git ", "https://www.acme.example/", `Acme "Widgets" & Co`, "Wïdgets, for everyone", "hi@acme.example"
if err := n.Check(); err != nil {
t.Fatal(err)
}
if n.Repo != "Us/acme" || n.URL != "https://www.acme.example" {
t.Errorf("tidied: %+v", n)
}
f := n.Files()
if !strings.Contains(f["hugo.toml"], `title = "Acme \"Widgets\" & Co"`) {
t.Errorf("hugo.toml:\n%s", f["hugo.toml"])
}
// Hugo reads the settings and builds the site, the title as given.
if _, err := exec.LookPath("hugo"); err == nil {
dir := t.TempDir()
for rel, body := range f {
os.MkdirAll(filepath.Join(dir, filepath.Dir(rel)), 0o755)
os.WriteFile(filepath.Join(dir, rel), []byte(body), 0o644)
}
out, err := hugorepo.BuildDir(context.Background(), dir)
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(out)
home, _ := os.ReadFile(filepath.Join(out, "index.html"))
if !strings.Contains(string(home), "<title>Acme &#34;Widgets&#34; &amp; Co — Wïdgets, for everyone</title>") {
t.Errorf("built home: %.600s", home)
}
}
if !strings.Contains(f["content/_index.md"], `title: "Acme \"Widgets\" & Co"`) || f["themes/supermarket/VERSION"] != "1\n" {
t.Errorf("home: %s", f["content/_index.md"])
}
for _, bad := range []NewSite{{Title: "x\ny"}, {Dark: "red"}, {Font: "Comic<Sans>"}, {Logo: "javascript:alert(1)"}, {URL: "https://x.example/path"}} {
m := Defaults()
m.Repo, m.URL, m.Title = "Us/acme", "https://acme.example", "Acme"
if bad.Title != "" {
m.Title = bad.Title
}
if bad.Dark != "" {
m.Dark = bad.Dark
}
if bad.Font != "" {
m.Font = bad.Font
}
if bad.Logo != "" {
m.Logo = bad.Logo
}
if bad.URL != "" {
m.URL = bad.URL
}
if err := m.Check(); err == nil {
t.Errorf("accepted %+v", bad)
}
}
}
+17
View File
@@ -33,6 +33,23 @@ var Kinds = []struct{ ID, Label, Guide string }{
"A side-by-side \"<us> vs <competitor>\" page: a short verdict, a comparison table, who each one is best for (honestly, including when the competitor fits better), an FAQ, a call to action. Say only what you're given about the competitor."},
{"blog", "Blog post",
"A blog post that teaches something useful to our customers, mostly text sections, ending with one call to action."},
{"home", "Home page",
"The site's home page (it replaces the current one): what the company does and for whom in the hero, its products or services, why choose it, proof it really has, and a call to action, ending with the closing band."},
{"about", "About page",
"An about page: who the company is, what it believes, how it works, where it is; only facts given here. It joins the top menu."},
{"contact", "Contact page",
"A contact page built around the site's lead form (the form section): a short heading, what happens after someone writes, the form with name, email, organization and a message, and other ways to reach the company. It joins the top menu."},
}
// menuWeight is where a kind of page goes in the top menu (0: not in it).
func menuWeight(kind string) int {
switch kind {
case "about":
return 80
case "contact":
return 90
}
return 0
}
// KindLabel is a kind's name for people.
+49
View File
@@ -0,0 +1,49 @@
package sites
import (
"slices"
"strings"
"testing"
"supermarket/internal/theme"
)
func TestReadThemeSite(t *testing.T) {
files := map[string]string{
"hugo.toml": "theme = 'supermarket'\n",
"content/_index.md": "---\ntitle: Home\nsections:\n - type: hero\n title: Hi\n - type: faq\n items: [{q: A, a: B}]\n---\n",
"README.md": "| `faq` | the site's own words |\n",
"layouts/partials/sections/faq.html": "{{ $s := . }}{{ range $s.items }}{{ .q }}{{ .a }}{{ end }}",
}
for p, b := range theme.Files() {
files[theme.Dir+"/"+p] = b
}
dir := write(t, files)
c, err := Read(dir, path)
if err != nil {
t.Fatal(err)
}
var names []string
for _, ty := range c.Types {
names = append(names, ty.Name)
}
slices.Sort(names)
want := []string{"callout", "cards", "checklist", "faq", "features", "final-cta", "form", "hero", "split", "stats", "steps", "table", "text"}
if !slices.Equal(names, want) {
t.Errorf("types: %v", names)
}
if !slices.Equal(c.Helpers, []string{"ctas", "head", "wrapper"}) {
t.Errorf("helpers: %v", c.Helpers)
}
if d := c.Type("hero").Doc; !strings.Contains(d, "`eyebrow`, `title`, `subhead`") {
t.Errorf("hero doc from the theme: %q", d)
}
// The site's own README and layout win over the theme's.
faq := c.Type("faq")
if faq.Doc != "the site's own words" || slices.Contains(faq.Layout, "ctas") {
t.Errorf("faq: %+v", faq)
}
if c.Type("form").Missing || !slices.Contains(c.Type("table").Layout, "rows") {
t.Errorf("form/table: %+v %+v", c.Type("form"), c.Type("table"))
}
}
+181
View File
@@ -0,0 +1,181 @@
package sites
import (
"context"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"supermarket/internal/api/gitea"
"supermarket/internal/hugorepo"
"supermarket/internal/seo"
"supermarket/internal/theme"
)
// ThemeState is a site's copy of Supermarket's theme.
type ThemeState struct {
Has bool
Version int // the copy's; 0 when its VERSION can't be read
Latest int // Supermarket's
Edited []string // files changed by hand since the copy was made
}
// Outdated says whether Supermarket has a newer theme than the copy.
func (t ThemeState) Outdated() bool { return t.Has && t.Version < t.Latest }
// themeFiles reads a site's copy of the theme: path (inside the theme) →
// content.
func themeFiles(siteDir string) (map[string][]byte, error) {
root := filepath.Join(siteDir, theme.Dir)
out := map[string][]byte{}
err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() {
return err
}
raw, err := os.ReadFile(p)
if err != nil {
return err
}
rel, _ := filepath.Rel(root, p)
out[filepath.ToSlash(rel)] = raw
return nil
})
return out, err
}
// ReadTheme reads a site's copy of the theme from its working copy.
func ReadTheme(siteDir string) ThemeState {
st := ThemeState{Latest: theme.Version}
files, err := themeFiles(siteDir)
if err != nil || len(files) == 0 {
return st
}
st.Has = true
st.Version, _ = strconv.Atoi(strings.TrimSpace(string(files["VERSION"])))
st.Edited = edited(files)
return st
}
// edited lists the files in a copy that don't match its manifest: changed
// or added by hand (a copy without a manifest can't be checked).
func edited(files map[string][]byte) []string {
man, ok := files["MANIFEST"]
if !ok {
return nil
}
sums := theme.ParseManifest(string(man))
var out []string
for p, raw := range files {
if p == "VERSION" || p == "MANIFEST" {
continue
}
if sums[p] != theme.Sum(raw) {
out = append(out, p)
}
}
sort.Strings(out)
return out
}
// ThemeDiff is what an update changes in the copy.
type ThemeDiff struct {
From, To int
Added, Changed, Removed []string
Overwritten []string // edited by hand, and replaced
}
// UpdateTheme opens a pull request that replaces the site's copy of the
// theme with Supermarket's: files added, changed and removed, checked with
// a build. Files changed by hand are listed, since the update overwrites
// them (the site's own layouts/ is the place for changes: it wins over the
// theme).
func UpdateTheme(ctx context.Context, ap *seo.Applier) (*gitea.Pull, *ThemeDiff, error) {
wc, full, published, err := ap.WorkingCopy(ctx)
if err != nil {
return nil, nil, err
}
defer wc.Release()
old, err := themeFiles(wc.Dir)
if err != nil || len(old) == 0 {
return nil, nil, errors.New("this site doesn't use Supermarket's theme (there's no " + theme.Dir + ")")
}
d := &ThemeDiff{To: theme.Version, Overwritten: edited(old)}
d.From, _ = strconv.Atoi(strings.TrimSpace(string(old["VERSION"])))
if d.From >= d.To {
return nil, nil, fmt.Errorf("the site already has the theme's version %d", d.From)
}
branch := fmt.Sprintf("supermarket/theme-%d", theme.Version)
if err := wc.NewBranch(ctx, branch); err != nil {
return nil, nil, err
}
latest := theme.Files()
for p, body := range latest {
prev, had := old[p]
switch {
case !had:
d.Added = append(d.Added, p)
case string(prev) != body:
if p != "VERSION" && p != "MANIFEST" {
d.Changed = append(d.Changed, p)
}
default:
continue
}
if err := wc.WriteFile(theme.Dir+"/"+p, body); err != nil {
return nil, nil, err
}
}
for p := range old {
if _, keep := latest[p]; !keep {
d.Removed = append(d.Removed, p)
if err := wc.RemoveFile(theme.Dir + "/" + p); err != nil {
return nil, nil, err
}
}
}
sort.Strings(d.Added)
sort.Strings(d.Changed)
sort.Strings(d.Removed)
note := "Not checked with a build: there's no Hugo in Supermarket's image."
if hugorepo.HugoVersion(ctx) != "" {
out, err := wc.Build(ctx)
if err != nil {
return nil, nil, fmt.Errorf("with the new theme, %w", err)
}
os.RemoveAll(out)
note = "Checked with a build: the site builds with the new theme."
}
subject := fmt.Sprintf("Sites: update the theme to version %d", theme.Version)
if err := wc.CommitAndPush(ctx, branch, subject); err != nil {
return nil, nil, err
}
var b strings.Builder
fmt.Fprintf(&b, "Updates the site's copy of Supermarket's theme (`%s`) from version %d to %d.\n\n", theme.Dir, d.From, d.To)
list := func(title string, ps []string) {
if len(ps) == 0 {
return
}
fmt.Fprintf(&b, "**%s:**\n", title)
for _, p := range ps {
fmt.Fprintf(&b, "- `%s`\n", p)
}
b.WriteString("\n")
}
list("Changed", d.Changed)
list("Added", d.Added)
list("Removed", d.Removed)
if len(d.Overwritten) > 0 {
list("Changed by hand in the site's copy, and replaced by this update (move such changes to the site's own layouts/ or static/, which win over the theme)", d.Overwritten)
}
b.WriteString(note + "\n\nPreview it in Supermarket (Sites → Previews) before merging: merging publishes it.")
pull, err := ap.Gitea.OpenPull(ctx, full, branch, published, subject, b.String())
if err != nil {
return nil, nil, err
}
return pull, d, nil
}
+75
View File
@@ -0,0 +1,75 @@
# The Supermarket site theme
A Hugo theme for websites made of sections, from Federated Computer's
design system. Supermarket copies it into a site as `themes/supermarket/`;
the site's `hugo.toml` says `theme = "supermarket"`. Anything in the site's
own `layouts/` or `static/` takes precedence over the theme's, so a site can
change any part of it.
## How pages are built
Every page's content lives in its front matter as a `sections:` list. Each
section has a `type` and the fields that type takes. Sections alternate
white and grey bands; `hero` opens the page as a dark band and `final-cta`
closes it as one.
Any section can take `id` (an anchor for links); without one it's made
from `kicker` or `headline`. Most take a heading: `kicker` (a small label
above), `headline` and `lede` (a sentence below). Buttons are `ctas`: a list
of `label`, `url` and `style` (`primary`, `ghost`, or `text` for a quiet
link). Text fields take Markdown inline (bold, links).
| Type | Fields |
|------|--------|
| `hero` | `eyebrow`, `title`, `subhead`, `ctas`, `compact` (shorter). Optional `log`: lines of `tag` + `text` (`think: true` for a greyed step, `done: true` to close) typed out in a console beside the copy, titled `logTitle`; `logImage` puts a photo behind the band, credited by `logCaption` |
| `text` | `kicker`, `headline`, `body` (Markdown), `centered`, `ctas`; `offer` adds a highlighted card below: `badge`, `text`, `ctas`. Without a headline, the body shows as a large statement |
| `features` | `kicker`, `headline`, `lede`, `intro` (Markdown), `items` of `label` + `body` |
| `cards` | `kicker`, `headline`, `lede`, `columns` (2 or 3), `items` of `label`, `title`, `body`, `image`, `link`, `linktext`; `visual: true` draws a panel where there's no image; `ctas` |
| `steps` | `kicker`, `headline`, `lede`, `items` of `title` + `body` |
| `checklist` | `kicker`, `headline`, `lede`, `items` (Markdown strings) |
| `split` | `kicker`, `headline`, `lede`, `columns` of `title` + `items` (short lists), `ctas` |
| `stats` | `kicker`, `headline`, `lede`, `items` of `value` + `label` (values starting with a number count up), `ctas` |
| `table` | A comparison: `kicker`, `headline`, `lede`, `headers` (one per column of values; the last is yours, highlighted), `rows` of `label` + `cells` (one value per header), `ctas` |
| `faq` | `kicker`, `headline`, `lede`, `items` of `q` + `a`, `ctas` |
| `callout` | `kicker`, `headline`, `intro`, `text` |
| `final-cta` | `headline`, `body`, `ctas` (the dark closing band) |
| `form` | A lead form: `kicker`, `headline`, `lede`, `points` (a list beside the form), `note`, `subject` (names the lead), `submit` (the button), `success` (shown after sending), `fields` of `name`, `label`, `type` (`text`, `email`, `number`, `select`, `textarea`), `options`, `placeholder`, `hint`, `required`, `half: true` (two to a row). It posts to `[params.leads] action` (EspoCRM's Lead Capture, set up by Supermarket); while that's empty it opens an email to `[params.leads] email` |
## Settings (hugo.toml)
```toml
theme = "supermarket"
[params]
tagline = "What the company does, in a line."
[params.brand]
logo = "/images/logo.svg" # without one, the site's title is shown
favicon = "/favicon.svg"
dark = "#001a2b" # the top bar, hero and closing band
dark2 = "#052b42"
primary = "#e0ff4f" # the main button
accent = "#614efa" # links and highlights
font = "Inter" # a Google Fonts family
[params.header]
ctas = [{ label = "Get started", url = "/contact/", style = "primary" }]
[params.footer]
tagline = "..."
place = "City, Country"
copyright = "© 2026 Company, Inc."
groups = [{ title = "Company", menu = "footer_company" }]
[params.leads]
action = ""
email = "hello@example.com"
[params.plausible]
script = "https://plausible.example.com/js/script.js"
domain = "example.com"
```
The top bar shows the `main` menu (`[[menu.main]]`); an entry with
`params.dropdown = "<menu>"` opens that menu as a panel. The footer shows
the menus its groups name, `footer_social` and `footer_legal`.
+8
View File
@@ -0,0 +1,8 @@
{{ define "main" }}
<header class="hero hero-compact">
<div class="wrap hero-grid"><div class="hero-copy">
<h1 class="statement">Page not found</h1>
<p class="dek">There's nothing at this address. Try the <a href="{{ "/" | relURL }}">home page</a>.</p>
</div></div>
</header>
{{ end }}
@@ -0,0 +1,35 @@
<!DOCTYPE html>
<html lang="{{ site.Language.LanguageCode | default "en" }}">
<head>
{{ partial "head.html" . }}
</head>
<body id="top">
<a class="skip" href="#content">Skip to content</a>
{{ partial "header.html" . }}
<main id="content" tabindex="-1">
{{ block "main" . }}{{ end }}
</main>
{{ partial "footer.html" . }}
<script>
/* Progressive only: fade sections in as they scroll into view, and
darken the top bar once the page has scrolled. */
(function () {
var root = document.documentElement;
var head = document.querySelector('.site-head');
function onScroll() { if (head) head.classList.toggle('is-scrolled', scrollY > 8); }
addEventListener('scroll', onScroll, { passive: true });
onScroll();
if (!('IntersectionObserver' in window)) return;
root.classList.add('js');
var io = new IntersectionObserver(function (entries) {
entries.forEach(function (e) {
if (e.isIntersecting) { e.target.classList.add('is-visible'); io.unobserve(e.target); }
});
}, { rootMargin: '0px 0px -8% 0px' });
document.querySelectorAll('[data-reveal]').forEach(function (el) { io.observe(el); });
})();
</script>
</body>
</html>
@@ -0,0 +1,4 @@
{{ define "main" }}
{{ partial "render-sections.html" . }}
{{ with .Content }}<div class="wrap prose page-body">{{ . }}</div>{{ end }}
{{ end }}
@@ -0,0 +1,4 @@
{{ define "main" }}
{{ partial "render-sections.html" . }}
{{ with .Content }}<div class="wrap prose page-body">{{ . }}</div>{{ end }}
{{ end }}
+4
View File
@@ -0,0 +1,4 @@
{{ define "main" }}
{{ partial "render-sections.html" . }}
{{ with .Content }}<div class="wrap prose page-body">{{ . }}</div>{{ end }}
{{ end }}
@@ -0,0 +1,45 @@
{{/*
The footer: the brand, [params.footer] tagline and place, the social
links (menu footer_social), the link groups in [params.footer] groups
(each a title and a menu's name), the legal links (menu footer_legal),
and the copyright line.
*/}}
{{ $b := site.Params.brand | default dict }}
{{ $f := site.Params.footer | default dict }}
<footer class="foot">
<div class="wrap">
<div class="foot-top-row">
<div class="foot-brand">
<a href="{{ "/" | relURL }}" class="foot-mark" aria-label="{{ site.Title }}, home">
{{ with $b.logo }}<img src="{{ . | relURL }}" alt="{{ site.Title }}" class="brand-logo">{{ else }}<span class="brand-name">{{ site.Title }}</span>{{ end }}
</a>
{{ with $f.tagline | default site.Params.tagline }}<p class="foot-line">{{ . }}</p>{{ end }}
{{ with $f.place }}<span class="foot-place">{{ . }}</span>{{ end }}
{{ with site.Menus.footer_social }}
<ul class="foot-social">
{{ range . }}<li><a href="{{ .URL }}" target="_blank" rel="noopener">{{ .Name }}<span class="arrow" aria-hidden="true">↗</span></a></li>{{ end }}
</ul>
{{ end }}
</div>
<div class="foot-grid">
{{ range $f.groups }}
<nav class="foot-group" aria-label="{{ .title }}">
<span class="foot-head">{{ .title }}</span>
<ul class="foot-links">
{{ range index site.Menus .menu }}
<li><a href="{{ if or (hasPrefix .URL "mailto:") (hasPrefix .URL "http") }}{{ .URL }}{{ else }}{{ .URL | relURL }}{{ end }}"{{ if .Params.external }} target="_blank" rel="noopener"{{ end }}>{{ .Name }}{{ if .Params.external }}<span class="arrow" aria-hidden="true">↗</span>{{ end }}</a></li>
{{ end }}
</ul>
</nav>
{{ end }}
</div>
</div>
<div class="foot-legal">
<span class="foot-copy">{{ with $f.copyright }}{{ . }}{{ else }}© {{ now.Format "2006" }} {{ site.Title }}{{ end }}</span>
{{ range site.Menus.footer_legal }}<a class="foot-policy" href="{{ .URL | relURL }}">{{ .Name }}</a>{{ end }}
<a class="foot-top" href="#top">Back to top<span class="foot-up" aria-hidden="true">↑</span></a>
</div>
</div>
</footer>
@@ -0,0 +1,43 @@
{{/* Brand settings ([params.brand] in hugo.toml) override the stylesheet's
colors and font; see the theme's README. */}}
{{ $b := site.Params.brand | default dict }}
{{ $dark := $b.dark | default "#001a2b" }}
{{ $dark2 := $b.dark2 | default "#052b42" }}
{{ $primary := $b.primary | default "#e0ff4f" }}
{{ $accent := $b.accent | default "#614efa" }}
{{ $font := $b.font | default "Inter" }}
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{ if .IsHome }}{{ site.Title }}{{ with site.Params.tagline }} — {{ . }}{{ end }}{{ else }}{{ .Title }} · {{ site.Title }}{{ end }}</title>
<meta name="description" content="{{ with .Description }}{{ . }}{{ else }}{{ site.Params.tagline }}{{ end }}">
<meta name="theme-color" content="{{ $dark }}">
<link rel="canonical" href="{{ .Permalink }}">
<meta property="og:title" content="{{ .Title | default site.Title }}">
<meta property="og:description" content="{{ with .Description }}{{ . }}{{ else }}{{ site.Params.tagline }}{{ end }}">
<meta property="og:url" content="{{ .Permalink }}">
<meta property="og:type" content="website">
{{ with $b.favicon }}<link rel="icon" href="{{ . | relURL }}">{{ end }}
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family={{ $font }}:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
<link rel="stylesheet" href="{{ "css/supermarket.css" | relURL }}">
<style>
:root {
--navy-deep: {{ $dark | safeCSS }}; --ink: {{ $dark | safeCSS }};
--navy: {{ $dark2 | safeCSS }}; --navy-2: {{ $dark2 | safeCSS }};
--lime: {{ $primary | safeCSS }}; --lime-deep: {{ $b.primaryHover | default $primary | safeCSS }}; --live: {{ $primary | safeCSS }};
--violet: {{ $accent | safeCSS }}; --violet-deep: {{ $b.accentHover | default $accent | safeCSS }};
--violet-7: color-mix(in srgb, {{ $accent | safeCSS }} 7%, transparent);
--violet-11: color-mix(in srgb, {{ $accent | safeCSS }} 11%, transparent);
--ink-86: color-mix(in srgb, {{ $dark | safeCSS }} 86%, transparent);
--ink-68: color-mix(in srgb, {{ $dark | safeCSS }} 68%, transparent);
--ink-60: color-mix(in srgb, {{ $dark | safeCSS }} 60%, transparent);
--ink-45: color-mix(in srgb, {{ $dark | safeCSS }} 45%, transparent);
--ink-22: color-mix(in srgb, {{ $dark | safeCSS }} 22%, transparent);
--font: "{{ $font | safeCSS }}", ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
}
</style>
{{ with site.Params.plausible }}{{ if .script }}
<script defer data-domain="{{ .domain | default (urls.Parse site.BaseURL).Host }}" src="{{ .script }}"></script>
<script>window.plausible = window.plausible || function () { (window.plausible.q = window.plausible.q || []).push(arguments) };</script>
{{ end }}{{ end }}
@@ -0,0 +1,63 @@
{{/*
The top bar: the logo (or the site's name), the main menu (a menu entry
with `params.dropdown = "<menu>"` opens that menu as a panel), and the
buttons in [params.header] ctas. Below 1000px the menu folds into a Menu
toggle (a <details>, so it works without JS).
*/}}
{{ $page := . }}
{{ $b := site.Params.brand | default dict }}
{{ $ctas := (site.Params.header | default dict).ctas }}
<header class="site-head">
<div class="wrap head-bar">
<a href="{{ "/" | relURL }}" class="brand" aria-label="{{ site.Title }}, home">
{{ with $b.logo }}<img src="{{ . | relURL }}" alt="{{ site.Title }}" class="brand-logo">{{ else }}<span class="brand-name">{{ site.Title }}</span>{{ end }}
</a>
<nav class="head-nav" aria-label="Site">
{{ range .Site.Menus.main }}
{{ if ne .URL "/" }}
{{ $m := . }}
{{ $active := hasPrefix $page.RelPermalink .URL }}
{{ with .Params.dropdown }}
<div class="nav-item has-drop">
<a href="{{ $m.URL | relURL }}" class="nav-link"{{ if $active }} aria-current="page"{{ end }}>{{ $m.Name }}<svg class="nav-caret" viewBox="0 0 10 6" width="10" height="6" aria-hidden="true"><path d="M1 1l4 4 4-4" fill="none" stroke="currentColor" stroke-width="1.5"/></svg></a>
<div class="drop">
<div class="drop-panel">
{{ range index $page.Site.Menus . }}
<a href="{{ .URL | relURL }}" class="drop-link"{{ if eq $page.RelPermalink .URL }} aria-current="page"{{ end }}>
<span class="drop-name">{{ .Name }}</span>
{{ with .Params.desc }}<span class="drop-desc">{{ . }}</span>{{ end }}
</a>
{{ end }}
</div>
</div>
</div>
{{ else }}
<a href="{{ $m.URL | relURL }}" class="nav-link"{{ if $active }} aria-current="page"{{ end }}>{{ $m.Name }}</a>
{{ end }}
{{ end }}
{{ end }}
</nav>
{{ with $ctas }}
<div class="head-actions">
{{ range . }}<a href="{{ .url | relURL }}" class="{{ if eq .style "ghost" }}head-signin{{ else }}btn btn-primary btn-sm{{ end }}">{{ .label }}</a>{{ end }}
</div>
{{ end }}
<details class="menu">
<summary><span class="menu-word">Menu</span><span class="menu-glyph" aria-hidden="true"><i></i><i></i></span></summary>
<nav class="menu-panel" aria-label="Site">
{{ range .Site.Menus.main }}
<a href="{{ .URL | relURL }}" class="menu-top">{{ .Name }}</a>
{{ with .Params.dropdown }}
<div class="menu-sub">
{{ range index $page.Site.Menus . }}<a href="{{ .URL | relURL }}">{{ .Name }}</a>{{ end }}
</div>
{{ end }}
{{ end }}
{{ with $ctas }}<div class="menu-actions">{{ partial "sections/ctas.html" . }}</div>{{ end }}
</nav>
</details>
</div>
</header>
@@ -0,0 +1,9 @@
{{ range .Params.sections }}
{{ if eq .type "hero" }}
{{ partial "sections/hero.html" . }}
{{ else if eq .type "final-cta" }}
{{ partial "sections/final-cta.html" . }}
{{ else if templates.Exists (printf "partials/sections/%s.html" .type) }}
{{ partial "sections/wrapper.html" . }}
{{ end }}
{{ end }}
@@ -0,0 +1,11 @@
{{/*
Anchor id for a section: its own `id`, else one made from its `toc`,
`kicker`, or `headline`. Used by the section wrapper.
*/}}
{{ $id := "" }}
{{ with .id }}
{{ $id = . }}
{{ else }}
{{ with (or .toc .kicker .headline) }}{{ $id = . | plainify | anchorize }}{{ end }}
{{ end }}
{{ return $id }}
@@ -0,0 +1,4 @@
{{ $s := . }}
{{ partial "sections/head.html" $s }}
{{ with $s.intro }}<div class="prose mb-2">{{ . | markdownify }}</div>{{ end }}
<div class="callout"><p>{{ $s.text | markdownify }}</p></div>
@@ -0,0 +1,22 @@
{{/*
A grid of cards: `items`, each with `title`, `body`, optional `label`
(a small tag above the title), `image`, and `link` (+ `linktext`).
Without an image, `visual: true` draws a gradient panel in its place.
*/}}
{{ $s := . }}
{{ partial "sections/head.html" $s }}
<ul class="card-grid{{ with $s.columns }} cols-{{ . }}{{ end }}">
{{ range $i, $c := $s.items }}
<li class="card{{ if or $c.image $s.visual }} has-visual{{ end }}">
{{ with $c.image }}<img class="card-visual" src="{{ . | relURL }}" alt="" loading="lazy">
{{ else }}{{ if $s.visual }}<span class="card-visual card-art" style="--i:{{ $i }}" aria-hidden="true"></span>{{ end }}{{ end }}
<div class="card-body">
{{ with $c.label }}<span class="card-label">{{ . }}</span>{{ end }}
<h3 class="card-title">{{ $c.title | markdownify }}</h3>
{{ with $c.body }}<p class="card-text">{{ . | markdownify }}</p>{{ end }}
{{ with $c.link }}<a class="more card-link" href="{{ . | relURL }}">{{ replaceRE `\s*[→↗]\s*$` "" ($c.linktext | default "Learn more") }}<span class="arrow" aria-hidden="true">→</span></a>{{ end }}
</div>
</li>
{{ end }}
</ul>
{{ if $s.ctas }}<div class="cta-row">{{ partial "sections/ctas.html" $s.ctas }}</div>{{ end }}
@@ -0,0 +1,5 @@
{{ $s := . }}
{{ partial "sections/head.html" $s }}
<ul class="check-list">
{{ range $s.items }}<li>{{ . | markdownify }}</li>{{ end }}
</ul>
@@ -0,0 +1,17 @@
{{/*
Buttons. `primary` is the solid lime button, `ghost` the outlined
secondary, `text` a quiet link with an arrow. Any trailing "→" in a
label is dropped — the arrow is drawn.
*/}}
{{ range . }}
{{ $label := replaceRE `\s*[→↗]\s*$` "" .label }}
{{ $external := or (hasPrefix .url "http") (hasPrefix .url "mailto:") }}
{{ $href := cond (or $external (hasPrefix .url "#")) .url (.url | relURL) }}
{{ if eq .style "ghost" }}
<a href="{{ $href }}" class="btn btn-secondary">{{ $label }}<span class="arrow" aria-hidden="true">{{ if $external }}↗{{ else }}→{{ end }}</span></a>
{{ else if eq .style "text" }}
<a href="{{ $href }}" class="more">{{ $label }}<span class="arrow" aria-hidden="true">{{ if $external }}↗{{ else }}→{{ end }}</span></a>
{{ else }}
<a href="{{ $href }}" class="btn btn-primary">{{ $label }}<span class="arrow" aria-hidden="true">{{ if $external }}↗{{ else }}→{{ end }}</span></a>
{{ end }}
{{ end }}
@@ -0,0 +1,11 @@
{{ $s := . }}
{{ partial "sections/head.html" $s }}
<div class="faq-list">
{{ range $s.items }}
<details class="faq-item">
<summary>{{ .q }}</summary>
<div class="faq-answer"><p>{{ .a | markdownify }}</p></div>
</details>
{{ end }}
</div>
{{ if $s.ctas }}<div class="cta-row mt-2">{{ partial "sections/ctas.html" $s.ctas }}</div>{{ end }}
@@ -0,0 +1,8 @@
{{ $s := . }}
{{ partial "sections/head.html" $s }}
{{ with $s.intro }}<div class="prose mb-2">{{ . | markdownify }}</div>{{ end }}
<ul class="feature-list">
{{ range $s.items }}
<li><strong>{{ .label }}</strong>{{ .body | markdownify }}</li>
{{ end }}
</ul>
@@ -0,0 +1,10 @@
{{ $s := . }}
<aside class="cta" data-reveal>
<div class="wrap cta-inner">
<div class="cta-copy">
<h2 class="cta-title">{{ $s.headline | markdownify }}</h2>
{{ with $s.body }}<p class="cta-text">{{ . | markdownify }}</p>{{ end }}
</div>
{{ if $s.ctas }}<div class="actions">{{ partial "sections/ctas.html" $s.ctas }}</div>{{ end }}
</div>
</aside>
@@ -0,0 +1,103 @@
{{/*
A lead form: the heading, lede, and an optional `points` list on the
left; the form on the right. `fields` take `name`, `label`, `type`
(text, email, number, select, textarea; default text), optional
`options` (select), `placeholder`, `hint`, `required`, and `half: true`
to sit two to a row. `submit` labels the button; `subject` names the lead
(e.g. "Partner platform"); `success` is shown once it's sent.
Where it goes: `[params.leads] action` in hugo.toml. When set, the form
POSTs its fields there (with `source` and `page` added) and shows
`success`. When empty, it opens an email to `[params.leads] email` with
the answers filled in, so leads still arrive before a backend exists.
Without JS, the form falls back to a plain POST (or mailto) of the same.
*/}}
<script src="{{ "js/supermarket-leads.js" | relURL }}"></script>
{{ $s := . }}
{{ $leads := site.Params.leads | default dict }}
{{ $action := $leads.action | default "" }}
{{ $email := $leads.email | default site.Params.supportEmail }}
{{ $subject := $s.subject | default "Website inquiry" }}
<div class="lead">
<div class="lead-copy">
{{ partial "sections/head.html" $s }}
{{ with $s.points }}
<ul class="check-list lead-points">
{{ range . }}<li>{{ . | markdownify }}</li>{{ end }}
</ul>
{{ end }}
{{ with $s.note }}<p class="lead-note">{{ . | markdownify }}</p>{{ end }}
</div>
<form class="lead-form"
{{ if $action }}action="{{ $action }}" method="post"{{ else }}action="{{ printf "mailto:%s?subject=%s" $email (replace (urlquery $subject) "+" "%20") | safeURL }}" method="post" enctype="text/plain"{{ end }}
data-lead="{{ if $action }}post{{ else }}mailto{{ end }}"
data-email="{{ $email }}" data-subject="{{ $subject }}">
<input type="hidden" name="source" value="{{ $subject }}">
{{ range $i, $f := $s.fields }}
{{ $id := printf "lead-%s" $f.name }}
{{ $type := $f.type | default "text" }}
<div class="field{{ if $f.half }} field-half{{ end }}">
<label for="{{ $id }}">{{ $f.label }}{{ if not $f.required }} <span class="field-optional">Optional</span>{{ end }}</label>
{{ if eq $type "select" }}
<select id="{{ $id }}" name="{{ $f.name }}"{{ if $f.required }} required{{ end }}>
<option value="" disabled selected>{{ $f.placeholder | default "Choose one" }}</option>
{{ range $f.options }}<option>{{ . }}</option>{{ end }}
</select>
{{ else if eq $type "textarea" }}
<textarea id="{{ $id }}" name="{{ $f.name }}" rows="3"{{ with $f.placeholder }} placeholder="{{ . }}"{{ end }}{{ if $f.required }} required{{ end }}></textarea>
{{ else }}
<input id="{{ $id }}" name="{{ $f.name }}" type="{{ $type }}"{{ with $f.placeholder }} placeholder="{{ . }}"{{ end }}{{ if eq $type "email" }} autocomplete="email"{{ else if eq $f.name "name" }} autocomplete="name"{{ else if in (slice "company" "organization") $f.name }} autocomplete="organization"{{ end }}{{ if eq $type "number" }} min="0" inputmode="numeric"{{ end }}{{ if $f.required }} required{{ end }}>
{{ end }}
{{ with $f.hint }}<small>{{ . }}</small>{{ end }}
</div>
{{ end }}
<button type="submit" class="btn btn-primary">{{ $s.submit | default "Send" }}<span class="arrow" aria-hidden="true">→</span></button>
<p class="lead-status" role="status" aria-live="polite" hidden></p>
<p class="lead-privacy">We'll use this only to reply to you. No newsletters unless you ask. See our <a href="{{ "/privacy-policy/" | relURL }}">Privacy Policy</a>.</p>
</form>
</div>
<script>
(function () {
var form = document.currentScript.previousElementSibling.querySelector('form');
var status = form.querySelector('.lead-status');
var success = {{ $s.success | default "Thanks — we've got it and will be in touch soon." }};
function show(msg, ok) {
status.hidden = false;
status.textContent = msg;
status.className = 'lead-status ' + (ok ? 'is-ok' : 'is-error');
}
form.addEventListener('submit', function (e) {
if (!form.checkValidity()) return;
e.preventDefault();
var data = new FormData(form);
data.append('page', location.pathname);
if (window.plausible) plausible('Lead', { props: { source: form.dataset.subject } });
if (form.dataset.lead === 'mailto') {
var lines = [];
form.querySelectorAll('.field').forEach(function (f) {
var el = f.querySelector('input, select, textarea');
lines.push(f.querySelector('label').childNodes[0].textContent.trim() + ': ' + (el.value || '—'));
});
location.href = 'mailto:' + form.dataset.email + '?subject=' + encodeURIComponent(form.dataset.subject) +
'&body=' + encodeURIComponent(lines.join('\n') + '\n\nPage: ' + location.href);
show('Your email app should open with your answers filled in. Just press send.', true);
return;
}
var btn = form.querySelector('button');
btn.disabled = true;
(window.leadPost ? window.leadPost(form, data) : fetch(form.action, { method: 'POST', body: data, headers: { Accept: 'application/json' } }))
.then(function (r) {
if (!r.ok) throw new Error(r.status);
form.reset();
form.querySelectorAll('.field').forEach(function (f) { f.hidden = true; });
btn.hidden = true;
show(success, true);
})
.catch(function () {
btn.disabled = false;
show('Something went wrong sending that. Please try again, or email ' + form.dataset.email + '.', false);
});
});
})();
</script>
@@ -0,0 +1,8 @@
{{/* Shared section heading: optional kicker (a mono eyebrow), headline, and lede. */}}
{{ if or .kicker .headline .lede }}
<div class="section-head">
{{ with .kicker }}<p class="eyebrow">{{ . }}</p>{{ end }}
{{ with .headline }}<h2>{{ . | markdownify }}</h2>{{ end }}
{{ with .lede }}<p class="lede">{{ . | markdownify }}</p>{{ end }}
</div>
{{ end }}
@@ -0,0 +1,93 @@
{{/*
The opening of every page: a full-bleed dark band. On the left, an
optional note (the eyebrow), the statement (title), the dek (subhead) and
the actions (ctas); on the right, when `log:` is set, an activity log
typed out line by line. `compact: true` makes it shorter; `logImage` sets
a photo behind the whole band (`logCaption` credits it).
*/}}
{{ $s := . }}
{{ $visual := $s.log }}
<header class="hero{{ if $s.compact }} hero-compact{{ end }}{{ if $visual }} has-visual{{ end }}{{ if $s.logImage }} has-image{{ end }}">
{{ with $s.logImage }}<img class="hero-bg" src="{{ . | relURL }}" alt="" fetchpriority="high">{{ end }}
<div class="wrap hero-grid">
<div class="hero-copy">
{{ with $s.eyebrow }}<p class="note" data-reveal><span class="note-live" aria-hidden="true"></span><span class="note-text">{{ . }}</span></p>{{ end }}
<h1 class="statement" data-reveal style="--d:80ms">{{ $s.title | markdownify }}</h1>
{{ with $s.subhead }}<p class="dek" data-reveal style="--d:140ms">{{ . | markdownify }}</p>{{ end }}
{{ if $s.ctas }}<div class="actions" data-reveal style="--d:200ms">{{ partial "sections/ctas.html" $s.ctas }}</div>{{ end }}
</div>
{{ with $s.log }}
{{/*
An agent's activity log, typed out line by line (see the script below).
Lines take `tag` + `text`; `think: true` marks a reasoning step (greyed,
with a pause); `done: true` closes the run. The window keeps a fixed
height and scrolls as lines arrive. `logCaption` credits the photo.
*/}}
<figure class="hero-log" data-reveal style="--d:260ms">
<div class="log-window">
<div class="log-bar">
<span class="log-title">{{ $s.logTitle | default "activity" }}</span>
<span class="log-live"><span class="note-live" aria-hidden="true"></span>Live</span>
</div>
<div class="log-view">
<ol class="log-lines" aria-label="{{ $s.logTitle | default "Activity" }}">
{{ range . }}
<li class="log-line{{ if .done }} is-done{{ end }}{{ if .think }} is-think{{ end }}">
<span class="log-tag">{{ .tag | default (cond .done "Done" (cond (.think | default false) "Thinking" "")) }}</span>
<span class="log-text">{{ .text }}</span>
</li>
{{ end }}
</ol>
</div>
</div>
</figure>
<script>
(function () {
var fig = document.currentScript.previousElementSibling;
if (!fig || matchMedia('(prefers-reduced-motion: reduce)').matches) return;
var view = fig.querySelector('.log-view'), list = fig.querySelector('.log-lines');
var lines = [].slice.call(fig.querySelectorAll('.log-line'));
var onScreen = true, i = 0;
function visible() { return onScreen && !document.hidden; }
fig.classList.add('is-animated');
lines.forEach(function (li) {
li.style.setProperty('--n', li.querySelector('.log-text').textContent.trim().length);
});
// Pause while the log is off screen or the tab is hidden.
function schedule(fn, ms) { setTimeout(function () { if (visible()) fn(); else schedule(fn, 400); }, ms); }
function next() {
if (i === lines.length) { schedule(reset, 4200); return; }
var li = lines[i++], n = +li.style.getPropertyValue('--n');
// Finished lines drop their typing animation, so a repaint can't replay it.
lines.forEach(function (l) { if (l.classList.contains('is-current')) l.classList.add('is-typed'); l.classList.remove('is-current'); });
li.classList.add('is-on', 'is-current');
// Keep the newest line in view, like a terminal: slide the list up.
var shift = Math.max(0, li.offsetTop + li.offsetHeight + 18 - view.clientHeight);
list.style.transform = 'translateY(' + -shift + 'px)';
var pause = li.classList.contains('is-think') ? 1300 : li.classList.contains('is-done') ? 300 : 450;
schedule(next, n * 16 + pause);
}
function reset() {
fig.classList.add('is-clearing');
schedule(function () {
lines.forEach(function (l) { l.classList.remove('is-on', 'is-current', 'is-typed'); });
list.style.transition = 'none';
list.style.transform = '';
void list.offsetHeight;
list.style.transition = '';
fig.classList.remove('is-clearing');
i = 0;
schedule(next, 500);
}, 450);
}
if ('IntersectionObserver' in window) {
new IntersectionObserver(function (e) { onScreen = e[0].isIntersecting; }).observe(fig);
}
schedule(next, 700);
})();
</script>
{{ end }}
</div>
{{ with $s.logCaption }}<p class="hero-caption">{{ . }}</p>{{ end }}
</header>
@@ -0,0 +1,14 @@
{{/* Two columns, each a heading plus a short list. */}}
{{ $s := . }}
{{ partial "sections/head.html" $s }}
<div class="split">
{{ range $s.columns }}
<div class="split-col">
<h3>{{ .title }}</h3>
<ul class="split-list">
{{ range .items }}<li>{{ . | markdownify }}</li>{{ end }}
</ul>
</div>
{{ end }}
</div>
{{ if $s.ctas }}<div class="cta-row mt-2">{{ partial "sections/ctas.html" $s.ctas }}</div>{{ end }}
@@ -0,0 +1,45 @@
{{/*
Stat tiles. Values that start with a number ("80%+", "100+", "30X") count
up from zero when the row scrolls into view; others show as written.
Without JS or with reduced motion, every value simply shows.
*/}}
{{ $s := . }}
{{ partial "sections/head.html" $s }}
<div class="stat-row">
{{ range $s.items }}
<div class="stat">
<span class="stat-value">{{ .value }}</span>
<span class="stat-label">{{ .label }}</span>
</div>
{{ end }}
</div>
<script>
(function () {
var row = document.currentScript.previousElementSibling;
if (!('IntersectionObserver' in window) || matchMedia('(prefers-reduced-motion: reduce)').matches) return;
var counters = [];
row.querySelectorAll('.stat-value').forEach(function (el) {
var m = el.textContent.trim().match(/^(\d+)(.*)$/);
if (!m) return;
var shown = document.createElement('span'), full = el.textContent.trim();
shown.setAttribute('aria-hidden', 'true');
shown.textContent = '0' + m[2];
el.innerHTML = '<span class="visually-hidden"></span>';
el.firstChild.textContent = full;
el.appendChild(shown);
counters.push({ node: shown, to: +m[1], suffix: m[2] });
});
if (!counters.length) return;
new IntersectionObserver(function (entries, io) {
if (!entries[0].isIntersecting) return;
io.disconnect();
var start = performance.now(), dur = 1200;
(function tick(now) {
var t = Math.min(1, (now - start) / dur), eased = 1 - Math.pow(1 - t, 3);
counters.forEach(function (c) { c.node.textContent = Math.round(c.to * eased) + c.suffix; });
if (t < 1) requestAnimationFrame(tick);
})(start);
}, { threshold: 0.6 }).observe(row);
})();
</script>
{{ if $s.ctas }}<div class="cta-row mt-2">{{ partial "sections/ctas.html" $s.ctas }}</div>{{ end }}
@@ -0,0 +1,13 @@
{{ $s := . }}
{{ partial "sections/head.html" $s }}
<ol class="step-row{{ if eq (len $s.items) 4 }} steps-4{{ end }}">
{{ range $i, $item := $s.items }}
<li class="step">
<div class="step-head">
<h3>{{ $item.title }}</h3>
<span class="step-num">{{ printf "%03d" (add $i 1) }}</span>
</div>
<p>{{ $item.body | markdownify }}</p>
</li>
{{ end }}
</ol>
@@ -0,0 +1,28 @@
{{ $s := . }}
{{ partial "sections/head.html" $s }}
<div class="table-scroll">
<table class="compare-table">
<thead>
<tr>
<th></th>
{{ range $s.headers }}<th>{{ . }}</th>{{ end }}
</tr>
</thead>
<tbody>
{{ range $s.rows }}
{{ $n := len .cells }}
<tr>
<th>{{ .label }}</th>
{{ range $i, $cell := .cells }}
{{ if eq (add $i 1) $n }}
<td class="good">{{ $cell }}</td>
{{ else }}
<td class="bad">{{ $cell }}</td>
{{ end }}
{{ end }}
</tr>
{{ end }}
</tbody>
</table>
</div>
{{ if $s.ctas }}<div class="cta-row mt-2">{{ partial "sections/ctas.html" $s.ctas }}</div>{{ end }}
@@ -0,0 +1,20 @@
{{/*
Prose, with optional `ctas`. `offer` adds a highlighted card below:
`badge` (a small lime tag), `text`, and `ctas`.
*/}}
{{ $s := . }}
{{ partial "sections/head.html" $s }}
{{/* markdownify drops the <p> around a lone paragraph; put it back so inline markup stays in the flow */}}
{{ $body := $s.body | markdownify }}
{{ if not (findRE `^\s*<(p|ul|ol|h[1-6]|div|blockquote|pre|table|figure|hr)[\s>]` $body) }}{{ $body = printf "<p>%s</p>" $body | safeHTML }}{{ end }}
<div class="prose{{ if $s.centered }} centered{{ end }}">
{{ $body }}
</div>
{{ if $s.ctas }}<div class="cta-row mt-2">{{ partial "sections/ctas.html" $s.ctas }}</div>{{ end }}
{{ with $s.offer }}
<div class="offer-card">
{{ with .badge }}<span class="offer-badge">{{ . }}</span>{{ end }}
<p class="offer-text">{{ .text | markdownify }}</p>
{{ with .ctas }}<div class="offer-actions">{{ partial "sections/ctas.html" . }}</div>{{ end }}
</div>
{{ end }}
@@ -0,0 +1,7 @@
{{ $s := . }}
{{ $id := partial "section-id.html" $s }}
<section class="section section-{{ $s.type }}"{{ with $id }} id="{{ . }}"{{ end }} data-reveal>
<div class="wrap">
{{ partial (printf "sections/%s.html" $s.type) $s }}
</div>
</section>
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,50 @@
/* Sends the site's lead forms to EspoCRM's Lead Capture. Written by
Supermarket: the form posts here instead of to [params.leads] action
directly, so its fields can be mapped onto a Lead's. */
(function () {
var mapped = { email: 'emailAddress', 'e-mail': 'emailAddress', phone: 'phoneNumber', tel: 'phoneNumber',
company: 'accountName', organization: 'accountName', organisation: 'accountName', church: 'accountName' };
function label(form, name) {
var el = form.querySelector('[name="' + name + '"]');
var l = el && el.id && form.querySelector('label[for="' + el.id + '"]');
return l ? l.childNodes[0].textContent.trim() : name;
}
window.leadPost = function (form, data) {
var lead = { firstName: null, lastName: null, emailAddress: null, accountName: null, phoneNumber: null };
var notes = [];
data.forEach(function (value, name) {
value = String(value).trim();
if (!value) return;
var key = name.toLowerCase();
if (key === 'name' || key === 'full_name' || key === 'fullname') {
var parts = value.split(/\s+/);
lead.lastName = parts.pop();
lead.firstName = parts.length ? parts.join(' ') : null;
} else if (key === 'first_name' || key === 'firstname') {
lead.firstName = value;
} else if (key === 'last_name' || key === 'lastname') {
lead.lastName = value;
} else if (mapped[key]) {
lead[mapped[key]] = value;
} else if (key === 'source') {
notes.unshift('Form: ' + value);
} else if (key === 'page') {
notes.push('Page: ' + location.origin + value);
} else {
notes.push(label(form, name) + ': ' + value);
}
});
if (!lead.lastName) lead.lastName = lead.emailAddress || 'Website visitor';
var q = new URLSearchParams(location.search);
['utm_campaign', 'utm_source', 'utm_medium', 'utm_content'].forEach(function (k) {
if (q.get(k)) notes.push(k + ': ' + q.get(k));
});
if (document.referrer) notes.push('Came from: ' + document.referrer);
lead.description = notes.join('\n') || null;
return fetch(form.action, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify(lead)
});
};
})();
+4
View File
@@ -0,0 +1,4 @@
name = "Supermarket"
license = "Proprietary"
description = "Websites made of sections, built and kept by Supermarket."
min_version = "0.146.0"
+101
View File
@@ -0,0 +1,101 @@
// Package theme is the Hugo theme new sites are made with: federated-
// website's look and sections, made generic, with each site's brand as
// settings. Supermarket copies it into a site as themes/supermarket/.
package theme
import (
"crypto/sha256"
"embed"
"fmt"
"io/fs"
"sort"
"strconv"
"strings"
)
// Version is the theme's version, written into the site's copy
// (themes/supermarket/VERSION) so an older copy can be updated. Raise it
// whenever the files change.
const Version = 1
// Dir is where the theme goes in a site.
const Dir = "themes/supermarket"
// Name is the theme's name in hugo.toml.
const Name = "supermarket"
//go:embed all:files
var files embed.FS
// Files are the theme's files: path (inside the theme) → content,
// VERSION and MANIFEST included.
func Files() map[string]string {
out := files0()
out["MANIFEST"] = Manifest(out)
return out
}
// Manifest lists each file's SHA-256 (VERSION and MANIFEST aside), so a
// site's copy can be checked for files changed by hand.
func Manifest(files map[string]string) string {
var b strings.Builder
for _, p := range sortedKeys(files) {
if p == "VERSION" || p == "MANIFEST" {
continue
}
fmt.Fprintf(&b, "%x %s\n", sha256.Sum256([]byte(files[p])), p)
}
return b.String()
}
// ParseManifest reads a MANIFEST: path → SHA-256 (hex).
func ParseManifest(m string) map[string]string {
out := map[string]string{}
for _, l := range strings.Split(m, "\n") {
if sum, p, ok := strings.Cut(l, " "); ok && p != "" {
out[p] = sum
}
}
return out
}
// Sum is a file's SHA-256, as in the manifest.
func Sum(content []byte) string { return fmt.Sprintf("%x", sha256.Sum256(content)) }
func sortedKeys(m map[string]string) []string {
var ks []string
for k := range m {
ks = append(ks, k)
}
sort.Strings(ks)
return ks
}
func files0() map[string]string {
out := map[string]string{"VERSION": strconv.Itoa(Version) + "\n"}
_ = fs.WalkDir(files, "files", func(p string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() {
return err
}
raw, err := files.ReadFile(p)
if err != nil {
return err
}
out[strings.TrimPrefix(p, "files/")] = string(raw)
return nil
})
return out
}
// Paths are the theme's file paths, sorted.
func Paths() []string {
var ps []string
for p := range Files() {
ps = append(ps, p)
}
sort.Strings(ps)
return ps
}
// LeadScript is the lead forms' script (static/js/supermarket-leads.js).
func LeadScript() string { return Files()["static/js/supermarket-leads.js"] }
+148
View File
@@ -0,0 +1,148 @@
package theme
import (
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)
const allSections = `---
title: Everything
description: Every section type.
sections:
- type: hero
eyebrow: New
title: "One **bill** for everything"
subhead: The apps your team needs.
ctas:
- { label: Start, url: /start/, style: primary }
- { label: Learn, url: "#more", style: ghost }
log:
- { tag: App, text: Read 14 tickets }
- { think: true, text: Checking }
- { done: true }
- type: text
kicker: Why
headline: Because
body: "It's **simple**."
- type: features
headline: Features
items: [{ label: Fast, body: Very }, { label: Private, body: Yours }]
- type: cards
columns: 2
items: [{ label: A, title: Card one, body: Text, link: /a/, linktext: Read }, { title: Card two, body: More, visual: true }]
- type: steps
items: [{ title: Sign up, body: Two minutes }, { title: Move in, body: We help }]
- type: checklist
items: ["Email", "Files"]
- type: split
columns: [{ title: Before, items: [Bills] }, { title: After, items: [One bill] }]
- type: stats
items: [{ value: "80%", label: saved }, { value: "24/7", label: support }]
- type: table
headers: [Them, Us]
rows: [{ label: Price, cells: ["$50", "$5"] }]
- type: faq
items: [{ q: Is it safe?, a: "Yes." }]
- type: callout
text: A note.
- type: form
headline: Ask us
subject: Contact
fields: [{ name: name, label: Name, required: true }, { name: email, label: Email, type: email, required: true }]
- type: nonsense
title: An unknown type is skipped
- type: final-cta
headline: Ready?
ctas: [{ label: Go, url: /go/ }]
---
`
func TestThemeBuilds(t *testing.T) {
hugo, err := exec.LookPath("hugo")
if err != nil {
t.Skip("no hugo")
}
site := t.TempDir()
for p, body := range Files() {
full := filepath.Join(site, Dir, p)
os.MkdirAll(filepath.Dir(full), 0o755)
os.WriteFile(full, []byte(body), 0o644)
}
cfg := `baseURL = "https://acme.example/"
title = "Acme"
theme = "supermarket"
disableKinds = ["taxonomy", "term", "RSS"]
[params]
tagline = "Widgets for everyone"
[params.brand]
primary = "#ff6600"
accent = "#0055ff"
font = "IBM Plex Sans"
[params.header]
ctas = [{ label = "Get started", url = "/start/", style = "primary" }]
[params.footer]
groups = [{ title = "Company", menu = "footer_company" }]
[params.leads]
action = "https://crm.example/api/v1/LeadCapture/k"
[[menu.main]]
name = "Pricing"
url = "/pricing/"
[[menu.footer_company]]
name = "About"
url = "/about/"
`
os.WriteFile(filepath.Join(site, "hugo.toml"), []byte(cfg), 0o644)
os.MkdirAll(filepath.Join(site, "content"), 0o755)
os.WriteFile(filepath.Join(site, "content", "_index.md"), []byte(allSections), 0o644)
os.WriteFile(filepath.Join(site, "content", "plain.md"), []byte("---\ntitle: Plain\n---\nJust **Markdown**.\n"), 0o644)
out := filepath.Join(t.TempDir(), "public")
cmd := exec.Command(hugo, "--quiet", "--destination", out)
cmd.Dir = site
if msg, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("hugo: %v\n%s", err, msg)
}
home, _ := os.ReadFile(filepath.Join(out, "index.html"))
h := string(home)
for _, want := range []string{
"<title>Acme — Widgets for everyone</title>", "--lime: #ff6600", "--violet: #0055ff", `family=IBM%20Plex%20Sans:wght`, `--font: "IBM Plex Sans"`,
`<span class="brand-name">Acme</span>`, ">Pricing<", ">Get started<", "One <strong>bill</strong> for everything", "Read 14 tickets",
"section-features", "Card one", "section-steps", "section-checklist", "section-split", "section-stats", "section-table", "section-faq",
"section-callout", "section-form", `action="https://crm.example/api/v1/LeadCapture/k"`, "window.leadPost", "supermarket-leads.js",
"Ready?", ">About<", "© ",
} {
if !strings.Contains(h, want) {
t.Errorf("home lacks %q", want)
}
}
if strings.Contains(h, "An unknown type is skipped") || strings.Contains(h, "Federated") {
t.Error("an unknown section, or Federated's own text, shows")
}
plain, _ := os.ReadFile(filepath.Join(out, "plain", "index.html"))
if !strings.Contains(string(plain), "Just <strong>Markdown</strong>") {
t.Errorf("plain page: %s", plain)
}
for _, f := range []string{"css/supermarket.css", "js/supermarket-leads.js", "404.html"} {
if _, err := os.Stat(filepath.Join(out, f)); err != nil {
t.Errorf("%s missing", f)
}
}
}
func TestFiles(t *testing.T) {
fs := Files()
man := ParseManifest(fs["MANIFEST"])
if len(man) != len(fs)-2 || man["static/css/supermarket.css"] != Sum([]byte(fs["static/css/supermarket.css"])) {
t.Errorf("manifest: %d entries for %d files", len(man), len(fs))
}
if fs["VERSION"] != "1\n" || !strings.Contains(fs["README.md"], "| `hero` |") || !strings.Contains(LeadScript(), "window.leadPost") {
t.Error("files")
}
for p := range fs {
if strings.Contains(fs[p], "federated.computer") {
t.Errorf("%s mentions federated.computer", p)
}
}
}
+89 -2
View File
@@ -136,7 +136,7 @@ func ImportPlausible(ctx context.Context, d *db.DB, c *plausible.Client, sites [
campaigns = append(campaigns, slug)
}
yesterday := now.Local().AddDate(0, 0, -1).Format(dayFormat)
visits := 0
visits, leads, leadNote := 0, 0, ""
for _, site := range sites {
var through string
if _, err := d.GetJSON(plausibleStateKey(site), &through); err != nil {
@@ -192,15 +192,73 @@ func ImportPlausible(ctx context.Context, d *db.DB, c *plausible.Client, sites [
visits += n
}
}
n, err := importLeads(ctx, d, c, site, from, yesterday, campaigns, tags)
if err != nil {
leadNote = fmt.Sprintf(" Form leads weren't read from %s: %v.", site, err)
}
leads += n
if err := d.PutJSON(plausibleStateKey(site), yesterday); err != nil {
return save(d, SourcePlausible, res, err)
}
}
res.Through = yesterday
res.Detail = fmt.Sprintf("%d visitors on links tagged with a signal.", visits)
res.Detail = fmt.Sprintf("%d visitors on links tagged with a signal; %d form leads.", visits, leads) + leadNote
return save(d, SourcePlausible, res, nil)
}
// LeadGoal is the Plausible goal (a custom event) the sites' lead forms
// send when they're submitted.
const LeadGoal = "Lead"
// importLeads counts the lead forms sent on visits tagged with a signal
// (Plausible's Lead goal, by the visit's UTM tags) as interested, on the
// signal's funnel. Without the goal set up in Plausible, it reports why.
func importLeads(ctx context.Context, d *db.DB, c *plausible.Client, site, from, to string, campaigns []any, tags map[string]int64) (int, error) {
rows, err := c.Run(ctx, plausible.Query{
SiteID: site,
Metrics: []string{"events"},
DateRange: []string{from, to},
Dimensions: []string{"time:day", "visit:utm_campaign", "visit:utm_source", "visit:utm_medium"},
Filters: [][]any{{"is", "event:goal", []any{LeadGoal}}, {"is", "visit:utm_campaign", campaigns}},
Pagination: &plausible.Pagination{Limit: 10000},
})
if err != nil {
if strings.Contains(strings.ToLower(err.Error()), "goal") {
return 0, fmt.Errorf("add a %q goal (a custom event) in Plausible to count them", LeadGoal)
}
return 0, err
}
n := 0
for _, r := range rows {
if len(r.Dimensions) < 4 || len(r.Metrics) < 1 || r.Metrics[0] < 1 {
continue
}
day, campaign, source, medium := r.Dimensions[0], r.Dimensions[1], r.Dimensions[2], r.Dimensions[3]
sig, ok := tags[strings.ToLower(campaign)]
if !ok {
continue
}
at, err := time.ParseInLocation(dayFormat, day[:min(len(day), 10)], time.Local)
if err != nil {
continue
}
count := int(r.Metrics[0])
note := strings.Trim(none(source)+" / "+none(medium), " /")
added, err := signals.Record(d, signals.Event{
SignalID: sig, Stage: signals.StageInterested, Channel: Channel(none(source), none(medium)),
Source: SourcePlausible, Count: count, Note: site + ": sent a lead form" + strings.TrimSuffix(" ("+note+")", " ()"),
At: at.Add(12 * time.Hour), ExternalID: strings.Join([]string{"lead", site, day, campaign, source, medium}, "|"),
})
if err != nil {
return n, err
}
if added {
n += count
}
}
return n, nil
}
// none is "" for Plausible's empty values.
func none(v string) string {
if v == "(none)" || v == "(not set)" {
@@ -269,3 +327,32 @@ func PageVisitors(ctx context.Context, c *plausible.Client, site string, paths [
}
return out, nil
}
// FormLead is a day's lead forms for a signal, as counted from Plausible.
type FormLead struct {
Signal string
Count int
Note string
At time.Time
}
// FormLeads are the latest lead forms counted, newest first.
func FormLeads(d *db.DB, limit int) ([]FormLead, error) {
rows, err := d.Query(`SELECT coalesce(s.name, ''), e.count, e.note, e.at FROM funnel_events e LEFT JOIN signals s ON s.id = e.signal_id
WHERE e.source = ? AND e.external_id LIKE 'lead|%' ORDER BY e.at DESC, e.id DESC LIMIT ?`, SourcePlausible, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var out []FormLead
for rows.Next() {
var f FormLead
var at string
if err := rows.Scan(&f.Signal, &f.Count, &f.Note, &at); err != nil {
return nil, err
}
f.At, _ = time.Parse(time.RFC3339, at)
out = append(out, f)
}
return out, rows.Err()
}
+40 -6
View File
@@ -70,6 +70,13 @@ func TestImportPlausible(t *testing.T) {
var q plausible.Query
json.NewDecoder(r.Body).Decode(&q)
got = append(got, q)
if len(q.Filters) == 2 { // the lead forms (the Lead goal)
json.NewEncoder(w).Encode(map[string]any{"results": []any{
map[string]any{"dimensions": []string{"2026-11-21", "leaving-m365", "linkedin", "social"}, "metrics": []float64{1}},
map[string]any{"dimensions": []string{"2026-11-21", "old-campaign", "x", "social"}, "metrics": []float64{3}},
}})
return
}
json.NewEncoder(w).Encode(map[string]any{"results": []any{
map[string]any{"dimensions": []string{"2026-11-20", "leaving-m365", "email", "outreach", "outreach-3"}, "metrics": []float64{2}},
map[string]any{"dimensions": []string{"2026-11-21", "leaving-m365", "linkedin", "social", "(none)"}, "metrics": []float64{5}},
@@ -82,7 +89,7 @@ func TestImportPlausible(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if res.Added != 2 || res.Through != "2026-11-21" || !strings.Contains(res.Detail, "7 visitors") {
if res.Added != 2 || res.Through != "2026-11-21" || !strings.Contains(res.Detail, "7 visitors") || !strings.Contains(res.Detail, "1 form leads") {
t.Fatalf("result: %+v", res)
}
q := got[0]
@@ -90,17 +97,24 @@ func TestImportPlausible(t *testing.T) {
if q.SiteID != "federated.computer" || string(dr) != `["2026-10-23","2026-11-21"]` || len(q.Filters) != 1 {
t.Errorf("query: %+v %s", q, dr)
}
if lq, _ := json.Marshal(got[1].Filters); !strings.Contains(string(lq), `["is","event:goal",["Lead"]]`) {
t.Errorf("leads query: %s", lq)
}
evs, _ := signals.RecentEvents(d, m365, 10)
if len(evs) != 2 || evs[0].Stage != signals.StageVisited || evs[0].Channel != "social" || evs[0].Count != 5 ||
evs[1].Channel != "email" || !strings.Contains(evs[1].Note, "outreach-3") {
t.Errorf("events: %+v", evs)
var stages []string
for _, e := range evs {
stages = append(stages, e.Stage+"/"+e.Channel)
}
if len(evs) != 3 || strings.Join(stages, " ") != "interested/social visited/social visited/email" ||
!strings.Contains(evs[0].Note, "sent a lead form (linkedin / social)") || !strings.Contains(evs[2].Note, "outreach-3") {
t.Errorf("events: %v %+v", stages, evs)
}
// The next day reads only the new day; running again the same day reads nothing.
if _, err := ImportPlausible(context.Background(), d, c, []string{"federated.computer"}, now); err != nil || len(got) != 1 {
if _, err := ImportPlausible(context.Background(), d, c, []string{"federated.computer"}, now); err != nil || len(got) != 2 {
t.Errorf("same day: %d queries, %v", len(got), err)
}
res, _ = ImportPlausible(context.Background(), d, c, []string{"federated.computer"}, now.AddDate(0, 0, 1))
dr, _ = json.Marshal(got[1].DateRange)
dr, _ = json.Marshal(got[2].DateRange)
if string(dr) != `["2026-11-22","2026-11-22"]` || res.Added != 0 {
t.Errorf("next day: %s %+v", dr, res)
}
@@ -198,3 +212,23 @@ func TestSyncStripe(t *testing.T) {
t.Error("a bad key worked")
}
}
func TestImportLeadsWithoutTheGoal(t *testing.T) {
d := openDB(t)
signal(t, d, "Leaving M365", "leaving-m365")
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var q plausible.Query
json.NewDecoder(r.Body).Decode(&q)
if len(q.Filters) == 2 {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(`{"error":"The goal ` + "`Lead`" + ` is not configured for this site."}`))
return
}
w.Write([]byte(`{"results":[]}`))
}))
defer srv.Close()
res, err := ImportPlausible(context.Background(), d, plausible.New(srv.URL, "k"), []string{"federated.computer"}, now)
if err != nil || !strings.Contains(res.Detail, `add a "Lead" goal`) || res.Through != "2026-11-21" {
t.Errorf("%+v %v", res, err)
}
}
+200
View File
@@ -0,0 +1,200 @@
package web
import (
"context"
"errors"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"supermarket/internal/backup"
"supermarket/internal/db"
)
func (s *Server) backupDir() string { return backup.Dir(s.DataDir) }
// RunBackups makes the daily backup, and prunes old dailies, while the app
// runs.
func (s *Server) RunBackups(ctx context.Context) {
tick := time.NewTicker(time.Hour)
defer tick.Stop()
for {
s.dailyBackup(time.Now())
select {
case <-ctx.Done():
return
case <-tick.C:
}
}
}
func (s *Server) dailyBackup(now time.Time) {
due, err := backup.DueDaily(s.backupDir(), now)
if err != nil {
s.Log.Warn("backups: listing", "err", err)
return
}
if !due {
return
}
if _, err := backup.Make(s.DB.DB, s.backupDir(), backup.Daily, "", now); err != nil {
s.Log.Error("backups: the daily backup failed", "err", err)
return
}
if n, err := backup.Prune(s.backupDir()); err != nil {
s.Log.Warn("backups: pruning", "err", err)
} else if n > 0 {
s.Log.Info("backups: removed old daily backups", "count", n)
}
}
func (s *Server) backupsPage(w http.ResponseWriter, r *http.Request) {
s.renderBackups(w, r, "", "")
}
func (s *Server) renderBackups(w http.ResponseWriter, r *http.Request, errMsg, flash string) {
bs, err := backup.List(s.backupDir())
if err != nil {
s.serverError(w, err)
return
}
var total int64
for _, b := range bs {
total += b.Size
}
keep := backup.Keep(bs)
hostDir := s.backupDir()
if s.MCPSocket != "" { // the data folder's path on the host
hostDir = filepath.Join(filepath.Dir(s.MCPSocket), "backups")
}
data := map[string]any{"Backups": bs, "Total": total, "Keep": keep, "Schema": db.Schema(), "Dir": hostDir,
"Pending": backup.Pending(s.DataDir), "CanRestart": s.Restart != nil}
if last := backup.LastRestore(s.DataDir); last != nil && time.Since(last.At) < 24*time.Hour {
data["Restored"] = last
}
s.render(w, r, "backups", page{Title: "Backups", Nav: "settings/backups", Error: errMsg, Flash: flash, Data: data})
}
func (s *Server) backupsAction(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
switch r.PathValue("action") {
case "now":
b, err := backup.Make(s.DB.DB, s.backupDir(), backup.Manual, r.PostFormValue("note"), time.Now())
if err != nil {
s.renderBackups(w, r, err.Error(), "")
return
}
s.renderBackups(w, r, "", "Backed up to "+b.Name+".")
case "restore":
b, err := backup.Find(s.backupDir(), r.PostFormValue("name"))
if err != nil {
s.renderBackups(w, r, "There's no backup called "+r.PostFormValue("name")+".", "")
return
}
s.restore(w, r, b.Path)
case "cancel":
backup.Cancel(s.DataDir)
s.renderBackups(w, r, "", "The restore is cancelled.")
case "delete":
name := r.PostFormValue("name")
if err := backup.Delete(s.backupDir(), name); err != nil {
if errors.Is(err, os.ErrNotExist) {
s.renderBackups(w, r, "There's no backup called "+name+".", "")
return
}
s.serverError(w, err)
return
}
s.renderBackups(w, r, "", "Deleted "+name+".")
default:
http.NotFound(w, r)
}
}
// backupDownload sends a backup file. It holds contacts and the app's
// data (not its secrets), so it's served to this machine only, like
// everything else here.
func (s *Server) backupDownload(w http.ResponseWriter, r *http.Request) {
b, err := backup.Find(s.backupDir(), r.PathValue("name"))
if err != nil {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "application/vnd.sqlite3")
w.Header().Set("Content-Disposition", `attachment; filename="`+b.Name+`"`)
w.Header().Set("Cache-Control", "no-store")
http.ServeFile(w, r, b.Path)
}
// restore stages a restore from a backup file, then restarts the app to
// apply it. Without a way to restart (tests, or not under Docker) it's
// left staged for the next start.
func (s *Server) restore(w http.ResponseWriter, r *http.Request, path string) {
res, err := backup.Stage(s.DB.DB, s.DataDir, path, db.Schema(), time.Now())
if err != nil {
s.renderBackups(w, r, "Not restored: "+err.Error(), "")
return
}
msg := "Restoring " + res.From + ". The current database is backed up as " + res.Backup + "."
if s.Restart == nil {
s.renderBackups(w, r, "", msg+" It's applied when Supermarket next starts.")
return
}
s.Log.Info("backups: restoring; restarting", "from", res.From)
// Reload once the app is back: Docker starts it again in a few seconds.
w.Header().Set("Refresh", "8; url=/settings/backups")
s.renderBackups(w, r, "", msg+" Supermarket is restarting to apply it; this page reloads by itself.")
go func() {
time.Sleep(500 * time.Millisecond)
s.Restart()
}()
}
// maxUpload is the biggest backup that can be uploaded.
const maxUpload = 4 << 30
// backupUpload takes a backup file from the browser (one downloaded from
// here, perhaps on another machine) and adds it to the list, checked;
// restoring it is a second step.
func (s *Server) backupUpload(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, maxUpload)
f, hdr, err := r.FormFile("file")
if err != nil {
s.renderBackups(w, r, "Choose a backup file to upload.", "")
return
}
defer f.Close()
if err := os.MkdirAll(s.backupDir(), 0o700); err != nil {
s.serverError(w, err)
return
}
tmp, err := os.CreateTemp(s.backupDir(), ".upload-*.db")
if err != nil {
s.serverError(w, err)
return
}
defer os.Remove(tmp.Name())
if _, err := io.Copy(tmp, f); err != nil {
tmp.Close()
s.renderBackups(w, r, "The upload didn't finish: "+err.Error(), "")
return
}
tmp.Close()
if err := backup.Check(tmp.Name()); err != nil {
s.renderBackups(w, r, hdr.Filename+" isn't a backup Supermarket can use: "+err.Error(), "")
return
}
note := "uploaded " + strings.TrimSuffix(filepath.Base(hdr.Filename), ".db")
b, err := backup.Adopt(tmp.Name(), s.backupDir(), note, time.Now())
if err != nil {
s.serverError(w, err)
return
}
s.renderBackups(w, r, "", "Uploaded as "+b.Name+". Restore it from the list when you're ready.")
}
+117
View File
@@ -0,0 +1,117 @@
package web
import (
"bytes"
"mime/multipart"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"time"
"supermarket/internal/backup"
)
func TestBackupsPage(t *testing.T) {
s, h := newTestServer(t, nil)
if body := do(h, http.MethodGet, "/settings/backups", nil, nil).Body.String(); !strings.Contains(body, "No backups yet") {
t.Errorf("empty: %s", body)
}
body := postForm(h, "/settings/backups/now", url.Values{"note": {"Before the import"}}).Body.String()
if !strings.Contains(body, "Backed up to app-") || !strings.Contains(body, "-manual-before-the-import.db") ||
!strings.Contains(body, "By you") || !strings.Contains(body, "before-the-import") {
t.Errorf("after backing up: %s", body)
}
bs, _ := backup.List(s.backupDir())
if len(bs) != 1 {
t.Fatalf("backups: %v", bs)
}
rec := do(h, http.MethodGet, "/settings/backups/file/"+bs[0].Name, nil, nil)
if rec.Code != http.StatusOK || !strings.HasPrefix(rec.Body.String(), "SQLite format 3") ||
!strings.Contains(rec.Header().Get("Content-Disposition"), bs[0].Name) {
t.Errorf("download: %d %v", rec.Code, rec.Header())
}
for _, bad := range []string{"..%2Fapp.db", "secrets.json", "app.db"} {
if rec := do(h, http.MethodGet, "/settings/backups/file/"+bad, nil, nil); rec.Code != http.StatusNotFound {
t.Errorf("%s: %d", bad, rec.Code)
}
}
// The daily one, once a day.
s.dailyBackup(time.Now())
s.dailyBackup(time.Now())
if bs, _ := backup.List(s.backupDir()); len(bs) != 2 {
t.Errorf("after the daily: %d", len(bs))
}
body = postForm(h, "/settings/backups/delete", url.Values{"name": {bs[0].Name}}).Body.String()
if !strings.Contains(body, "Deleted "+bs[0].Name) {
t.Errorf("delete: %s", body)
}
if _, err := os.Stat(bs[0].Path); err == nil {
t.Error("still there")
}
if body := postForm(h, "/settings/backups/delete", url.Values{"name": {"../app.db"}}).Body.String(); !strings.Contains(body, "There&#39;s no backup called") {
t.Errorf("bad delete: %s", body)
}
}
func TestRestoreFromThePage(t *testing.T) {
s, h := newTestServer(t, nil)
s.DB.PutJSON("test:value", "before")
b, err := backup.Make(s.DB.DB, s.backupDir(), backup.Manual, "good", time.Now().Add(-time.Hour))
if err != nil {
t.Fatal(err)
}
s.DB.PutJSON("test:value", "after")
var restarts atomic.Int32
s.Restart = func() { restarts.Add(1) }
rec := postForm(h, "/settings/backups/restore", url.Values{"name": {b.Name}})
body := rec.Body.String()
if !strings.Contains(body, "Restoring "+b.Name) || !strings.Contains(body, "this page reloads by itself") ||
!strings.Contains(body, "A restore is waiting") || rec.Header().Get("Refresh") == "" {
t.Errorf("restore: %v %s", rec.Header(), body)
}
time.Sleep(700 * time.Millisecond)
if restarts.Load() != 1 || !backup.Pending(s.DataDir) {
t.Errorf("restarts %d, pending %v", restarts.Load(), backup.Pending(s.DataDir))
}
// Cancelled before the restart: nothing happens.
body = postForm(h, "/settings/backups/cancel", nil).Body.String()
if !strings.Contains(body, "The restore is cancelled") || backup.Pending(s.DataDir) {
t.Errorf("cancel: %s", body)
}
if body := postForm(h, "/settings/backups/restore", url.Values{"name": {"../app.db"}}).Body.String(); !strings.Contains(body, "There&#39;s no backup called") {
t.Errorf("bad name: %s", body)
}
}
func TestBackupUpload(t *testing.T) {
s, h := newTestServer(t, nil)
b, _ := backup.Make(s.DB.DB, t.TempDir(), backup.Manual, "elsewhere", time.Now())
raw, _ := os.ReadFile(b.Path)
upload := func(name string, content []byte) string {
var buf bytes.Buffer
mw := multipart.NewWriter(&buf)
fw, _ := mw.CreateFormFile("file", name)
fw.Write(content)
mw.Close()
return do(h, http.MethodPost, "/settings/backups/upload", &buf, map[string]string{"Content-Type": mw.FormDataContentType()}).Body.String()
}
body := upload("app-from-laptop.db", raw)
if !strings.Contains(body, "Uploaded as app-") || !strings.Contains(body, "-manual-uploaded-app-from-laptop.db") {
t.Errorf("upload: %s", body)
}
if body := upload("notes.txt", []byte("hello")); !strings.Contains(body, "isn&#39;t a backup Supermarket can use") {
t.Errorf("bad upload: %s", body)
}
if bs, _ := backup.List(s.backupDir()); len(bs) != 1 {
t.Errorf("backups: %v", bs)
}
left, _ := filepath.Glob(filepath.Join(s.backupDir(), ".upload-*"))
if len(left) != 0 {
t.Errorf("temporary files left: %v", left)
}
}
+9 -4
View File
@@ -44,10 +44,15 @@ func (s *Server) gitea() *gitea.Client {
func (s *Server) applier(site seoSite) *seo.Applier {
p, _ := profile.Load(s.DB)
var repo, branch string
if p != nil && site.Index < len(p.Websites) {
if p != nil && site.Index >= 0 && site.Index < len(p.Websites) {
repo, branch = p.Websites[site.Index].Repo, p.Websites[site.Index].Branch
}
author := "Supermarket <supermarket@localhost>"
return &seo.Applier{Gitea: s.gitea(), Repo: repo, Branch: branch, ReposDir: filepath.Join(s.DataDir, "sites"), Author: s.commitAuthor()}
}
// commitAuthor is who Supermarket's commits are by: the Core's user, via
// Supermarket.
func (s *Server) commitAuthor() string {
if s.Core != nil && s.Core.Email != "" {
name := s.Core.Name
if name == "" {
@@ -55,9 +60,9 @@ func (s *Server) applier(site seoSite) *seo.Applier {
} else {
name += " (via Supermarket)"
}
author = name + " <" + s.Core.Email + ">"
return name + " <" + s.Core.Email + ">"
}
return &seo.Applier{Gitea: s.gitea(), Repo: repo, Branch: branch, ReposDir: filepath.Join(s.DataDir, "sites"), Author: author}
return "Supermarket <supermarket@localhost>"
}
func (s *Server) proposer() (*seo.Proposer, error) {
+33 -7
View File
@@ -62,13 +62,24 @@ func (s *Server) publishers() content.Publishers {
}
pubs[content.ChannelX] = xPublisher{c}
}
var li linkedInPublisher
if tok, urn := s.Secrets.Get(secrets.LinkedInAccessToken), s.Secrets.Get(secrets.LinkedInAuthorURN); tok != "" && urn != "" {
if e := s.linkedInExpiry(); e != nil && e.Expired() {
pubs[content.ChannelLinkedIn] = expiredPublisher{*e}
li.meErr = expiredPublisher{*e}.err()
} else {
pubs[content.ChannelLinkedIn] = linkedInPublisher{linkedin.New(tok, urn)}
li.me = linkedin.New(tok, urn)
}
}
if tok, org := s.Secrets.Get(secrets.LinkedInPageAccessToken), s.liPage(); tok != "" && org != nil {
if e := s.linkedInPageExpiry(); e != nil && e.Expired() {
li.pageErr = expiredPublisher{*e}.err()
} else {
li.page = linkedin.New(tok, org.URN)
}
}
if li.me != nil || li.page != nil || li.meErr != nil || li.pageErr != nil {
pubs[content.ChannelLinkedIn] = li
}
if c := s.redditUser(); c != nil {
pubs[content.ChannelReddit] = redditPublisher{s: s, c: c}
}
@@ -80,7 +91,11 @@ func (s *Server) publishers() content.Publishers {
type expiredPublisher struct{ e Expiry }
func (p expiredPublisher) Publish(context.Context, content.Post) (string, error) {
return "", fmt.Errorf("%s's sign-in expired on %s: reconnect %s under Settings → Social accounts, then publish again",
return "", p.err()
}
func (p expiredPublisher) err() error {
return fmt.Errorf("%s's sign-in expired on %s: reconnect %s under Settings → Social accounts, then publish again",
p.e.Network, p.e.At.Local().Format("2 Jan 2006"), p.e.Network)
}
@@ -96,12 +111,23 @@ func (p xPublisher) Publish(ctx context.Context, post content.Post) (string, err
return p.c.PostTweet(ctx, text)
}
type linkedInPublisher struct{ c *linkedin.Client }
// Publish attaches the source link as an article preview.
func (p linkedInPublisher) Publish(ctx context.Context, post content.Post) (string, error) {
c := p.me
switch {
case post.AsPage && p.pageErr != nil:
return "", p.pageErr
case post.AsPage && p.page == nil:
return "", errNoPage
case post.AsPage:
c = p.page
case p.meErr != nil:
return "", p.meErr
case p.me == nil:
return "", errNoMe
}
if post.SourceURL == "" {
return p.c.PostUpdate(ctx, post.Text, nil)
return c.PostUpdate(ctx, post.Text, nil)
}
// LinkedIn wants the card's title from us. A page that can't be read
// still gets a card, titled with its address.
@@ -109,7 +135,7 @@ func (p linkedInPublisher) Publish(ctx context.Context, post content.Post) (stri
ictx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
link.Title, link.Description, _ = site.PageInfo(ictx, post.SourceURL, "Supermarket/1 (link preview)")
return p.c.PostUpdate(ctx, post.Text, link)
return c.PostUpdate(ctx, post.Text, link)
}
type redditPublisher struct {
+13 -2
View File
@@ -74,9 +74,13 @@ func groupBatches(drafts []content.Draft) []*draftBatch {
func (s *Server) connected() map[string]bool {
out := map[string]bool{}
for id, p := range s.publishers() {
if _, expired := p.(expiredPublisher); !expired {
out[id] = true
if _, expired := p.(expiredPublisher); expired {
continue
}
if li, ok := p.(linkedInPublisher); ok && li.me == nil && li.page == nil {
continue // only expired sign-ins
}
out[id] = true
}
return out
}
@@ -100,6 +104,7 @@ func (s *Server) renderInbox(w http.ResponseWriter, r *http.Request, errMsg stri
"Sections": sections,
"Reddit": s.redditViews(r.Context(), pending),
"Connected": s.connected(),
"Page": s.liPageIfSignedIn(),
"Tagged": s.tagger() != nil,
"Now": time.Now().Add(time.Hour).Truncate(time.Hour).Format(dateTimeLocal),
"Zone": time.Now().Format("MST"),
@@ -246,6 +251,12 @@ func (s *Server) draftAction(w http.ResponseWriter, r *http.Request) {
return
}
}
if as, sent := r.PostForm["linkedin_as"]; sent {
if err := content.SetLinkedInAs(s.DB, id, as[0]); err != nil {
fail(err)
return
}
}
}
switch action {
case "save":
+148
View File
@@ -0,0 +1,148 @@
package web
import (
"context"
"net/http"
"strconv"
"strings"
"time"
"supermarket/internal/hugorepo"
"supermarket/internal/sites"
"supermarket/internal/tracking"
)
// captureClient is the HTTP client for testing a Lead Capture (a test's
// TLS server's in tests).
var captureClient = sites.TestClient
func captureKey(repo string) string { return "sites:lead-capture:" + repo }
func formsPRKey(repo string) string { return "sites:lead-forms-pr:" + repo }
// formsPR is the pull request that connects a site's forms.
type formsPR struct {
Number int64 `json:"number"`
URL string `json:"url"`
Capture string `json:"capture"`
At time.Time `json:"at"`
State string `json:"state"` // open, merged, closed
}
func (s *Server) sitesFormsPage(w http.ResponseWriter, r *http.Request) {
s.renderForms(w, r, "", "")
}
func (s *Server) renderForms(w http.ResponseWriter, r *http.Request, errMsg, flash string) {
all, cur := s.currentSite(r)
data := map[string]any{"Sites": all, "Current": cur, "Gitea": s.gitea() != nil, "Payload": sites.LeadPayloadFields,
"Goal": tracking.LeadGoal, "Plausible": s.plausible() != nil}
if s.Core != nil && s.Core.Domain != "" {
data["CRM"] = "https://espocrm." + s.Core.Domain
}
if cur != nil && cur.Repo != "" {
var capture string
s.DB.GetJSON(captureKey(cur.Repo), &capture)
data["Capture"] = capture
var pr formsPR
if ok, _ := s.DB.GetJSON(formsPRKey(cur.Repo), &pr); ok {
if pr.State == "open" && s.gitea() != nil {
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
if pull, err := s.gitea().GetPull(ctx, cur.Repo, pr.Number); err == nil {
switch {
case pull.Merged:
pr.State = "merged"
case pull.State == "closed":
pr.State = "closed"
}
_ = s.DB.PutJSON(formsPRKey(cur.Repo), pr)
}
cancel()
}
data["PR"] = pr
}
var synced siteSynced
if ok, _ := s.DB.GetJSON(siteSyncKey(cur.Repo), &synced); ok && !synced.At.IsZero() {
data["HasSynced"] = true
wc := &hugorepo.Repo{Dir: s.siteDir(cur.Repo), Branch: synced.Branch}
wc.Acquire()
cat, _ := sites.Read(wc.Dir, wc.PathOf)
st := sites.ReadForms(wc, cat)
wc.Release()
data["State"] = st
data["Connected"] = st.Connected(capture)
}
}
data["Leads"], _ = tracking.FormLeads(s.DB, 20)
s.render(w, r, "sites-forms", page{Title: "Lead forms", Nav: "sites/forms", Error: errMsg, Flash: flash, Data: data})
}
func (s *Server) sitesFormsAction(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
_, cur := s.currentSite(r)
if cur == nil || cur.Repo == "" {
s.renderForms(w, r, "Set this website's Hugo repository in Settings → Profile first.", "")
return
}
capture := strings.TrimSpace(r.PostFormValue("capture"))
if _, has := r.PostForm["capture"]; !has {
s.DB.GetJSON(captureKey(cur.Repo), &capture)
}
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Minute)
defer cancel()
switch r.PathValue("action") {
case "save":
if capture != "" {
if err := sites.CheckCaptureURL(capture); err != nil {
s.renderForms(w, r, err.Error(), "")
return
}
}
if err := s.DB.PutJSON(captureKey(cur.Repo), capture); err != nil {
s.serverError(w, err)
return
}
if capture == "" {
s.renderForms(w, r, "", "The Lead Capture address is removed.")
return
}
if err := sites.TestCapture(ctx, captureClient(), capture, cur.URL); err != nil {
s.renderForms(w, r, "Saved, but the test failed: "+err.Error(), "")
return
}
s.renderForms(w, r, "", "Saved and tested: "+cur.URL+" may post to it. Nothing was created in the CRM.")
case "connect":
if capture == "" {
s.renderForms(w, r, "Save the Lead Capture address first.", "")
return
}
if s.gitea() == nil {
s.renderForms(w, r, "Save a Gitea token under Settings → Search engines first.", "")
return
}
cat, err := s.catalog(ctx, *cur, true)
if err != nil {
s.renderForms(w, r, err.Error(), "")
return
}
formPage := ""
if t := cat.Type("form"); t != nil && len(t.Pages) > 0 {
formPage = t.Pages[0]
}
pull, err := sites.ConnectForms(ctx, s.applier(seoSite{Index: cur.Index, URL: cur.URL}), capture, formPage)
if err != nil {
s.renderForms(w, r, err.Error(), "")
return
}
pr := formsPR{Number: pull.Number, URL: pull.HTMLURL, Capture: capture, At: time.Now(), State: "open"}
if err := s.DB.PutJSON(formsPRKey(cur.Repo), pr); err != nil {
s.serverError(w, err)
return
}
http.Redirect(w, r, "/sites/forms?site="+strconv.Itoa(cur.Index), http.StatusSeeOther)
default:
http.NotFound(w, r)
}
}
+197
View File
@@ -0,0 +1,197 @@
package web
import (
"context"
"errors"
"net/http"
"regexp"
"strings"
"time"
linkedinapi "supermarket/internal/api/linkedin"
"supermarket/internal/content"
"supermarket/internal/oauth"
"supermarket/internal/secrets"
)
// Posting as the company page needs a second LinkedIn app with the
// Community Management API, which LinkedIn approves by hand; see PLAN.md,
// Future enhancements item 1.
const (
liPageScopesKey = "linkedin-page:scopes"
liPageOrgsKey = "linkedin-page:orgs" // the pages the sign-in may post for
liPageOrgKey = "linkedin-page:org" // the one chosen
liPageNoteKey = "linkedin-page:note" // why the pages couldn't be listed
liPageProvider = "linkedin-page"
liPageNetwork = "LinkedIn page"
)
// pageSetup is the company page's part of its card.
type pageSetup struct {
Orgs []linkedinapi.Org
Chosen *linkedinapi.Org
Default string // content.AsPage or ""
Scopes string
Note string // why listing failed
Signed bool
Approved string // what the user must have from LinkedIn
}
func (s *Server) liPageScopes() string {
var sc string
if _, err := s.DB.GetJSON(liPageScopesKey, &sc); err == nil && strings.TrimSpace(sc) != "" {
return sc
}
return oauth.LinkedInPageScopes
}
// liPage is the chosen company page, or nil.
func (s *Server) liPage() *linkedinapi.Org {
var o linkedinapi.Org
if ok, _ := s.DB.GetJSON(liPageOrgKey, &o); !ok || o.URN == "" {
return nil
}
return &o
}
func (s *Server) pageSetup() *pageSetup {
p := &pageSetup{Scopes: s.liPageScopes(), Signed: s.Secrets.Has(secrets.LinkedInPageAccessToken), Chosen: s.liPage()}
s.DB.GetJSON(liPageOrgsKey, &p.Orgs)
s.DB.GetJSON(liPageNoteKey, &p.Note)
s.DB.GetJSON(content.LinkedInDefaultKey, &p.Default)
return p
}
// linkedInPageExpiry is when the page's sign-in runs out, or nil.
func (s *Server) linkedInPageExpiry() *Expiry {
if !s.Secrets.Has(secrets.LinkedInPageAccessToken) {
return nil
}
c := s.connections()[liPageProvider]
at := c.Expires
if at.IsZero() {
if c.At.IsZero() {
return nil
}
at = c.At.Add(linkedInTokenLife)
}
return &Expiry{Network: liPageNetwork, At: at}
}
// pageOrgs lists the pages the page sign-in may post for, and keeps them.
func (s *Server) pageOrgs(ctx context.Context, token string) ([]linkedinapi.Org, error) {
orgs, err := linkedinapi.New(token, "").Organizations(ctx)
note := ""
if err != nil {
note = err.Error()
} else if len(orgs) == 0 {
note = "LinkedIn lists no page you may post for: you need an approved administrator or content admin role on the company page."
}
_ = s.DB.PutJSON(liPageNoteKey, note)
if err != nil {
return nil, err
}
if err := s.DB.PutJSON(liPageOrgsKey, orgs); err != nil {
return nil, err
}
// The only page, or the chosen one gone: choose for the user.
cur := s.liPage()
still := false
for _, o := range orgs {
if cur != nil && o.URN == cur.URN {
still = true
}
}
if len(orgs) == 1 && !still {
_ = s.DB.PutJSON(liPageOrgKey, orgs[0])
}
return orgs, nil
}
var orgID = regexp.MustCompile(`(?:urn:li:organization:|linkedin\.com/company/)?(\d{3,})\b`)
// linkedInPageSave saves the page's settings: which page, what new
// LinkedIn drafts default to, and the scopes the sign-in asks for.
func (s *Server) linkedInPageSave(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
switch r.PostFormValue("do") {
case "refresh":
tok := s.Secrets.Get(secrets.LinkedInPageAccessToken)
if tok == "" {
redirect(w, r, "/settings/accounts", "")
return
}
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
_, _ = s.pageOrgs(ctx, tok)
redirect(w, r, "/settings/accounts", "saved")
return
}
if sc := strings.Join(strings.Fields(r.PostFormValue("scopes")), " "); sc != "" {
if err := s.DB.PutJSON(liPageScopesKey, sc); err != nil {
s.serverError(w, err)
return
}
}
def := ""
if r.PostFormValue("default") == content.AsPage {
def = content.AsPage
}
if err := s.DB.PutJSON(content.LinkedInDefaultKey, def); err != nil {
s.serverError(w, err)
return
}
choice := strings.TrimSpace(r.PostFormValue("org"))
if manual := strings.TrimSpace(r.PostFormValue("org_manual")); manual != "" {
m := orgID.FindStringSubmatch(manual)
if m == nil {
s.render(w, r, "message", page{Title: "LinkedIn page", Nav: "settings/accounts",
Error: "That isn't a company page's number: it's in the page admin view's address, linkedin.com/company/<number>/admin.",
Data: map[string]string{"Back": "/settings/accounts"}})
return
}
o := linkedinapi.Org{URN: "urn:li:organization:" + m[1], ID: m[1], Name: "Page " + m[1]}
if err := s.DB.PutJSON(liPageOrgKey, o); err != nil {
s.serverError(w, err)
return
}
} else if choice != "" {
var orgs []linkedinapi.Org
s.DB.GetJSON(liPageOrgsKey, &orgs)
for _, o := range orgs {
if o.URN == choice {
if err := s.DB.PutJSON(liPageOrgKey, o); err != nil {
s.serverError(w, err)
return
}
}
}
}
redirect(w, r, "/settings/accounts", "saved")
}
// linkedInPublisher posts as you or as the company page, as each draft
// says.
type linkedInPublisher struct {
me *linkedinapi.Client // nil: you aren't signed in
meErr error // why not (an expired sign-in)
page *linkedinapi.Client // nil: no page set up
pageErr error
}
var errNoPage = errors.New("this draft posts as the company page, which isn't set up: connect the LinkedIn page under Settings → Social accounts, or post it as you")
var errNoMe = errors.New("this draft posts as you, but LinkedIn isn't connected: connect it under Settings → Social accounts, or post it as the company page")
// liPageIfSignedIn is the chosen page when the page app is signed in, for
// the "post as" choice on LinkedIn drafts.
func (s *Server) liPageIfSignedIn() *linkedinapi.Org {
if !s.Secrets.Has(secrets.LinkedInPageAccessToken) {
return nil
}
return s.liPage()
}
+78
View File
@@ -0,0 +1,78 @@
package web
import (
"context"
"net/http"
"strconv"
"strings"
"time"
"supermarket/internal/profile"
"supermarket/internal/sites"
)
func (s *Server) newSitePage(w http.ResponseWriter, r *http.Request) {
s.renderNewSite(w, r, sites.Defaults(), "")
}
func (s *Server) renderNewSite(w http.ResponseWriter, r *http.Request, n sites.NewSite, errMsg string) {
gitea := ""
if s.gitea() != nil {
gitea = s.giteaURL()
}
s.render(w, r, "sites-new", page{Title: "New site", Nav: "sites/new", Error: errMsg, Data: map[string]any{
"N": n, "Fonts": sites.Fonts, "Gitea": gitea,
}})
}
// newSiteCreate makes the new site: the first commit to its empty
// repository, then the site in the profile, read like the others.
func (s *Server) newSiteCreate(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
f := r.PostFormValue
n := sites.NewSite{Repo: f("repo"), URL: f("url"), Title: f("title"), Tagline: f("tagline"), Email: f("email"),
Dark: f("dark"), Primary: f("primary"), Accent: f("accent"), Font: f("font"), Logo: f("logo")}
if err := n.Check(); err != nil {
s.renderNewSite(w, r, n, err.Error())
return
}
prof, err := profile.Load(s.DB)
if err != nil {
s.serverError(w, err)
return
}
if prof == nil {
prof = &profile.Profile{}
}
for _, ws := range prof.Websites {
if strings.EqualFold(strings.TrimRight(ws.URL, "/"), n.URL) {
s.renderNewSite(w, r, n, n.URL+" is already one of your websites.")
return
}
}
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Minute)
defer cancel()
branch, err := sites.Create(ctx, s.gitea(), n, s.siteDir(n.Repo), s.commitAuthor())
if err != nil {
s.renderNewSite(w, r, n, err.Error())
return
}
prof.Websites = append(prof.Websites, profile.Website{URL: n.URL, Repo: n.Repo, Branch: branch})
if err := profile.Save(s.DB, prof); err != nil {
s.serverError(w, err)
return
}
_ = s.DB.PutJSON(siteSyncKey(n.Repo), siteSynced{At: time.Now(), Branch: branch})
index := 0
if p, _ := profile.Load(s.DB); p != nil {
for i, ws := range p.Websites {
if strings.TrimRight(ws.URL, "/") == n.URL {
index = i
}
}
}
http.Redirect(w, r, "/sites?site="+strconv.Itoa(index)+"&msg=site-created", http.StatusSeeOther)
}
+208
View File
@@ -0,0 +1,208 @@
package web
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"os/exec"
"path/filepath"
"strings"
"testing"
"supermarket/internal/ai"
"supermarket/internal/hugorepo"
"supermarket/internal/hugorepo/hugotest"
"supermarket/internal/profile"
"supermarket/internal/secrets"
"supermarket/internal/sites"
"supermarket/internal/theme"
)
func TestNewSite(t *testing.T) {
if hugorepo.HugoVersion(context.Background()) == "" {
t.Skip("no hugo")
}
bare := filepath.Join(t.TempDir(), "acme.git")
if out, err := exec.Command("git", "init", "--quiet", "--bare", "--initial-branch", "main", bare).CombinedOutput(); err != nil {
t.Fatalf("%s", out)
}
clone := "file://" + bare
empty := true
var opened []map[string]string
g := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/api/v1/repos/Us/acme":
fmt.Fprintf(w, `{"full_name":"Us/acme","default_branch":"main","clone_url":%q,"empty":%v,"permissions":{"push":true}}`, clone, empty)
case r.URL.Path == "/api/v1/repos/Us/acme/pulls" && r.Method == http.MethodPost:
var body map[string]string
json.NewDecoder(r.Body).Decode(&body)
opened = append(opened, body)
fmt.Fprint(w, `{"number":1,"state":"open","html_url":"https://gitea.example/pulls/1"}`)
default:
http.NotFound(w, r)
}
}))
defer g.Close()
s, h := newTestServer(t, nil)
profile.Save(s.DB, &profile.Profile{Name: "Acme", Description: "Widgets.", Websites: []profile.Website{{URL: "https://old.example"}}})
postForm(h, "/settings/search", url.Values{"gitea_url": {g.URL}, secrets.GiteaToken: {"tok"}})
if body := do(h, http.MethodGet, "/sites/new", nil, nil).Body.String(); !strings.Contains(body, g.URL+"/repo/create") || !strings.Contains(body, `value="#e0ff4f"`) {
t.Errorf("form: %s", body)
}
form := url.Values{"repo": {"Us/acme"}, "url": {"https://www.acme.example"}, "title": {"Acme Widgets"}, "tagline": {"Widgets for everyone"},
"email": {"hello@acme.example"}, "dark": {"#1d1238"}, "primary": {"#ffb703"}, "accent": {"#e4572e"}, "font": {"Manrope"}}
for field, bad := range map[string]string{"url": "http://acme.example", "dark": "purple", "repo": "nope", "title": " "} {
v := url.Values{}
for k, vs := range form {
v[k] = vs
}
v.Set(field, bad)
if rec := postForm(h, "/sites/new", v); rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `role="alert"`) {
t.Errorf("bad %s accepted: %d", field, rec.Code)
}
}
empty = false
if body := postForm(h, "/sites/new", form).Body.String(); !strings.Contains(body, "isn&#39;t empty") {
t.Errorf("non-empty repository: %s", body)
}
empty = true
rec := postForm(h, "/sites/new", form)
if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/sites?site=1&msg=site-created" {
t.Fatalf("create: %d %s", rec.Code, rec.Body.String())
}
show := func(ref, path string) string {
out, err := exec.Command("git", "--git-dir", bare, "show", ref+":"+path).CombinedOutput()
if err != nil {
t.Fatalf("%s %s: %s", ref, path, out)
}
return string(out)
}
cfg := show("main", "hugo.toml")
for _, want := range []string{`baseURL = "https://www.acme.example/"`, `title = "Acme Widgets"`, `theme = "supermarket"`, `primary = "#ffb703"`, `font = "Manrope"`, `email = "hello@acme.example"`} {
if !strings.Contains(cfg, want) {
t.Errorf("hugo.toml lacks %s:\n%s", want, cfg)
}
}
if v := show("main", "themes/supermarket/VERSION"); v != "1\n" || !strings.Contains(show("main", "content/_index.md"), "Widgets for everyone") {
t.Errorf("theme or home: %q", v)
}
p, _ := profile.Load(s.DB)
if len(p.Websites) != 2 || p.Websites[1].URL != "https://www.acme.example" || p.Websites[1].Repo != "Us/acme" || p.Websites[1].Branch != "main" {
t.Errorf("profile: %+v", p.Websites)
}
body := do(h, http.MethodGet, "/sites?site=1&msg=site-created", nil, nil).Body.String()
for _, want := range []string{"The site is started", "First pages", "version 1", ">Home page<", ">About page<", ">Contact page<", "<summary>form", "<summary>hero"} {
if !strings.Contains(body, want) {
t.Errorf("site page lacks %q", want)
}
}
// The same address again is refused.
if body := postForm(h, "/sites/new", form).Body.String(); !strings.Contains(body, "already one of your websites") {
t.Errorf("again: %s", body)
}
// A contact page from the theme's sections joins the top menu.
composed, _ := json.Marshal(map[string]any{"path": "/contact/", "title": "Contact", "description": "Write to us.",
"sections_yaml": "- type: hero\n title: Talk to us\n compact: true\n- type: form\n headline: Write to us\n subject: Contact\n fields:\n - { name: name, label: Name, required: true }\n - { name: email, label: Email, type: email, required: true }\n",
"needs": []string{}})
newAIClient = func(ai.Config, *secrets.Store) (ai.Client, error) { return cannedAI{string(composed)}, nil }
defer func() { newAIClient = ai.New }()
if rec := postForm(h, "/sites/pages", url.Values{"site": {"1"}, "kind": {"contact"}}); rec.Code != http.StatusSeeOther {
t.Fatalf("contact: %d %s", rec.Code, rec.Body.String())
}
pg, _ := sites.GetPage(s.DB, 1)
if pg.Error != "" || len(pg.Warnings) != 0 {
t.Errorf("contact page: %q %v", pg.Error, pg.Warnings)
}
postForm(h, "/sites/pages/1/pr", url.Values{"title": {pg.Title}, "description": {pg.Description}, "path": {pg.Path}, "sections": {pg.Sections}})
if len(opened) != 1 {
t.Fatalf("no pull request: %v", opened)
}
if fm := show("supermarket/site-page-1", "content/contact.md"); !strings.Contains(fm, "menus:\n main:\n weight: 90\n") {
t.Errorf("contact file:\n%s", fm)
}
if !strings.Contains(opened[0]["body"], "the page is at /contact/") {
t.Errorf("build check: %s", opened[0]["body"])
}
}
func TestThemeUpdate(t *testing.T) {
if hugorepo.HugoVersion(context.Background()) == "" {
t.Skip("no hugo")
}
// A site with an older copy of the theme: version 0, a file the theme
// no longer has, and the header changed by hand.
files := map[string]string{"hugo.toml": "baseURL = 'https://acme.example/'\ntitle = 'Acme'\ntheme = 'supermarket'\ndisableKinds = ['taxonomy', 'term', 'RSS', 'sitemap']\n",
"content/_index.md": "---\ntitle: Home\nsections:\n - type: hero\n title: Hi\n---\n"}
old := theme.Files()
old["VERSION"] = "0\n"
old["layouts/partials/retired.html"] = "<p>old</p>"
delete(old, "layouts/404.html")
old["MANIFEST"] = theme.Manifest(old)
old["layouts/partials/header.html"] += "<!-- changed by hand -->"
for p, b := range old {
files[theme.Dir+"/"+p] = b
}
clone := hugotest.Site(t, files)
var opened []map[string]string
g := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/api/v1/repos/Us/acme":
fmt.Fprintf(w, `{"full_name":"Us/acme","default_branch":"main","clone_url":%q,"permissions":{"push":true}}`, clone)
case r.URL.Path == "/api/v1/repos/Us/acme/pulls" && r.Method == http.MethodPost:
var body map[string]string
json.NewDecoder(r.Body).Decode(&body)
opened = append(opened, body)
fmt.Fprint(w, `{"number":4,"state":"open","html_url":"https://gitea.example/pulls/4"}`)
default:
http.NotFound(w, r)
}
}))
defer g.Close()
s, h := newTestServer(t, nil)
profile.Save(s.DB, &profile.Profile{Name: "Acme", Websites: []profile.Website{{URL: "https://acme.example", Repo: "Us/acme"}}})
postForm(h, "/settings/search", url.Values{"gitea_url": {g.URL}, secrets.GiteaToken: {"tok"}})
postForm(h, "/sites/sync", url.Values{"site": {"0"}})
body := do(h, http.MethodGet, "/sites", nil, nil).Body.String()
if !strings.Contains(body, "theme version 0; Supermarket has version 1") || !strings.Contains(body, "Changed by hand in the site's copy of the theme: layouts/partials/header.html.") {
t.Errorf("before: %s", body)
}
if rec := postForm(h, "/sites/theme/update", url.Values{"site": {"0"}}); rec.Code != http.StatusSeeOther {
t.Fatalf("update: %d %s", rec.Code, rec.Body.String())
}
if len(opened) != 1 {
t.Fatalf("pull requests: %v", opened)
}
pr := opened[0]
for _, want := range []string{"from version 0 to 1", "**Changed:**\n- `layouts/partials/header.html`", "**Added:**\n- `layouts/404.html`",
"**Removed:**\n- `layouts/partials/retired.html`", "replaced by this update", "Checked with a build"} {
if !strings.Contains(pr["body"], want) {
t.Errorf("pull request lacks %q:\n%s", want, pr["body"])
}
}
if pr["head"] != "supermarket/theme-1" || pr["title"] != "Sites: update the theme to version 1" {
t.Errorf("pull request: %v", pr)
}
bare := strings.TrimPrefix(clone, "file://")
if out, _ := exec.Command("git", "--git-dir", bare, "show", "supermarket/theme-1:"+theme.Dir+"/VERSION").CombinedOutput(); string(out) != "1\n" {
t.Errorf("VERSION on the branch: %q", out)
}
if out, err := exec.Command("git", "--git-dir", bare, "show", "supermarket/theme-1:"+theme.Dir+"/layouts/partials/retired.html").CombinedOutput(); err == nil {
t.Errorf("the retired file is still there: %s", out)
}
// Once merged, the site is up to date; updating again is refused.
exec.Command("git", "--git-dir", bare, "update-ref", "refs/heads/main", "refs/heads/supermarket/theme-1").Run()
postForm(h, "/sites/sync", url.Values{"site": {"0"}})
body = do(h, http.MethodGet, "/sites", nil, nil).Body.String()
if !strings.Contains(body, "version 1: the latest") || strings.Contains(body, "Changed by hand") || !strings.Contains(body, "https://gitea.example/pulls/4") {
t.Errorf("after: %s", body)
}
if body := postForm(h, "/sites/theme/update", url.Values{"site": {"0"}}).Body.String(); !strings.Contains(body, "already has the theme&#39;s version 1") {
t.Errorf("again: %s", body)
}
}
+6 -3
View File
@@ -72,10 +72,13 @@ func (s *Server) linkedInExpiry() *Expiry {
// reminders are the sign-ins running out soon, or already, for the
// Overview and Posts.
func (s *Server) reminders() []Expiry {
if e := s.linkedInExpiry(); e != nil && e.Soon() {
return []Expiry{*e}
var out []Expiry
for _, e := range []*Expiry{s.linkedInExpiry(), s.linkedInPageExpiry()} {
if e != nil && e.Soon() {
out = append(out, *e)
}
}
return nil
return out
}
const connectionsKey = "connections"
+77 -50
View File
@@ -48,6 +48,7 @@ type Server struct {
MCPToken string
MCPSocket string // the MCP socket's path on the host, for Hermes' config
MCP http.Handler
Restart func() // stops the app so Docker starts it again; nil in tests
Log *slog.Logger
// What the legacy import did at startup, or why it failed.
@@ -118,6 +119,7 @@ func (s *Server) Handler() (http.Handler, error) {
mux.HandleFunc("GET /settings/accounts", s.accountsPage)
mux.HandleFunc("POST /settings/accounts", s.accountsSave)
mux.HandleFunc("POST /settings/accounts/linkedin-page", s.linkedInPageSave)
mux.HandleFunc("POST /auth/{provider}/start", s.oauthStart)
mux.HandleFunc("GET /auth/{provider}/callback", s.oauthCallback)
@@ -184,6 +186,11 @@ func (s *Server) Handler() (http.Handler, error) {
mux.HandleFunc("GET /sites/pages/{id}", s.sitePagePage)
mux.HandleFunc("POST /sites/pages/{id}/{action}", s.sitePageAction)
mux.HandleFunc("GET /sites/publishing", s.sitesPublishingPage)
mux.HandleFunc("POST /sites/theme/update", s.sitesThemeUpdate)
mux.HandleFunc("GET /sites/new", s.newSitePage)
mux.HandleFunc("POST /sites/new", s.newSiteCreate)
mux.HandleFunc("GET /sites/forms", s.sitesFormsPage)
mux.HandleFunc("POST /sites/forms/{action}", s.sitesFormsAction)
mux.HandleFunc("GET /sites/previews", s.sitesPreviewsPage)
mux.HandleFunc("POST /sites/previews/build", s.sitesPreviewBuild)
mux.HandleFunc("POST /sites/previews/delete", s.sitesPreviewDelete)
@@ -230,6 +237,10 @@ func (s *Server) Handler() (http.Handler, error) {
mux.HandleFunc("POST /crm/{action}", s.crmAction)
mux.HandleFunc("POST /crm/{id}/{action}", s.crmAction)
mux.HandleFunc("GET /settings/backups", s.backupsPage)
mux.HandleFunc("POST /settings/backups/{action}", s.backupsAction)
mux.HandleFunc("GET /settings/backups/file/{name}", s.backupDownload)
mux.HandleFunc("POST /settings/backups/upload", s.backupUpload)
mux.HandleFunc("GET /settings/core", s.corePage)
mux.HandleFunc("GET /settings/core/checks", s.coreChecks)
@@ -300,6 +311,19 @@ func sameOrigin(r *http.Request) bool {
return false
}
// humanBytes is a file size for people: "840 KB", "12.3 MB".
func humanBytes(n int64) string {
switch {
case n >= 1<<30:
return fmt.Sprintf("%.1f GB", float64(n)/(1<<30))
case n >= 1<<20:
return fmt.Sprintf("%.1f MB", float64(n)/(1<<20))
case n >= 1<<10:
return fmt.Sprintf("%d KB", n>>10)
}
return fmt.Sprintf("%d bytes", n)
}
var backticks = regexp.MustCompile("`([^`]+)`")
// ticks shows Markdown's `code` spans as code, the rest as plain text.
@@ -313,6 +337,7 @@ func (s *Server) loadTemplates() error {
"join": strings.Join,
"ago": ago,
"ticks": ticks,
"bytes": humanBytes,
"kindLabel": sites.KindLabel,
"add": func(a, b int) int { return a + b },
"hasPrefix": strings.HasPrefix,
@@ -482,56 +507,58 @@ func (s *Server) fragment(w http.ResponseWriter, page, name string, data any) {
// Messages shown after a redirect, by code, so no user text is reflected.
var flashes = map[string]string{
"saved": "Saved.",
"deleted": "Deleted.",
"x-connected": "X is connected.",
"li-connected": "LinkedIn is connected.",
"google-connected": "Search Console is connected. Choose each website's property below, then sync.",
"synced": "Synced from Search Console.",
"report-written": "This week's report is written.",
"setup-opened": "Pull request opened: read it on Gitea, then merge it.",
"pinged": "Sent to IndexNow.",
"brief-written": "Brief written. Read it, answer its questions, then write the page.",
"page-written": "Page drafted. Read it, and confirm or remove every sentence that claims an experience.",
"keywords-found": "Looked for keywords: the candidates are below.",
"top-read": "Read the live top results.",
"proposed": "Proposed: read each one, edit it if you like, then say yes or no.",
"approved": "Approved: Supermarket is making the pull request; it shows here in a minute.",
"declined": "Declined.",
"auditing": "Auditing. It reads up to 300 pages politely, so it takes a few minutes; this page updates when it's done.",
"no-data": "There isn't two weeks of Search Console data yet.",
"reddit-connected": "Reddit is connected.",
"crm-test": "Test Lead queued. Hermes creates it on its next run; or run it now (below).",
"crm-sync": "Sync requested: Hermes copies CRM records on its next run.",
"accepted": "Accepted: queued for the CRM. Hermes adds it on its next run.",
"rejected": "Set aside.",
"reconsidered": "Back in New.",
"suppressed": "Added to the suppression list.",
"unsuppressed": "Taken off the suppression list.",
"prospect-added": "Added. Review it below.",
"outcome": "Outcome recorded.",
"discovering": "Searching. It takes a few minutes; new companies appear in Review, tagged with this signal.",
"rules-refreshed": "Rules refreshed.",
"imported": "Imported.",
"hunter-done": "Hunter.io search done: the result is on the card.",
"verified": "Checked with Hunter.io: the result is on each person.",
"drafted-outreach": "Drafted. Read it, edit it, then queue it to send.",
"queued": "Queued: it goes out in turn, within your sending hours.",
"unqueued": "Back in Drafts.",
"sent": "Sent.",
"marked-sent": "Marked as sent.",
"reply-recorded": "Reply recorded.",
"checked": "Inbox checked: what it found is above.",
"test-sent": "Test email sent: check your inbox.",
"oauth-expired": "That sign-in took too long or was already used. Try again.",
"dismissed": "Dismissed.",
"restored": "Restored.",
"drafted": "Drafts written. Review them below.",
"published": "Published.",
"discarded": "Discarded.",
"scheduled": "Scheduled.",
"posted": "Marked as posted: it's under Content → Published.",
"unscheduled": "Back in Posts: edit it, then publish or schedule it again.",
"saved": "Saved.",
"deleted": "Deleted.",
"x-connected": "X is connected.",
"li-connected": "LinkedIn is connected.",
"site-created": "The site is started: its first commit is on Gitea. Build its first pages below.",
"li-page-connected": "The LinkedIn page app is connected.",
"google-connected": "Search Console is connected. Choose each website's property below, then sync.",
"synced": "Synced from Search Console.",
"report-written": "This week's report is written.",
"setup-opened": "Pull request opened: read it on Gitea, then merge it.",
"pinged": "Sent to IndexNow.",
"brief-written": "Brief written. Read it, answer its questions, then write the page.",
"page-written": "Page drafted. Read it, and confirm or remove every sentence that claims an experience.",
"keywords-found": "Looked for keywords: the candidates are below.",
"top-read": "Read the live top results.",
"proposed": "Proposed: read each one, edit it if you like, then say yes or no.",
"approved": "Approved: Supermarket is making the pull request; it shows here in a minute.",
"declined": "Declined.",
"auditing": "Auditing. It reads up to 300 pages politely, so it takes a few minutes; this page updates when it's done.",
"no-data": "There isn't two weeks of Search Console data yet.",
"reddit-connected": "Reddit is connected.",
"crm-test": "Test Lead queued. Hermes creates it on its next run; or run it now (below).",
"crm-sync": "Sync requested: Hermes copies CRM records on its next run.",
"accepted": "Accepted: queued for the CRM. Hermes adds it on its next run.",
"rejected": "Set aside.",
"reconsidered": "Back in New.",
"suppressed": "Added to the suppression list.",
"unsuppressed": "Taken off the suppression list.",
"prospect-added": "Added. Review it below.",
"outcome": "Outcome recorded.",
"discovering": "Searching. It takes a few minutes; new companies appear in Review, tagged with this signal.",
"rules-refreshed": "Rules refreshed.",
"imported": "Imported.",
"hunter-done": "Hunter.io search done: the result is on the card.",
"verified": "Checked with Hunter.io: the result is on each person.",
"drafted-outreach": "Drafted. Read it, edit it, then queue it to send.",
"queued": "Queued: it goes out in turn, within your sending hours.",
"unqueued": "Back in Drafts.",
"sent": "Sent.",
"marked-sent": "Marked as sent.",
"reply-recorded": "Reply recorded.",
"checked": "Inbox checked: what it found is above.",
"test-sent": "Test email sent: check your inbox.",
"oauth-expired": "That sign-in took too long or was already used. Try again.",
"dismissed": "Dismissed.",
"restored": "Restored.",
"drafted": "Drafts written. Review them below.",
"published": "Published.",
"discarded": "Discarded.",
"scheduled": "Scheduled.",
"posted": "Marked as posted: it's under Content → Published.",
"unscheduled": "Back in Posts: edit it, then publish or schedule it again.",
}
func redirect(w http.ResponseWriter, r *http.Request, path, msg string) {
+1 -1
View File
@@ -100,7 +100,7 @@ func TestEveryPageRenders(t *testing.T) {
"/settings/ai", "/settings/accounts", "/settings/core", "/static/app.css", "/favicon.ico", "/static/favicon.png", "/static/logo.png", "/static/apple-touch-icon.png", "/search", "/crm", "/search?q=rival", "/search?q=nothing+here", "/static/htmx.min.js", "/healthz",
"/content", "/content/1", "/content/1?dismissed=1", "/posts", "/posts?msg=drafted",
"/content/scheduled", "/content/published",
"/prospects", "/prospects?status=accepted", "/prospects?status=rejected", "/prospects/new", "/prospects/suppressed", "/outreach", "/outreach?tab=queued", "/outreach?tab=sent", "/outreach?tab=replied", "/outreach?tab=failed", "/settings/email", "/settings/tracking", "/settings/search", "/seo", "/seo/check", "/seo/report", "/seo/audit", "/seo/changes", "/seo/keywords", "/seo/briefs", "/seo/engines", "/metrics", "/metrics/customers", "/metrics/customers?show=all", "/metrics/spend", "/metrics/clv", "/metrics/clv?view=profit", "/metrics/publish", "/sites", "/sites?site=0", "/sites/previews", "/sites/pages", "/sites/publishing",
"/prospects", "/prospects?status=accepted", "/prospects?status=rejected", "/prospects/new", "/prospects/suppressed", "/outreach", "/outreach?tab=queued", "/outreach?tab=sent", "/outreach?tab=replied", "/outreach?tab=failed", "/settings/email", "/settings/tracking", "/settings/search", "/seo", "/seo/check", "/seo/report", "/seo/audit", "/seo/changes", "/seo/keywords", "/seo/briefs", "/seo/engines", "/metrics", "/metrics/customers", "/metrics/customers?show=all", "/metrics/spend", "/metrics/clv", "/metrics/clv?view=profit", "/metrics/publish", "/sites", "/sites?site=0", "/sites/previews", "/sites/pages", "/sites/publishing", "/sites/forms", "/sites/new", "/settings/backups",
"/signals", "/signals?period=30d&channel=email", "/signals/new", "/settings/sources"} {
rec := do(h, http.MethodGet, path, nil, nil)
if rec.Code != http.StatusOK {
+48 -3
View File
@@ -180,6 +180,10 @@ var accountFields = []secretField{
"Create an app (it needs a LinkedIn company page), add the products Share on LinkedIn and Sign In with LinkedIn using OpenID Connect, then open the Auth tab.", linkedInApps},
{"LinkedIn", secrets.LinkedInClientSecret, "Client secret",
"On the same Auth tab, under the client ID.", linkedInApps},
{"LinkedIn page", secrets.LinkedInPageClientID, "Client ID",
"A second LinkedIn app, linked to the company page, with the Community Management API approved by LinkedIn (it must be the app's only product). Its Auth tab has the ID.", linkedInApps},
{"LinkedIn page", secrets.LinkedInPageClientSecret, "Client secret",
"On the same Auth tab, under the client ID.", linkedInApps},
{"Reddit", secrets.RedditClientID, "Client ID",
"Create app → choose \"web app\" and enter the redirect URI below. The client ID is the string under the app's name.", redditApps},
{"Reddit", secrets.RedditClientSecret, "Client secret",
@@ -228,7 +232,8 @@ type connectInfo struct {
Account string
At time.Time
Note string
Expiry *Expiry // when the sign-in runs out, for LinkedIn
Expiry *Expiry // when the sign-in runs out, for LinkedIn
Page *pageSetup // the company page's choices, for the LinkedIn page
}
func (s *Server) accountsPage(w http.ResponseWriter, r *http.Request) {
@@ -239,7 +244,7 @@ func (s *Server) accountsPage(w http.ResponseWriter, r *http.Request) {
// networks are the cards on the Social accounts tab, as things stand.
func (s *Server) networks() []network {
names := []string{secrets.XAccessToken, secrets.LinkedInAccessToken, secrets.RedditAccessToken}
names := []string{secrets.XAccessToken, secrets.LinkedInAccessToken, secrets.LinkedInPageAccessToken, secrets.RedditAccessToken}
for _, f := range accountFields {
names = append(names, f.Name)
}
@@ -259,7 +264,7 @@ func (s *Server) networks() []network {
}
}
var nets []network
for _, name := range []string{"X", "LinkedIn", "Reddit", "YouTube"} {
for _, name := range []string{"X", "LinkedIn", liPageNetwork, "Reddit", "YouTube"} {
n := network{Name: name, Set: set}
for _, f := range accountFields {
if f.Group == name {
@@ -274,6 +279,12 @@ func (s *Server) networks() []network {
n.Connect = connect("linkedin", secrets.LinkedInAccessToken, "In your LinkedIn app's Auth settings, add this redirect URL:", "",
set[secrets.LinkedInClientID] && set[secrets.LinkedInClientSecret], func(string) string { return "" })
n.Connect.Expiry = s.linkedInExpiry()
case liPageNetwork:
n.Connect = connect(liPageProvider, secrets.LinkedInPageAccessToken, "In the page app's Auth settings, add this redirect URL:",
"Posts can then go out as the company page instead of you; each LinkedIn draft says which.",
set[secrets.LinkedInPageClientID] && set[secrets.LinkedInPageClientSecret], func(a string) string { return a })
n.Connect.Expiry = s.linkedInPageExpiry()
n.Connect.Page = s.pageSetup()
case "Reddit":
n.Connect = connect("reddit", secrets.RedditAccessToken, "At reddit.com/prefs/apps, create a web app with this redirect URI:",
"Reddit's API terms need approval for commercial use: Supermarket is meant for a few hand-approved posts, not volume.",
@@ -351,6 +362,13 @@ func (s *Server) oauthStart(w http.ResponseWriter, r *http.Request) {
return
}
authURL, p, err = oauth.LinkedInStart(id, s.callbackURL("linkedin"))
case liPageProvider:
id := s.Secrets.Get(secrets.LinkedInPageClientID)
if id == "" || !s.Secrets.Has(secrets.LinkedInPageClientSecret) {
http.Error(w, "Save the LinkedIn page app's client ID and secret first.", http.StatusBadRequest)
return
}
authURL, p, err = oauth.LinkedInStartScopes(liPageProvider, id, s.callbackURL(liPageProvider), s.liPageScopes())
case "reddit":
id := s.Secrets.Get(secrets.RedditClientID)
if id == "" || !s.Secrets.Has(secrets.RedditClientSecret) {
@@ -489,6 +507,33 @@ func (s *Server) oauthCallback(w http.ResponseWriter, r *http.Request) {
s.Log.Error("saving connection", "err", err)
}
redirect(w, r, "/settings/accounts", "li-connected")
case liPageProvider:
res, err := oauth.LinkedInExchange(ctx, s.Secrets.Get(secrets.LinkedInPageClientID), s.Secrets.Get(secrets.LinkedInPageClientSecret), code, p)
if err != nil {
fail(err.Error())
return
}
if err := s.Secrets.Set(map[string]string{secrets.LinkedInPageAccessToken: res.AccessToken}); err != nil {
fail("Signed in, but couldn't save the token: " + err.Error())
return
}
life := res.ExpiresIn
if life <= 0 {
life = linkedInTokenLife
}
now := time.Now()
_, listErr := s.pageOrgs(ctx, res.AccessToken)
if listErr != nil {
s.Log.Warn("linkedin page: couldn't list the pages", "err", listErr)
}
account := ""
if o := s.liPage(); o != nil {
account = o.Name
}
if err := s.saveConnection(liPageProvider, Connection{Account: account, At: now, Expires: now.Add(life)}); err != nil {
s.Log.Error("saving connection", "err", err)
}
redirect(w, r, "/settings/accounts", "li-page-connected")
case "reddit":
res, err := oauth.RedditExchange(ctx, s.Secrets.Get(secrets.RedditClientID), s.Secrets.Get(secrets.RedditClientSecret),
s.redditUserAgent(), code, p)
+94
View File
@@ -0,0 +1,94 @@
package web
import (
"context"
"errors"
"net/http"
"net/url"
"strconv"
"strings"
"testing"
linkedinapi "supermarket/internal/api/linkedin"
"supermarket/internal/content"
"supermarket/internal/secrets"
)
func TestLinkedInPageSettings(t *testing.T) {
s, h := newTestServer(t, nil)
body := do(h, http.MethodGet, "/settings/accounts", nil, nil).Body.String()
if !strings.Contains(body, `id="network-LinkedIn page"`) || !strings.Contains(body, "/auth/linkedin-page/callback") ||
!strings.Contains(body, "Once connected, choose the page here") || !strings.Contains(body, `value="w_organization_social r_organization_admin"`) {
t.Errorf("card: %s", body)
}
// Without the app's keys, the sign-in can't start.
if rec := postForm(h, "/auth/linkedin-page/start", nil); rec.Code != http.StatusBadRequest {
t.Errorf("start without keys: %d", rec.Code)
}
s.Secrets.Set(map[string]string{secrets.LinkedInPageClientID: "cid", secrets.LinkedInPageClientSecret: "sec"})
postForm(h, "/settings/accounts/linkedin-page", url.Values{"scopes": {"w_organization_social rw_organization_admin"}})
rec := postForm(h, "/auth/linkedin-page/start", nil)
loc, _ := url.Parse(rec.Header().Get("Location"))
if rec.Code != http.StatusSeeOther || loc.Query().Get("scope") != "w_organization_social rw_organization_admin" || loc.Query().Get("client_id") != "cid" {
t.Errorf("start: %d %s", rec.Code, loc)
}
// Signed in (the callback's work), with two pages listed.
s.Secrets.Set(map[string]string{secrets.LinkedInPageAccessToken: "page-tok"})
s.DB.PutJSON(liPageOrgsKey, []linkedinapi.Org{{URN: "urn:li:organization:111", ID: "111", Name: "Federated Computer", Role: "ADMINISTRATOR"},
{URN: "urn:li:organization:222", ID: "222", Name: "Other", Role: "CONTENT_ADMIN"}})
body = do(h, http.MethodGet, "/settings/accounts", nil, nil).Body.String()
if !strings.Contains(body, `value="urn:li:organization:111"`) || !strings.Contains(body, "Federated Computer") {
t.Errorf("pages: %s", body)
}
postForm(h, "/settings/accounts/linkedin-page", url.Values{"org": {"urn:li:organization:111"}, "default": {"page"}})
if o := s.liPage(); o == nil || o.Name != "Federated Computer" {
t.Errorf("chosen: %+v", o)
}
var def string
s.DB.GetJSON(content.LinkedInDefaultKey, &def)
if def != content.AsPage {
t.Errorf("default: %q", def)
}
// Typed in by hand, from the page's admin address.
postForm(h, "/settings/accounts/linkedin-page", url.Values{"org_manual": {"https://www.linkedin.com/company/87654321/admin/"}})
if o := s.liPage(); o == nil || o.URN != "urn:li:organization:87654321" {
t.Errorf("manual: %+v", o)
}
if body := postForm(h, "/settings/accounts/linkedin-page", url.Values{"org_manual": {"federated"}}).Body.String(); !strings.Contains(body, "isn&#39;t a company page&#39;s number") {
t.Errorf("bad manual: %s", body)
}
// A LinkedIn draft offers the page, and the choice is saved.
postForm(h, "/settings/accounts/linkedin-page", url.Values{"org": {"urn:li:organization:111"}, "default": {"page"}})
if _, err := content.CreateDrafts(s.DB, []content.Draft{{Channel: content.ChannelLinkedIn, Content: "Hello"}}); err != nil {
t.Fatal(err)
}
ds, _ := content.ListDrafts(s.DB, 1, content.StatusDraft)
body = do(h, http.MethodGet, "/posts", nil, nil).Body.String()
if !strings.Contains(body, `name="linkedin_as"`) || !strings.Contains(body, `<option value="page" selected>Federated Computer</option>`) {
t.Errorf("posts: %s", body)
}
postForm(h, "/drafts/"+strconv.FormatInt(ds[0].ID, 10)+"/save", url.Values{"content": {"Hello"}, "linkedin_as": {""}})
if dr, _ := content.GetDraft(s.DB, ds[0].ID); dr.LinkedInAs != "" {
t.Errorf("switched: %q", dr.LinkedInAs)
}
// The page counts as LinkedIn being connected, even without the member sign-in.
if !s.connected()[content.ChannelLinkedIn] {
t.Error("LinkedIn not connected with only the page")
}
}
func TestLinkedInPublisherChoosesTheAuthor(t *testing.T) {
ctx := context.Background()
if _, err := (linkedInPublisher{}).Publish(ctx, content.Post{Text: "x", AsPage: true}); !errors.Is(err, errNoPage) {
t.Errorf("no page: %v", err)
}
if _, err := (linkedInPublisher{page: linkedinapi.New("t", "urn:li:organization:1")}).Publish(ctx, content.Post{Text: "x"}); !errors.Is(err, errNoMe) {
t.Errorf("no member: %v", err)
}
expired := errors.New("expired")
if _, err := (linkedInPublisher{pageErr: expired}).Publish(ctx, content.Post{Text: "x", AsPage: true}); !errors.Is(err, expired) {
t.Errorf("expired page: %v", err)
}
}
+44
View File
@@ -100,6 +100,17 @@ func (s *Server) renderSites(w http.ResponseWriter, r *http.Request, errMsg stri
cancel()
}
wc.Release()
if ts := sites.ReadTheme(wc.Dir); ts.Has {
data["Theme"] = ts
var pr formsPR
if ok, _ := s.DB.GetJSON(themePRKey(cur.Repo), &pr); ok {
data["ThemePR"] = pr
}
data["Kinds"] = []string{"home", "about", "contact"}
if p, _ := profile.Load(s.DB); p != nil {
data["Products"] = p.Products
}
}
if err != nil {
errMsg = "Couldn't read the working copy: " + err.Error()
} else {
@@ -391,3 +402,36 @@ func (n noListing) Open(name string) (http.File, error) {
}
return f, nil
}
func themePRKey(repo string) string { return "sites:theme-pr:" + repo }
// sitesThemeUpdate opens the pull request that brings a site's copy of the
// theme up to date.
func (s *Server) sitesThemeUpdate(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
_, cur := s.currentSite(r)
if cur == nil || cur.Repo == "" {
s.renderSites(w, r, "Choose a website with a Hugo repository.")
return
}
if s.gitea() == nil {
s.renderSites(w, r, "Save a Gitea token under Settings → Search engines first.")
return
}
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Minute)
defer cancel()
pull, d, err := sites.UpdateTheme(ctx, s.applier(seoSite{Index: cur.Index, URL: cur.URL}))
if err != nil {
s.renderSites(w, r, err.Error())
return
}
pr := formsPR{Number: pull.Number, URL: pull.HTMLURL, At: time.Now(), State: "open", Capture: strconv.Itoa(d.To)}
if err := s.DB.PutJSON(themePRKey(cur.Repo), pr); err != nil {
s.serverError(w, err)
return
}
http.Redirect(w, r, "/sites?site="+strconv.Itoa(cur.Index), http.StatusSeeOther)
}
+92
View File
@@ -519,3 +519,95 @@ func TestSitesPublishing(t *testing.T) {
t.Errorf("page: %s", body)
}
}
func TestLeadForms(t *testing.T) {
if hugorepo.HugoVersion(context.Background()) == "" {
t.Skip("no hugo")
}
partial := "{{/*\n A lead form.\n*/}}\n<div class=\"lead\"><form class=\"lead-form\" action=\"{{ site.Params.leads.action }}\"></form></div>\n" +
"<script>\n (function () {\n var form = document.currentScript.previousElementSibling.querySelector('form');\n" +
" form.addEventListener('submit', function () { var data = new FormData(form);\n" +
" fetch(form.action, { method: 'POST', body: data, headers: { Accept: 'application/json' } }); });\n })();\n</script>\n"
clone := hugotest.Site(t, map[string]string{
"hugo.toml": "baseURL = 'https://site.example/'\ntitle = 'Site'\ndisableKinds = ['taxonomy', 'term', 'RSS', 'sitemap']\n\n[params.leads]\n action = \"\"\n email = \"info@site.example\"\n",
"layouts/partials/render-sections.html": `{{ range .Params.sections }}{{ partial (printf "sections/%s.html" .type) . }}{{ end }}`,
"layouts/partials/sections/form.html": partial,
"layouts/_default/single.html": `{{ define "main" }}<h1>{{ .Title }}</h1>{{ partial "render-sections.html" . }}{{ end }}`,
"content/churches.md": "---\ntitle: Churches\nsections:\n - type: form\n subject: Church\n---\n",
})
var opened []map[string]string
g := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.URL.Path == "/api/v1/repos/Us/site":
fmt.Fprintf(w, `{"full_name":"Us/site","default_branch":"main","clone_url":%q,"permissions":{"push":true}}`, clone)
case r.URL.Path == "/api/v1/repos/Us/site/pulls" && r.Method == http.MethodPost:
var body map[string]string
json.NewDecoder(r.Body).Decode(&body)
opened = append(opened, body)
fmt.Fprint(w, `{"number":9,"state":"open","html_url":"https://gitea.example/pulls/9"}`)
case r.URL.Path == "/api/v1/repos/Us/site/pulls/9":
fmt.Fprint(w, `{"number":9,"state":"open"}`)
default:
http.NotFound(w, r)
}
}))
defer g.Close()
crm := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodOptions {
t.Errorf("the test sent a %s", r.Method)
}
w.Header().Set("Access-Control-Allow-Origin", "*")
}))
defer crm.Close()
captureClient = crm.Client
defer func() { captureClient = sites.TestClient }()
capture := crm.URL + "/api/v1/LeadCapture/key123"
s, h := newTestServer(t, nil)
profile.Save(s.DB, &profile.Profile{Name: "Us", Websites: []profile.Website{{URL: "https://site.example", Repo: "Us/site"}}})
postForm(h, "/settings/search", url.Values{"gitea_url": {g.URL}, secrets.GiteaToken: {"tok"}})
postForm(h, "/sites/sync", url.Values{"site": {"0"}})
body := do(h, http.MethodGet, "/sites/forms", nil, nil).Body.String()
if !strings.Contains(body, "The forms open an email") || !strings.Contains(body, "Pages with a form: /churches/") ||
!strings.Contains(body, "First Name, Last Name, Email, Account Name, Phone, Description") {
t.Errorf("before: %s", body)
}
if body := postForm(h, "/sites/forms/save", url.Values{"site": {"0"}, "capture": {"https://crm.example/api/v1/Lead"}}).Body.String(); !strings.Contains(body, "isn&#39;t a Lead Capture address") {
t.Errorf("bad address: %s", body)
}
if body := postForm(h, "/sites/forms/save", url.Values{"site": {"0"}, "capture": {capture}}).Body.String(); !strings.Contains(body, "Saved and tested") {
t.Errorf("save: %s", body)
}
if rec := postForm(h, "/sites/forms/connect", url.Values{"site": {"0"}}); rec.Code != http.StatusSeeOther {
t.Fatalf("connect: %d %s", rec.Code, rec.Body.String())
}
if len(opened) != 1 || opened[0]["head"] != "supermarket/lead-forms" || !strings.Contains(opened[0]["body"], "/churches/ loads the script and posts to the Lead Capture") {
t.Fatalf("pull request: %v", opened)
}
show := func(path string) string {
out, err := exec.Command("git", "--git-dir", strings.TrimPrefix(clone, "file://"), "show", "supermarket/lead-forms:"+path).CombinedOutput()
if err != nil {
t.Fatalf("%s: %s", path, out)
}
return string(out)
}
if cfg := show("hugo.toml"); !strings.Contains(cfg, " action = \""+capture+"\"\n email = \"info@site.example\"") {
t.Errorf("hugo.toml: %s", cfg)
}
if p := show("layouts/partials/sections/form.html"); !strings.Contains(p, "window.leadPost(form, data)") || !strings.Contains(p, "supermarket-leads.js") {
t.Errorf("partial: %s", p)
}
if js := show("static/js/supermarket-leads.js"); !strings.Contains(js, "window.leadPost = function") {
t.Errorf("script: %s", js)
}
if body := do(h, http.MethodGet, "/sites/forms", nil, nil).Body.String(); !strings.Contains(body, "A pull request is open") || !strings.Contains(body, "https://gitea.example/pulls/9") {
t.Errorf("after: %s", body)
}
// Once merged and read again, the page says they're connected.
exec.Command("git", "--git-dir", strings.TrimPrefix(clone, "file://"), "update-ref", "refs/heads/main", "refs/heads/supermarket/lead-forms").Run()
postForm(h, "/sites/sync", url.Values{"site": {"0"}})
if body := do(h, http.MethodGet, "/sites/forms", nil, nil).Body.String(); !strings.Contains(body, "Connected: the forms on https://site.example send their answers to EspoCRM") {
t.Errorf("connected: %s", body)
}
}
+12
View File
@@ -452,3 +452,15 @@ details.inline-details > summary::-webkit-details-marker { display: none; }
details.inline-details[open] { display: block; white-space: normal; margin: 0.4rem 0; }
details.inline-details form { margin-top: 0.5rem; min-width: 18rem; }
.button.small { padding: 0.28rem 0.75rem; font-size: 0.82rem; }
input[type="color"] { height: 2.6rem; padding: 0.25rem; cursor: pointer; }
/* Collapsible module menus in the sidebar (app.js shows the toggles). */
.nav-row { display: flex; align-items: center; gap: 2px; }
.nav-row > a { flex: 1; min-width: 0; }
.nav .nav-toggle { background: transparent; border: 0; box-shadow: none; color: hsl(var(--muted-foreground)); padding: 0.3rem 0.35rem; min-height: 0; border-radius: var(--radius); cursor: pointer; line-height: 0; }
.nav .nav-toggle:hover { background: hsl(var(--accent) / 0.6); color: hsl(var(--foreground)); transform: none; }
.nav .nav-toggle .icon { width: 1rem; height: 1rem; transition: transform var(--fast); }
.nav-row.collapsed .nav-toggle .icon { transform: rotate(-90deg); }
.nav-sum { margin-left: auto; }
.nav-row:not(.collapsed) .nav-sum { display: none; }
.nav .nav-toggle:active { transform: none; }
+33
View File
@@ -137,4 +137,37 @@
});
document.addEventListener("DOMContentLoaded", syncProvider);
// Sidebar: each module's pages fold under a toggle. The module you're in
// is always open; the others stay as you last left them (closed at
// first). A folded module shows the sum of its pages' counts.
(function () {
var KEY = "supermarket.nav";
var state = {};
try { state = JSON.parse(localStorage.getItem(KEY)) || {}; } catch (e) {}
function set(sub, btn, open) {
sub.hidden = !open;
btn.setAttribute("aria-expanded", open ? "true" : "false");
btn.closest(".nav-row").classList.toggle("collapsed", !open);
}
document.querySelectorAll(".subnav[data-subnav]").forEach(function (sub) {
var btn = document.querySelector('.nav-toggle[aria-controls="' + sub.id + '"]');
if (!btn) return;
btn.hidden = false;
var sum = 0;
sub.querySelectorAll(".count-badge").forEach(function (b) { sum += parseInt(b.textContent, 10) || 0; });
var total = btn.closest(".nav-row").querySelector(".nav-sum");
if (total && sum > 0) {
total.textContent = sum;
total.title = sum + " waiting";
total.hidden = false;
}
set(sub, btn, sub.hasAttribute("data-current") || state[sub.dataset.subnav] === true);
btn.addEventListener("click", function () {
var open = sub.hidden;
set(sub, btn, open);
state[sub.dataset.subnav] = open;
try { localStorage.setItem(KEY, JSON.stringify(state)); } catch (e) {}
});
});
})();
})();
+28
View File
@@ -43,6 +43,34 @@
<button type="submit" {{if not .Ready}}disabled title="Save the client ID{{if ne .Provider "x"}} and secret{{end}} first"{{end}}>{{if .Signed}}Reconnect{{else}}Connect{{end}} {{$name}}</button>
</form>
</div>
{{with .Page}}{{$pg := .}}
<form method="post" action="/settings/accounts/linkedin-page" class="signin">
<h3>The company page</h3>
{{if .Signed}}
{{if .Orgs}}
<fieldset><legend>Post as</legend>
{{range .Orgs}}<label class="check"><input type="radio" name="org" value="{{.URN}}" {{if and $pg.Chosen (eq $pg.Chosen.URN .URN)}}checked{{end}}> {{.Name}}{{with .Vanity}} <span class="muted small">linkedin.com/company/{{.}}</span>{{end}} <span class="badge">{{.Role}}</span></label>{{end}}
</fieldset>
{{else}}
{{with .Note}}<p class="warn-text">Couldn't list your pages: {{.}}</p>{{end}}
<label>The page's number <span class="muted">(from its admin view: linkedin.com/company/&lt;number&gt;/admin)</span>
<input name="org_manual" value="{{with $pg.Chosen}}{{.ID}}{{end}}" placeholder="12345678"></label>
{{end}}
{{with .Chosen}}<p class="small">Posting as <strong>{{.Name}}</strong>.</p>{{end}}
{{else}}<p class="help">Once connected, choose the page here.</p>{{end}}
<fieldset><legend>New LinkedIn drafts post as</legend>
<label class="check"><input type="radio" name="default" value="" {{if ne .Default "page"}}checked{{end}}> You</label>
<label class="check"><input type="radio" name="default" value="page" {{if eq .Default "page"}}checked{{end}}> The company page</label>
<span class="help">Each draft can still be switched before it's published.</span>
</fieldset>
<label>Permissions to ask for <input name="scopes" value="{{.Scopes}}">
<span class="help">As on the approved app's Auth tab: posting as the page (<code>w_organization_social</code>) and reading the pages you manage (<code>r_organization_admin</code> or <code>rw_organization_admin</code>). Reconnect after changing them.</span></label>
<div class="row">
<button type="submit" class="secondary">Save</button>
{{if .Signed}}<button type="submit" class="secondary" name="do" value="refresh">List my pages again</button>{{end}}
</div>
</form>
{{end}}
{{end}}
</section>
{{end}}
+51
View File
@@ -0,0 +1,51 @@
{{define "content"}}{{template "settings-start" .}}{{with .Data}}{{$d := .}}
<h2>Backups</h2>
<p class="lede">Copies of Supermarket's database: your profile, inventory, signals, prospects, drafts, SEO and metrics. Each one is a single SQLite file. Your keys and tokens aren't in them; they stay in <code>secrets.json</code>.</p>
{{with .Restored}}<p class="ok">Restored from {{.From}} {{ago .At}}{{if .Secrets}}, keys and tokens included{{end}}. What was there before is backed up as {{.Backup}}.</p>{{end}}
{{if .Pending}}
<section class="card warn">
<p><strong>A restore is waiting</strong> for Supermarket to restart. {{if not .CanRestart}}It's applied the next time Supermarket starts (<code>supermarket restart</code>).{{end}}</p>
<form method="post" action="/settings/backups/cancel"><button type="submit" class="secondary small">Cancel the restore</button></form>
</section>
{{end}}
<section class="card">
<p>Supermarket backs up by itself once a day, and before every update that changes the database. The last 7 daily backups are kept, plus one a week for 4 weeks. The ones made before an update, before a restore, and the ones you make are kept until you delete them.</p>
<form method="post" action="/settings/backups/now" class="inline-form">
<label>Note <span class="muted">(optional)</span> <input name="note" placeholder="before the big import" maxlength="60"></label>
<button type="submit" data-busy="Backing up…">Back up now</button>
</form>
<p class="small muted">They're kept in <code>{{.Dir}}</code>, on this computer. From a terminal: <code>supermarket backup [note]</code> and <code>supermarket backups</code>.</p>
</section>
{{if .Backups}}
<p class="small">{{len .Backups}} backup{{if ne (len .Backups) 1}}s{{end}}, {{bytes .Total}} in all. This version of Supermarket is at schema {{.Schema}}.</p>
<div class="table-wrap"><table>
<thead><tr><th>Made</th><th>Why</th><th class="num">Size</th><th class="num">Schema</th><th></th></tr></thead>
<tbody>{{range .Backups}}<tr>
<td>{{.At.Format "2 Jan 2006, 15:04"}}<br><span class="small muted">{{ago .At}}</span></td>
<td>{{if eq .Kind "manual"}}By you{{else if eq .Kind "migration"}}Before an update{{else if eq .Kind "daily"}}Daily{{if not (index $d.Keep .Name)}} <span class="muted">(next to go)</span>{{end}}{{else if eq .Kind "restore"}}Before a restore{{else}}An older copy{{end}}{{with .Note}}<br><span class="small muted">{{.}}</span>{{end}}</td>
<td class="num">{{bytes .Size}}</td>
<td class="num">{{if ge .Schema 0}}{{.Schema}}{{else}}<span class="error-text" title="{{.Err}}">unreadable</span>{{end}}</td>
<td><div class="row-actions">
{{if ge .Schema 0}}{{if le .Schema $d.Schema}}<form method="post" action="/settings/backups/restore" data-confirm="Restore the backup from {{.At.Format "2 Jan 2006, 15:04"}}? Everything since then is replaced (it's backed up first), and Supermarket restarts.">
<input type="hidden" name="name" value="{{.Name}}"><button type="submit" class="secondary small" data-busy="Restoring…">Restore</button></form>{{end}}{{end}}
<a class="button secondary small" href="/settings/backups/file/{{.Name}}" download>Download</a>
<form method="post" action="/settings/backups/delete" data-confirm="Delete the backup from {{.At.Format "2 Jan 2006, 15:04"}}?">
<input type="hidden" name="name" value="{{.Name}}"><button type="submit" class="secondary small">Delete</button></form>
</div></td>
</tr>{{end}}</tbody>
</table></div>
{{else}}
<section class="card empty"><p>No backups yet. The first daily one is made when Supermarket starts.</p></section>
{{end}}
<section class="card">
<h3>Restore from a file</h3>
<p class="help">A backup downloaded from here, on this computer or another. It's checked and added to the list; then restore it from there. For a backup made with <code>supermarket backup --with-secrets</code> (keys and tokens included), use <code>supermarket restore &lt;file&gt;</code> in a terminal.</p>
<form method="post" action="/settings/backups/upload" enctype="multipart/form-data" class="inline-form">
<input type="file" name="file" accept=".db,application/vnd.sqlite3" required>
<button type="submit" class="secondary" data-busy="Uploading…">Upload</button>
</form>
</section>
{{end}}{{template "settings-end"}}{{end}}
+6 -1
View File
@@ -1,4 +1,4 @@
{{define "content"}}{{with .Data}}{{$conn := .Connected}}{{$now := .Now}}{{$zone := .Zone}}{{$reddit := .Reddit}}
{{define "content"}}{{with .Data}}{{$conn := .Connected}}{{$page := .Page}}{{$now := .Now}}{{$zone := .Zone}}{{$reddit := .Reddit}}
<h1>Posts</h1>
<p class="lede">Everything waiting for your approval. Nothing is published until you say so: publish a draft now, or schedule it.
{{if .Tagged}}Links to your own sites get UTM tags when published.{{end}}</p>
@@ -43,6 +43,11 @@
data-count="{{.Channel}}" data-limit="{{.Limit}}" data-reserve="{{if eq .Channel "x"}}{{xreserve .SourceURL}}{{else}}0{{end}}"
aria-describedby="count-{{.ID}}" id="text-{{.ID}}">{{.Content}}</textarea>
{{if eq .Channel "reddit"}}{{if .SourceURL}}<p class="help">The source link is added at the end as “Source: …”.</p>{{end}}{{end}}
{{if and (eq .Channel "linkedin") $page}}
<label class="small inline-label">Post as
<select name="linkedin_as"><option value="">You</option><option value="page" {{if eq .LinkedInAs "page"}}selected{{end}}>{{$page.Name}}</option></select>
</label>
{{else if eq .LinkedInAs "page"}}<p class="warn-text small">This draft posts as the company page, which isn't connected: set it up under <a href="/settings/accounts">Settings → Social accounts</a>.</p>{{end}}
<p class="count{{if .TooLong}} over{{end}}" id="count-{{.ID}}">{{.Length}} / {{.Limit}}{{if and (eq .Channel "x") .SourceURL}} including the link{{end}}</p>
<div class="actions">
<button type="submit" name="action" value="publish" formaction="/drafts/{{.ID}}/publish"
+15 -6
View File
@@ -29,9 +29,12 @@
{{$nav := .Nav}}{{$inbox := .Inbox}}
{{range .Modules}}
{{if .Link}}
<a href="{{.Link}}" {{if eq $nav .ID}}aria-current="page"{{end}} class="{{if hasPrefix $nav .ID}}open{{end}}">{{template "icon" .ID}}<span>{{.Name}}</span></a>
<div class="nav-row">
<a href="{{.Link}}" {{if eq $nav .ID}}aria-current="page"{{end}} class="{{if hasPrefix $nav .ID}}open{{end}}">{{template "icon" .ID}}<span>{{.Name}}</span><span class="count-badge nav-sum" hidden></span></a>
<button type="button" class="nav-toggle" aria-controls="subnav-{{.ID}}" aria-expanded="true" aria-label="Show or hide {{.Name}}'s pages" hidden>{{template "icon" "chevron"}}</button>
</div>
{{if eq .ID "content"}}
<div class="subnav">
<div class="subnav" id="subnav-content" data-subnav="content"{{if hasPrefix $nav "content"}} data-current{{end}}>
<a href="/posts" {{if eq $nav "content/posts"}}aria-current="page"{{end}}>Posts{{if $inbox}} <span class="count-badge" title="{{$inbox}} waiting for review">{{$inbox}}</span>{{end}}</a>
<a href="/content" {{if eq $nav "content/sources"}}aria-current="page"{{end}}>Sources</a>
<a href="/content/scheduled" {{if eq $nav "content/scheduled"}}aria-current="page"{{end}}>Scheduled</a>
@@ -39,7 +42,7 @@
</div>
{{end}}
{{if eq .ID "seo"}}
<div class="subnav">
<div class="subnav" id="subnav-seo" data-subnav="seo"{{if hasPrefix $nav "seo"}} data-current{{end}}>
<a href="/seo/check" {{if eq $nav "seo/check"}}aria-current="page"{{end}}>Morning check</a>
<a href="/seo/report" {{if eq $nav "seo/report"}}aria-current="page"{{end}}>Monday report</a>
<a href="/seo" {{if eq $nav "seo/ranks"}}aria-current="page"{{end}}>What ranks</a>
@@ -51,7 +54,7 @@
</div>
{{end}}
{{if eq .ID "metrics"}}
<div class="subnav">
<div class="subnav" id="subnav-metrics" data-subnav="metrics"{{if hasPrefix $nav "metrics"}} data-current{{end}}>
<a href="/metrics" {{if eq $nav "metrics/overview"}}aria-current="page"{{end}}>MRR and NRR</a>
<a href="/metrics/spend" {{if eq $nav "metrics/spend"}}aria-current="page"{{end}}>Spend and CAC</a>
<a href="/metrics/clv" {{if eq $nav "metrics/clv"}}aria-current="page"{{end}}>CLV and cohorts</a>
@@ -60,15 +63,17 @@
</div>
{{end}}
{{if eq .ID "sites"}}
<div class="subnav">
<div class="subnav" id="subnav-sites" data-subnav="sites"{{if hasPrefix $nav "sites"}} data-current{{end}}>
<a href="/sites" {{if eq $nav "sites/site"}}aria-current="page"{{end}}>Sections and pages</a>
<a href="/sites/pages" {{if hasPrefix $nav "sites/pages"}}aria-current="page"{{end}}>New pages</a>
<a href="/sites/previews" {{if eq $nav "sites/previews"}}aria-current="page"{{end}}>Previews</a>
<a href="/sites/publishing" {{if eq $nav "sites/publishing"}}aria-current="page"{{end}}>Publishing</a>
<a href="/sites/forms" {{if eq $nav "sites/forms"}}aria-current="page"{{end}}>Lead forms</a>
<a href="/sites/new" {{if eq $nav "sites/new"}}aria-current="page"{{end}}>New site</a>
</div>
{{end}}
{{if eq .ID "prospects"}}
<div class="subnav">
<div class="subnav" id="subnav-prospects" data-subnav="prospects"{{if hasPrefix $nav "prospects"}} data-current{{end}}>
<a href="/signals" {{if eq $nav "prospects/signals"}}aria-current="page"{{end}}>Signals</a>
<a href="/prospects" {{if eq $nav "prospects/review"}}aria-current="page"{{end}}>Review{{with $.NewProspects}} <span class="count-badge" title="{{.}} waiting for review">{{.}}</span>{{end}}</a>
<a href="/outreach" {{if eq $nav "prospects/outreach"}}aria-current="page"{{end}}>Outreach{{with $.Drafts}} <span class="count-badge" title="{{.}} drafts to review">{{.}}</span>{{end}}</a>
@@ -127,6 +132,8 @@
<a href="/settings/search" {{if eq .Nav "settings/search"}}aria-current="page"{{end}}>{{template "icon" "seo"}}Search engines</a>
<div class="nav-label">AI</div>
<a href="/settings/ai" {{if eq .Nav "settings/ai"}}aria-current="page"{{end}}>{{template "icon" "ai"}}AI</a>
<div class="nav-label">Data</div>
<a href="/settings/backups" {{if eq .Nav "settings/backups"}}aria-current="page"{{end}}>{{template "icon" "backups"}}Backups</a>
</nav>
<div class="settings-body">
{{end}}
@@ -174,6 +181,8 @@
{{- else if eq . "accounts"}}<circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><path d="m8.59 13.51 6.83 3.98"/><path d="m15.41 6.51-6.82 3.98"/>
{{- else if eq . "ai"}}<path d="M12 8V4H8"/><rect width="16" height="12" x="4" y="8" rx="2"/><path d="M2 14h2"/><path d="M20 14h2"/><path d="M15 13v2"/><path d="M9 13v2"/>
{{- else if eq . "core"}}<path d="M6.3 20.3a2.4 2.4 0 0 0 3.4 0L12 18l-6-6-2.3 2.3a2.4 2.4 0 0 0 0 3.4Z"/><path d="m2 22 3-3"/><path d="M7.5 13.5 10 11"/><path d="M10.5 16.5 13 14"/><path d="m18 3-4 4h6l-4 4"/>
{{- else if eq . "backups"}}<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/><path d="M12 7v5l4 2"/>
{{- else if eq . "chevron"}}<path d="m6 9 6 6 6-6"/>
{{- else if eq . "menu"}}<path d="M4 12h16"/><path d="M4 6h16"/><path d="M4 18h16"/>
{{- end}}</svg>{{end}}
+64
View File
@@ -0,0 +1,64 @@
{{define "content"}}{{with .Data}}{{$d := .}}
<div class="heading"><h1>Lead forms</h1></div>
<p class="lede">Your website's forms ("send me a cost comparison", "become a partner") send each answer to EspoCRM as a new Lead, using EspoCRM's own Lead Capture: Supermarket only runs on this computer, so the forms can't post to it. The Lead's description says which form, which page, and which campaign brought the visitor; Plausible counts the forms sent per buying signal.</p>
{{if not .Sites}}
<section class="card empty"><p>Add your website and its Hugo repository under <a href="/settings/profile">Settings → Profile</a> first.</p></section>
{{else}}
{{if gt (len .Sites) 1}}<nav class="tabs">{{range .Sites}}<a href="/sites/forms?site={{.Index}}" {{if and $d.Current (eq .Index $d.Current.Index)}}aria-current="page"{{end}}>{{.URL}}</a>{{end}}</nav>{{end}}
{{with .Current}}{{$cur := .}}
{{if .Err}}<section class="card"><p class="warn-text">{{.URL}}: {{.Err}}.</p></section>{{else}}
{{if not $d.HasSynced}}
<section class="card empty"><p>Read {{.Repo}} under <a href="/sites?site={{.Index}}">Sections and pages</a> first.</p></section>
{{else}}{{with $d.State}}
<section class="card">
<h2>Now</h2>
{{if $d.Connected}}<p class="ok">Connected: the forms on {{$cur.URL}} send their answers to EspoCRM.</p>
{{else if .Action}}<p>The forms post to <code>{{.Action}}</code>{{if not .Patched}}, without Supermarket's mapping{{end}}.</p>
{{else}}<p>The forms open an email with the answers filled in: they don't post anywhere yet.</p>{{end}}
{{with .Pages}}<p class="small">Pages with a form: {{join . ", "}}</p>{{else}}<p class="small muted">No page has a form section yet. The page builder can add one where the site has the <code>form</code> section type.</p>{{end}}
{{if not .Supported}}<p class="warn-text">This site's form section doesn't post the way Supermarket knows, so it can't be connected automatically.</p>{{end}}
</section>
{{end}}{{end}}
<section class="card">
<h2>1. In EspoCRM</h2>
<ol>
<li>Open {{with $d.CRM}}<a href="{{.}}" target="_blank" rel="noopener noreferrer">EspoCRM</a>{{else}}EspoCRM{{end}} as an administrator: <em>Administration → Lead Capture → Create Lead Capture</em>.</li>
<li>Name it after the site, tick <em>Is Active</em>, and under <em>Payload Fields</em> add: {{join $d.Payload ", "}}.</li>
<li>Optional: a <em>Campaign</em> (for EspoCRM's own campaign statistics), a <em>Target List</em>, a <em>Target Team</em>, and <em>Double Opt-in</em> if people should confirm by email.</li>
<li>Save, and copy the <em>API URL</em> it shows: <code>https://…/api/v1/LeadCapture/…</code>.</li>
</ol>
<p class="small muted">Your site must be allowed to post to the CRM: EspoCRM allows every site by default (<code>leadCaptureAllowOrigin</code> in its <code>data/config.php</code>). The test below checks it.</p>
</section>
<form method="post" action="/sites/forms/save" class="card">
<h2>2. The Lead Capture's address</h2>
<input type="hidden" name="site" value="{{.Index}}">
<label>API URL <input name="capture" value="{{$d.Capture}}" placeholder="{{or $d.CRM "https://espocrm.example.com"}}/api/v1/LeadCapture/…"></label>
<button type="submit" class="secondary" data-busy="Testing…">Save and test</button>
<p class="small muted">The test asks the CRM whether {{.URL}} may post to it, the way a browser would. Nothing is created.</p>
</form>
<form method="post" action="/sites/forms/connect" class="card">
<h2>3. Connect the forms</h2>
<input type="hidden" name="site" value="{{.Index}}">
<p>Opens a pull request on {{.Repo}} that sets the forms' address, adds a small script mapping their fields onto a Lead's (name, email, organization, phone; the rest, the page and the campaign go in the description), and has the form section post through it. Merging publishes it.</p>
{{with $d.PR}}<p>{{if eq .State "merged"}}<span class="ok">Merged.</span> Send a test form on the live site and look for the Lead in EspoCRM.{{else if eq .State "closed"}}The last pull request was closed without merging.{{else}}A pull request is open{{end}} <a href="{{.URL}}" target="_blank" rel="noopener noreferrer">{{.URL}} ↗</a> <span class="small muted">{{ago .At}}</span></p>{{end}}
<button type="submit" data-busy="Opening…" {{if or (not $d.Capture) (not $d.Gitea)}}disabled{{end}}>{{if $d.Connected}}Open it again{{else}}Open the pull request{{end}}</button>
</form>
{{end}}
{{end}}
{{end}}
<h2>Forms sent, by buying signal</h2>
{{if not .Plausible}}<p class="help">Counted from Plausible: save its key under <a href="/settings/tracking">Settings → Website &amp; sales</a>.</p>{{end}}
<p class="small muted">The forms tell Plausible when they're sent (a <code>{{.Goal}}</code> event). Add a <code>{{.Goal}}</code> goal (a custom event) in Plausible, and the daily import counts the ones from visits tagged with a signal as <em>interested</em> on its scorecard.</p>
{{with .Leads}}
<div class="table-wrap"><table class="compact">
<thead><tr><th>Day</th><th>Signal</th><th class="num">Forms</th><th>From</th></tr></thead>
<tbody>{{range .}}<tr><td>{{.At.Format "2 Jan 2006"}}</td><td>{{.Signal}}</td><td class="num">{{.Count}}</td><td class="small">{{.Note}}</td></tr>{{end}}</tbody>
</table></div>
{{else}}<p class="help">None counted yet.</p>{{end}}
{{end}}{{end}}
+39
View File
@@ -0,0 +1,39 @@
{{define "content"}}{{with .Data}}{{$n := .N}}
<div class="heading"><h1>A new site</h1></div>
<p class="lede">Start a website with Supermarket's theme: federated-website's look and sections, in your brand. Supermarket fills an empty Gitea repository with the theme, the settings and a starter home page; then you build its pages here, as pull requests.</p>
<section class="card">
<h2>1. In Gitea</h2>
<p>Create a new, <strong>empty</strong> repository{{with .Gitea}} on <a href="{{.}}/repo/create" target="_blank" rel="noopener noreferrer">{{.}}</a>{{end}}: no README, license or .gitignore. Supermarket makes its first commit.</p>
<p class="small muted">Publishing the site is your Gitea's job, as for your other sites: add the deploy hook that builds it with Hugo on your web server, and point the address below at it.</p>
{{if not .Gitea}}<p class="warn-text">Save a Gitea token under <a href="/settings/search">Settings → Search engines</a> first.</p>{{end}}
</section>
<form method="post" action="/sites/new" class="card">
<h2>2. The site</h2>
<div class="cols">
<label>Repository <input name="repo" value="{{$n.Repo}}" placeholder="owner/name" required></label>
<label>Its address <input name="url" value="{{$n.URL}}" placeholder="https://www.example.com" required></label>
</div>
<div class="cols">
<label>Name <input name="title" value="{{$n.Title}}" placeholder="Acme Widgets" required></label>
<label>Contact email <span class="muted">(where forms go until they're connected to EspoCRM)</span> <input name="email" type="email" value="{{$n.Email}}"></label>
</div>
<label>Tagline <input name="tagline" value="{{$n.Tagline}}" placeholder="What the company does, in a line."></label>
<h3>Brand</h3>
<div class="cols">
<label>Dark <span class="muted">(top bar, hero, closing band)</span> <input type="color" name="dark" value="{{$n.Dark}}"></label>
<label>Primary <span class="muted">(the main button)</span> <input type="color" name="primary" value="{{$n.Primary}}"></label>
<label>Accent <span class="muted">(links, highlights)</span> <input type="color" name="accent" value="{{$n.Accent}}"></label>
</div>
<div class="cols">
<label>Font <select name="font">{{range .Fonts}}<option {{if eq . $n.Font}}selected{{end}}>{{.}}</option>{{end}}</select></label>
<label>Logo <span class="muted">(optional: an image's https:// address, or a path on the site; without one, the name shows)</span> <input name="logo" value="{{$n.Logo}}"></label>
</div>
<div class="actions">
<button type="submit" data-busy="Starting the site…" {{if not .Gitea}}disabled{{end}}>Start the site</button>
</div>
<p class="small muted">It checks the repository is empty and builds the site with Hugo before pushing anything. Colors, font and logo can be changed later in the site's <code>hugo.toml</code>.</p>
</form>
{{end}}{{end}}
+28
View File
@@ -26,6 +26,34 @@
{{end}}
{{with .Catalog}}
{{with $d.Theme}}
<section class="card">
<h2>The theme</h2>
{{if .Outdated}}
<p>This site has Supermarket's theme version {{.Version}}; Supermarket has version {{.Latest}}.</p>
<form method="post" action="/sites/theme/update"><input type="hidden" name="site" value="{{$d.Current.Index}}">
<button type="submit" data-busy="Opening…" {{if not $d.Gitea}}disabled{{end}}>Update the theme</button>
<span class="small muted">Opens a pull request that replaces the site's copy, checked with a build.</span></form>
{{else}}<p class="ok">This site has Supermarket's theme, version {{.Version}}: the latest.</p>{{end}}
{{with .Edited}}<p class="warn-text small">Changed by hand in the site's copy of the theme: {{join . ", "}}. An update replaces them; such changes belong in the site's own <code>layouts/</code> or <code>static/</code>, which win over the theme.</p>{{end}}
{{with $d.ThemePR}}<p class="small">Last update: <a href="{{.URL}}" target="_blank" rel="noopener noreferrer">the pull request ↗</a>, {{ago .At}}.</p>{{end}}
</section>
<section class="card">
<h2>First pages</h2>
<p>This site uses Supermarket's theme. Build its pages: each is written from your profile, opens for you to edit and preview, and goes to the site as a pull request.</p>
<div class="row-actions">
{{range $d.Kinds}}
<form method="post" action="/sites/pages"><input type="hidden" name="site" value="{{$d.Current.Index}}"><input type="hidden" name="kind" value="{{.}}">
<button type="submit" class="secondary" data-busy="Writing…">{{kindLabel .}}</button></form>
{{end}}
{{range $d.Products}}
<form method="post" action="/sites/pages"><input type="hidden" name="site" value="{{$d.Current.Index}}"><input type="hidden" name="kind" value="product"><input type="hidden" name="product" value="{{.Name}}">
<button type="submit" class="secondary" data-busy="Writing…">Product page: {{.Name}}</button></form>
{{end}}
</div>
<p class="small muted">Each uses the AI (a paid call). About and Contact join the top menu; Contact has a lead form: connect it under <a href="/sites/forms?site={{$d.Current.Index}}">Lead forms</a>.</p>
</section>
{{end}}
{{with $d.Commits}}
<h2>Latest on the published branch</h2>
<div class="table-wrap"><table class="compact">