From 5927c79b9ba219807737cc4df7045327d83c66ea Mon Sep 17 00:00:00 2001 From: Wynne Pirini Date: Fri, 23 Oct 2026 07:51:54 +1300 Subject: [PATCH] fix(email): share branding with the reminder worker (#167) Reminder emails rendered because the worker read logo_url straight out of server_settings, skipping the relative->absolute step that applyBranding performs for confirmations, cancellations and reschedules. Mail clients cannot resolve a relative path, so the logo vanished and the banner was never loaded at all. The cause was structural: applyBranding/loadBranding were methods on handler.Handler, and the worker is a separate package, so it could not call them. Move the brand identity into internal/branding (Load + ApplyTo) and have both senders use it. handler keeps thin loadBranding/applyBranding wrappers so its call sites are unchanged; brandingSettings is an alias of the shared type. The worker now takes the booker-facing base URL via WithPublicURL, wired in server.go with the same PUBLIC_BASE_URL -> BaseURL fallback handler.publicURL() uses. Regression test asserts the rendered reminder carries absolute logo and banner URLs and no relative branding path; it fails against the pre-fix worker. --- internal/branding/branding.go | 85 +++++++++++++++++++++++++++ internal/handler/branding_settings.go | 59 +++---------------- internal/server/server.go | 8 ++- internal/worker/reminder_test.go | 67 +++++++++++++++++++++ internal/worker/worker.go | 20 +++++-- 5 files changed, 182 insertions(+), 57 deletions(-) create mode 100644 internal/branding/branding.go diff --git a/internal/branding/branding.go b/internal/branding/branding.go new file mode 100644 index 00000000..5365a4b8 --- /dev/null +++ b/internal/branding/branding.go @@ -0,0 +1,85 @@ +// Package branding holds the instance-wide brand identity (wordmark, logo, +// banner, legal links) and the one place that stamps it onto outbound email. +// +// It lives outside internal/handler because two different senders need it: the +// HTTP handlers (confirmations, cancellations, reschedules) and the background +// worker (reminders). Duplicating the loading logic is exactly what let reminder +// emails ship with a relative logo path the recipient's mail client could not +// resolve (#167) — so both paths call Load and ApplyTo here instead. +package branding + +import ( + "context" + "database/sql" + "strings" + + "github.com/calnode/calnode/internal/i18n" + "github.com/calnode/calnode/internal/mailer" +) + +// Settings is the instance-wide brand identity used in emails and on the public +// booking/manage/directory pages. +type Settings struct { + BusinessName string + LogoURL string // served path (relative), e.g. "/branding/logo?v=123"; empty = no logo + LogoHeight int // email logo height in px (pages scale up); see handler.pageLogoHeight + LogoOpacity int // 20–100; CSS opacity for a subtle logo. 100 = fully opaque + BannerURL string // served path (relative), e.g. "/branding/banner?v=123"; empty = no banner + BannerOpacity int // 20–100; CSS opacity for the banner. 100 = fully opaque + PrivacyURL string // operator's Privacy Policy URL (absolute http[s]); "" = hidden + TermsURL string // operator's Terms URL (absolute http[s]); "" = hidden + // FallbackLocale is what a visitor sees when their browser doesn't ask for any + // locale Calnode supports — defaults to "en". See i18n.ResolveWithFallback. + FallbackLocale string +} + +// Load reads the brand identity from the singleton settings row. +func Load(ctx context.Context, db *sql.DB) Settings { + var s Settings + _ = db.QueryRowContext(ctx, ` + SELECT COALESCE(business_name,''), COALESCE(logo_url,''), + COALESCE(logo_height,28), COALESCE(logo_opacity,100), + COALESCE(banner_url,''), COALESCE(banner_opacity,100), + COALESCE(privacy_url,''), COALESCE(terms_url,''), + COALESCE(fallback_locale,'en') + FROM server_settings WHERE id = 1`).Scan(&s.BusinessName, &s.LogoURL, &s.LogoHeight, &s.LogoOpacity, + &s.BannerURL, &s.BannerOpacity, &s.PrivacyURL, &s.TermsURL, &s.FallbackLocale) + if s.LogoHeight <= 0 { + s.LogoHeight = 28 + } + if s.LogoOpacity <= 0 || s.LogoOpacity > 100 { + s.LogoOpacity = 100 + } + if s.BannerOpacity <= 0 || s.BannerOpacity > 100 { + s.BannerOpacity = 100 + } + if i18n.Get(s.FallbackLocale) == nil { + s.FallbackLocale = i18n.DefaultCode + } + return s +} + +// ApplyTo stamps the brand identity onto booking email data so every outbound +// email carries the configured wordmark/logo/banner. +// +// The logo and banner are stored as relative served paths; email clients cannot +// resolve those, so a leading "/" is prefixed with the caller's public base URL. +// baseURL is supplied by the caller (handler or worker) rather than read here, +// because the two resolve it from different config sources. +func (s Settings) ApplyTo(d *mailer.BookingData, baseURL string) { + d.BrandName = s.BusinessName + d.LogoHeight = s.LogoHeight + d.LogoOpacity = s.LogoOpacity + d.LogoURL = absoluteAssetURL(s.LogoURL, baseURL) + d.BannerOpacity = s.BannerOpacity + d.BannerURL = absoluteAssetURL(s.BannerURL, baseURL) +} + +// absoluteAssetURL joins a relative served path onto the public base URL, +// leaving absolute or empty values untouched. +func absoluteAssetURL(path, baseURL string) string { + if !strings.HasPrefix(path, "/") { + return path + } + return strings.TrimRight(baseURL, "/") + path +} diff --git a/internal/handler/branding_settings.go b/internal/handler/branding_settings.go index 42017919..d296399a 100644 --- a/internal/handler/branding_settings.go +++ b/internal/handler/branding_settings.go @@ -14,6 +14,7 @@ import ( "strings" "time" + "github.com/calnode/calnode/internal/branding" "github.com/calnode/calnode/internal/i18n" "github.com/calnode/calnode/internal/mailer" "github.com/disintegration/imaging" @@ -26,46 +27,14 @@ const logoServePath = "/branding/logo" // bannerServePath is the served path for the instance banner image. const bannerServePath = "/branding/banner" -// brandingSettings is the instance-wide brand identity used in emails and on the -// public booking/manage/directory pages. -type brandingSettings struct { - BusinessName string - LogoURL string // served path (relative), e.g. "/branding/logo?v=123"; empty = no logo - LogoHeight int // email logo height in px (pages scale up); see pageLogoHeight - LogoOpacity int // 20–100; CSS opacity for a subtle logo. 100 = fully opaque - BannerURL string // served path (relative), e.g. "/branding/banner?v=123"; empty = no banner - BannerOpacity int // 20–100; CSS opacity for the banner. 100 = fully opaque - PrivacyURL string // operator's Privacy Policy URL (absolute http[s]); "" = hidden - TermsURL string // operator's Terms URL (absolute http[s]); "" = hidden - // FallbackLocale is what a visitor sees when their browser doesn't ask for any - // locale Calnode supports — defaults to "en". See i18n.ResolveWithFallback. - FallbackLocale string -} +// brandingSettings is the instance-wide brand identity. The definition lives in +// internal/branding so the background worker can load it too (reminder emails); +// this alias keeps the handler's existing references unchanged. +type brandingSettings = branding.Settings // loadBranding reads the brand identity from the singleton settings row. func (h *Handler) loadBranding(ctx context.Context) brandingSettings { - var b brandingSettings - _ = h.db.QueryRowContext(ctx, ` - SELECT COALESCE(business_name,''), COALESCE(logo_url,''), - COALESCE(logo_height,28), COALESCE(logo_opacity,100), - COALESCE(banner_url,''), COALESCE(banner_opacity,100), - COALESCE(privacy_url,''), COALESCE(terms_url,''), - COALESCE(fallback_locale,'en') - FROM server_settings WHERE id = 1`).Scan(&b.BusinessName, &b.LogoURL, &b.LogoHeight, &b.LogoOpacity, - &b.BannerURL, &b.BannerOpacity, &b.PrivacyURL, &b.TermsURL, &b.FallbackLocale) - if b.LogoHeight <= 0 { - b.LogoHeight = 28 - } - if b.LogoOpacity <= 0 || b.LogoOpacity > 100 { - b.LogoOpacity = 100 - } - if b.BannerOpacity <= 0 || b.BannerOpacity > 100 { - b.BannerOpacity = 100 - } - if i18n.Get(b.FallbackLocale) == nil { - b.FallbackLocale = i18n.DefaultCode - } - return b + return branding.Load(ctx, h.db) } // pageLogoHeight scales the email logo height up ~1.3× for the roomier public @@ -107,21 +76,7 @@ func opacityCSS(pct int) string { // as a relative path; emails need an absolute URL, so it's prefixed with the // public base URL here. Cheap single-row read; called once per send batch. func (h *Handler) applyBranding(ctx context.Context, d *mailer.BookingData) { - b := h.loadBranding(ctx) - d.BrandName = b.BusinessName - d.LogoHeight = b.LogoHeight - d.LogoOpacity = b.LogoOpacity - if strings.HasPrefix(b.LogoURL, "/") { - d.LogoURL = h.publicURL() + b.LogoURL - } else { - d.LogoURL = b.LogoURL - } - d.BannerOpacity = b.BannerOpacity - if strings.HasPrefix(b.BannerURL, "/") { - d.BannerURL = h.publicURL() + b.BannerURL - } else { - d.BannerURL = b.BannerURL - } + h.loadBranding(ctx).ApplyTo(d, h.publicURL()) } // GetBranding handles GET /v1/settings/branding (admin). diff --git a/internal/server/server.go b/internal/server/server.go index 6c0c07ca..e3108098 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -125,7 +125,13 @@ func BuildHandler(ctx context.Context, cfg *config.Config, db *sql.DB, logger *s } else { h.SetWebhookSvc(whs) // Pass live so the worker picks up SMTP changes automatically. - wrk := worker.New(db, whs, logger, worker.WithMailer(live)) + // Reminder emails need the booker-facing host to make branding asset paths + // absolute — mirror handler.publicURL()'s PUBLIC_BASE_URL → BaseURL fallback. + publicURL := cfg.PublicBaseURL + if publicURL == "" { + publicURL = cfg.BaseURL + } + wrk := worker.New(db, whs, logger, worker.WithMailer(live), worker.WithPublicURL(publicURL)) // Notetaker jobs live in the handler package (they need LLM/S3/encKey). wrk.RegisterHandler("notetaker.transcribe", h.JobNotetakerTranscribe) wrk.RegisterHandler("notetaker.summarize", h.JobNotetakerSummarize) diff --git a/internal/worker/reminder_test.go b/internal/worker/reminder_test.go index 3e5b49d5..b509576e 100644 --- a/internal/worker/reminder_test.go +++ b/internal/worker/reminder_test.go @@ -270,3 +270,70 @@ func TestWorker_reminderNamesAssignedHost(t *testing.T) { t.Errorf("reminder body names the event-type owner; want the assigned host:\n%s", msg.Text) } } + +// --------------------------------------------------------------------------- +// reminder.send: branding reaches the email as absolute URLs (#167) +// --------------------------------------------------------------------------- + +// Reminder emails skipped the handler's applyBranding: they read logo_url +// straight from server_settings and never loaded the banner. The stored value is +// a relative served path, so the rendered was +// unresolvable in a mail client and the logo silently disappeared. Assert the +// worker now emits absolute asset URLs and carries the banner too. +func TestWorker_reminderEmailCarriesAbsoluteBranding(t *testing.T) { + database, svc := setup(t) + ctx := context.Background() + + pastRunAt := time.Now().UTC().Add(-time.Second).Format(time.RFC3339) + bookingStart := time.Now().UTC().Add(25 * time.Hour).Format(time.RFC3339) + + if _, err := database.ExecContext(ctx, ` + UPDATE server_settings SET + business_name = 'Acme Scheduling', + logo_url = '/branding/logo?v=42', + logo_height = 40, + logo_opacity = 80, + banner_url = '/branding/banner?v=43', + banner_opacity = 60 + WHERE id = 1`); err != nil { + t.Fatalf("seed branding: %v", err) + } + + database.ExecContext(ctx, + `INSERT INTO event_types (id, user_id, slug, name, duration_minutes) + VALUES ('et-b1','host-01','rem-brand-1','Branded Meeting',30)`) + database.ExecContext(ctx, + `INSERT INTO bookings (id, event_type_id, host_id, start_at, end_at, status) + VALUES ('bk-b1','et-b1','host-01',?,?,'confirmed')`, bookingStart, bookingStart) + database.ExecContext(ctx, + `INSERT INTO booking_attendees (id, booking_id, name, email, iana_timezone, is_organizer) + VALUES ('att-b1','bk-b1','Alice','alice@example.com','UTC',1)`) + database.ExecContext(ctx, ` + INSERT INTO jobs (id, type, payload, run_at, status, attempts, max_attempts) + VALUES ('job-b1','reminder.send','{"booking_id":"bk-b1"}',?,'pending',0,3)`, + pastRunAt) + + m := &captureMailer{} + w := worker.New(database, svc, slog.Default(), + worker.WithMailer(m), + worker.WithPublicURL("https://book.example.com"), + worker.WithHTTPClient(&http.Client{})) + w.Poll(ctx) + + if len(m.sent) != 1 { + t.Fatalf("sent %d emails; want 1", len(m.sent)) + } + html := m.sent[0].HTML + for _, want := range []string{ + `src="https://book.example.com/branding/logo?v=42"`, + `src="https://book.example.com/branding/banner?v=43"`, + "Acme Scheduling", + } { + if !strings.Contains(html, want) { + t.Errorf("reminder HTML missing %q", want) + } + } + if strings.Contains(html, `src="/branding/`) { + t.Error("reminder HTML still contains a relative branding asset path") + } +} diff --git a/internal/worker/worker.go b/internal/worker/worker.go index 72bc8cb7..68bedbb2 100644 --- a/internal/worker/worker.go +++ b/internal/worker/worker.go @@ -11,6 +11,7 @@ import ( "net/http" "time" + "github.com/calnode/calnode/internal/branding" "github.com/calnode/calnode/internal/i18n" "github.com/calnode/calnode/internal/mailer" "github.com/calnode/calnode/internal/netutil" @@ -30,6 +31,7 @@ type Worker struct { mailer mailer.Mailer logger *slog.Logger httpClient *http.Client + publicURL string // booker-facing base URL for outbound email links/assets handlers map[string]func(context.Context, string) error // custom job types (e.g. notetaker) done chan struct{} } @@ -51,6 +53,14 @@ func WithMailer(m mailer.Mailer) func(*Worker) { return func(w *Worker) { w.mailer = m } } +// WithPublicURL sets the booker-facing base URL used to turn stored relative +// branding asset paths into absolute URLs in outbound email. Callers pass the +// same value handler.publicURL() resolves (PUBLIC_BASE_URL, falling back to the +// identity base URL). +func WithPublicURL(url string) func(*Worker) { + return func(w *Worker) { w.publicURL = url } +} + func New(db *sql.DB, svc *webhook.Service, logger *slog.Logger, opts ...func(*Worker)) *Worker { w := &Worker{ db: db, @@ -348,10 +358,12 @@ func (w *Worker) sendReminder(ctx context.Context, payload string) error { } d.Locale = i18n.Get(locale) - // Brand the reminder email with the instance wordmark/logo. - _ = w.db.QueryRowContext(ctx, ` - SELECT COALESCE(business_name,''), COALESCE(logo_url,'') - FROM server_settings WHERE id = 1`).Scan(&d.BrandName, &d.LogoURL) + // Brand the reminder email with the instance wordmark/logo/banner. Reminders + // used to read business_name/logo_url straight from server_settings here, which + // skipped the relative→absolute URL step and never loaded the banner, so mail + // clients rendered a broken (#167). The shared + // branding package is now the only place that does this. + branding.Load(ctx, w.db).ApplyTo(&d, w.publicURL) if err := mailer.SendReminder(ctx, w.mailer, d); err != nil { return fmt.Errorf("worker: reminder: send: %w", err)