Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 85 additions & 0 deletions internal/branding/branding.go
Original file line number Diff line number Diff line change
@@ -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
}
59 changes: 7 additions & 52 deletions internal/handler/branding_settings.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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
Expand Down Expand Up @@ -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).
Expand Down
8 changes: 7 additions & 1 deletion internal/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
67 changes: 67 additions & 0 deletions internal/worker/reminder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 <img src="/branding/logo?..."> 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")
}
}
20 changes: 16 additions & 4 deletions internal/worker/worker.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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{}
}
Expand All @@ -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,
Expand Down Expand Up @@ -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 <img src="/branding/logo?..."> (#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)
Expand Down
Loading