From 9ca09c1ffa1fc9a1f64ec386512097c280bd4b0e Mon Sep 17 00:00:00 2001 From: David Young Date: Sun, 22 Nov 2026 15:27:22 -0700 Subject: [PATCH] Phase 6 part 5, step 2: start a new site MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- PLAN.md | 21 +++ TEST.md | 21 +++ internal/api/gitea/client.go | 1 + internal/hugorepo/repo.go | 52 +++++++ internal/sites/compose.go | 34 ++++- internal/sites/newsite.go | 209 ++++++++++++++++++++++++++ internal/sites/newsite_test.go | 69 +++++++++ internal/sites/pages.go | 17 +++ internal/web/changes.go | 13 +- internal/web/newsite.go | 78 ++++++++++ internal/web/newsite_test.go | 129 ++++++++++++++++ internal/web/server.go | 3 + internal/web/server_test.go | 2 +- internal/web/sites.go | 8 + internal/web/static/app.css | 2 + internal/web/templates/layout.html | 1 + internal/web/templates/sites-new.html | 39 +++++ internal/web/templates/sites.html | 17 +++ 18 files changed, 709 insertions(+), 7 deletions(-) create mode 100644 internal/sites/newsite.go create mode 100644 internal/sites/newsite_test.go create mode 100644 internal/web/newsite.go create mode 100644 internal/web/newsite_test.go create mode 100644 internal/web/templates/sites-new.html diff --git a/PLAN.md b/PLAN.md index cb9fd40..4f8a747 100644 --- a/PLAN.md +++ b/PLAN.md @@ -1418,6 +1418,27 @@ shared theme for new sites (deferred in Phase 5). 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. + **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 `/backups`, named `app---[-].db` diff --git a/TEST.md b/TEST.md index c96584b..580192f 100644 --- a/TEST.md +++ b/TEST.md @@ -655,6 +655,27 @@ Throughout, also notice: - [ ] 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. + ## 9. Search - [ ] Searching for an inventory entry, a fetched item, a post, a prospect diff --git a/internal/api/gitea/client.go b/internal/api/gitea/client.go index 596c139..930bba4 100644 --- a/internal/api/gitea/client.go +++ b/internal/api/gitea/client.go @@ -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"` diff --git a/internal/hugorepo/repo.go b/internal/hugorepo/repo.go index e434fd8..915c73a 100644 --- a/internal/hugorepo/repo.go +++ b/internal/hugorepo/repo.go @@ -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) +} diff --git a/internal/sites/compose.go b/internal/sites/compose.go index ecd8772..a1348ee 100644 --- a/internal/sites/compose.go +++ b/internal/sites/compose.go @@ -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 } diff --git a/internal/sites/newsite.go b/internal/sites/newsite.go new file mode 100644 index 0000000..adabfed --- /dev/null +++ b/internal/sites/newsite.go @@ -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 +} diff --git a/internal/sites/newsite_test.go b/internal/sites/newsite_test.go new file mode 100644 index 0000000..3015c20 --- /dev/null +++ b/internal/sites/newsite_test.go @@ -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), "Acme "Widgets" & Co — Wïdgets, for everyone") { + 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"}, {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) + } + } +} diff --git a/internal/sites/pages.go b/internal/sites/pages.go index b88a688..229ea98 100644 --- a/internal/sites/pages.go +++ b/internal/sites/pages.go @@ -33,6 +33,23 @@ var Kinds = []struct{ ID, Label, Guide string }{ "A side-by-side \" vs \" 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. diff --git a/internal/web/changes.go b/internal/web/changes.go index 64b492f..6d6c083 100644 --- a/internal/web/changes.go +++ b/internal/web/changes.go @@ -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 " + 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 " } func (s *Server) proposer() (*seo.Proposer, error) { diff --git a/internal/web/newsite.go b/internal/web/newsite.go new file mode 100644 index 0000000..843447a --- /dev/null +++ b/internal/web/newsite.go @@ -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) +} diff --git a/internal/web/newsite_test.go b/internal/web/newsite_test.go new file mode 100644 index 0000000..505d800 --- /dev/null +++ b/internal/web/newsite_test.go @@ -0,0 +1,129 @@ +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/profile" + "supermarket/internal/secrets" + "supermarket/internal/sites" +) + +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'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<", "form", "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"]) + } +} diff --git a/internal/web/server.go b/internal/web/server.go index ba6b06f..3accdb5 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -186,6 +186,8 @@ 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("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) @@ -508,6 +510,7 @@ var flashes = map[string]string{ "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.", diff --git a/internal/web/server_test.go b/internal/web/server_test.go index a138fd5..4e5f3c1 100644 --- a/internal/web/server_test.go +++ b/internal/web/server_test.go @@ -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", "/sites/forms", "/settings/backups", + "/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 { diff --git a/internal/web/sites.go b/internal/web/sites.go index 626e799..7e21117 100644 --- a/internal/web/sites.go +++ b/internal/web/sites.go @@ -15,6 +15,7 @@ import ( "supermarket/internal/hugorepo" "supermarket/internal/profile" "supermarket/internal/sites" + "supermarket/internal/theme" ) // siteRepo is a website with a Hugo repository, from the profile. @@ -100,6 +101,13 @@ func (s *Server) renderSites(w http.ResponseWriter, r *http.Request, errMsg stri cancel() } wc.Release() + if raw, rerr := os.ReadFile(filepath.Join(wc.Dir, theme.Dir, "VERSION")); rerr == nil { + data["Theme"] = strings.TrimSpace(string(raw)) + 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 { diff --git a/internal/web/static/app.css b/internal/web/static/app.css index deb2fd2..f0d4cba 100644 --- a/internal/web/static/app.css +++ b/internal/web/static/app.css @@ -452,3 +452,5 @@ 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; } + diff --git a/internal/web/templates/layout.html b/internal/web/templates/layout.html index 82629e1..d3b4693 100644 --- a/internal/web/templates/layout.html +++ b/internal/web/templates/layout.html @@ -66,6 +66,7 @@ Previews Publishing Lead forms + New site {{end}} {{if eq .ID "prospects"}} diff --git a/internal/web/templates/sites-new.html b/internal/web/templates/sites-new.html new file mode 100644 index 0000000..a12c308 --- /dev/null +++ b/internal/web/templates/sites-new.html @@ -0,0 +1,39 @@ +{{define "content"}}{{with .Data}}{{$n := .N}} +

A new site

+

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.

+ +
+

1. In Gitea

+

Create a new, empty repository{{with .Gitea}} on {{.}}{{end}}: no README, license or .gitignore. Supermarket makes its first commit.

+

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.

+ {{if not .Gitea}}

Save a Gitea token under Settings → Search engines first.

{{end}} +
+ +
+

2. The site

+
+ + +
+
+ + +
+ + +

Brand

+
+ + + +
+
+ + +
+
+ +
+

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 hugo.toml.

+
+{{end}}{{end}} diff --git a/internal/web/templates/sites.html b/internal/web/templates/sites.html index 0adde0b..12908bb 100644 --- a/internal/web/templates/sites.html +++ b/internal/web/templates/sites.html @@ -26,6 +26,23 @@ {{end}} {{with .Catalog}} +{{if $d.Theme}} +
+

First pages

+

This site uses Supermarket's theme (version {{$d.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.

+
+ {{range $d.Kinds}} +
+
+ {{end}} + {{range $d.Products}} +
+
+ {{end}} +
+

Each uses the AI (a paid call). About and Contact join the top menu; Contact has a lead form: connect it under Lead forms.

+
+{{end}} {{with $d.Commits}}

Latest on the published branch