Files
tenant-registry/internal/server/catalog.go
T
Sharang ParnerkarandClaude Opus 5.5 fb86a78324
ci / shared (pull_request) Successful in 30s
ci / test (pull_request) Successful in 8m49s
ci / image (pull_request) Skipped
feat(branding): derive colour and logo from the signup domain
Customer branding (#155), steps 1–6: the registry reads the home page
of the workspace's company domain and stores its CI colour and logo.

- Domain: the admin's address, else the most frequent member domain
  (tie: alphabetical); free mail never counts; no domain, no branding.
- Fetch (internal/branding): own transport (no proxy, no trace
  headers, no cookies), https on 443 only, public IPs only, checked on
  every dial after DNS, ≤ 5 redirects within the registrable domain,
  10 s per request, HTML ≤ 2 MB, images ≤ 1 MB, User-Agent
  BreakpilotBranding/1.0.
- Colour: theme-color without media, the manifest's theme_color, else
  the logo's dominant colour; white, black and grey are skipped.
- Logo: manifest PNG ≥ 128 px, apple-touch-icon, PNG/ICO/JPEG icon,
  /favicon.ico; stored as a 256×256 PNG, never SVG.
- POST /v1/tenants/{id}/branding/derive ("Neu ermitteln"): synchronous,
  replaces a manual choice and counts as acknowledged.
- Background: tenant creation and trial requests queue the workspace;
  RunBranding derives queued ones every minute, retries network
  failures twice, 6 h apart. Audit branding.derived / branding.failed.
- Switches: BRANDING_DERIVE=on (off by default), BRANDING_BACKFILL=on
  queues every customer workspace without branding once at start.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 13:15:31 +01:00

199 lines
6.5 KiB
Go

package server
import (
"context"
"errors"
"git.breakpilot.com/platform/tenant-registry/internal/authn"
"net/http"
"time"
"git.breakpilot.com/platform/tenant-registry/internal/store"
)
// The catalog lives in the products table (migration 0003) since M-MIG-5.
// Launch URLs are resolved for this registry's environment (APP_ENV) so the
// portal can link straight to the product host.
func (s *Server) getCatalog(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
products, err := s.Store.ListProducts(ctx, false)
if err != nil {
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
items := make([]store.CatalogEntry, 0, len(products))
for _, p := range products {
e := p.Catalog(s.env())
if s.onPrem() {
e.SupportsTrial = false // no trials on a customer's node: the portal hides the button
}
items = append(items, e)
}
writeJSON(w, http.StatusOK, map[string]any{"items": items})
}
// env is the environment key used for per-env product URLs (see
// config.CatalogEnv). On-prem the catalog has no seeded URLs; they come from
// PRODUCT_*_URLS through store.ProductOverrides.
func (s *Server) env() string { return s.Cfg.CatalogEnv() }
// onPrem reports a registry on a customer's node (APP_ENV=onprem).
func (s *Server) onPrem() bool { return s.Cfg.OnPrem() }
// notOnPrem answers 404 for a feature that does not exist on-prem (sign-up,
// trial offers, sales requests, the ERP) and reports whether it did.
func (s *Server) notOnPrem(w http.ResponseWriter) bool {
if !s.onPrem() {
return false
}
writeError(w, http.StatusNotFound, "not_available", "not available in this installation")
return true
}
// product returns an enabled catalog product or ErrNotFound.
func (s *Server) product(ctx context.Context, key string) (*store.Product, error) {
p, err := s.Store.GetProduct(ctx, key)
if err != nil {
return nil, err
}
if !p.Enabled {
return nil, store.ErrNotFound
}
return p, nil
}
func (s *Server) knownProduct(ctx context.Context, key string) bool {
_, err := s.product(ctx, key)
return err == nil
}
type catalogRequestReq struct {
TenantID string `json:"tenant_id"`
Product string `json:"product"`
}
// catalogRequest — customer requests a non-subscribed product. Emits an
// audit event; the ERP outbox (M-MIG-7) turns it into a CRM Lead.
func (s *Server) catalogRequest(w http.ResponseWriter, r *http.Request) {
if s.notOnPrem(w) {
return
}
var in catalogRequestReq
if !decodeJSON(w, r, &in) {
return
}
if in.TenantID == "" || in.Product == "" {
writeError(w, http.StatusBadRequest, "invalid_input", "tenant_id and product are required")
return
}
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
if !s.knownProduct(ctx, in.Product) {
writeError(w, http.StatusBadRequest, "unknown_product", "product is not in the catalog")
return
}
t, err := s.Store.GetTenant(ctx, in.TenantID)
if err != nil {
if mapStoreError(w, err) {
return
}
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
s.emitAudit(ctx, r, store.AuditEvent{
TenantID: in.TenantID, Action: "catalog.requested",
TargetID: in.Product, TargetType: "product",
Metadata: map[string]interface{}{"product": in.Product},
})
// CRM lead through the ERP outbox (M-MIG-7).
email := ""
if p, _ := authn.PrincipalFrom(r.Context()); p != nil {
email = p.Email
}
if _, err := s.enqueueERP(ctx, store.OutboxItem{Kind: store.OutboxLeadCreate, TenantID: in.TenantID,
Payload: map[string]interface{}{"lead_name": t.Name, "company_name": t.Name, "email": email, "product": in.Product,
"notes": "Requested " + in.Product + " from the platform catalog"}}); err != nil {
s.Log.Error("enqueue lead failed", "tenant_id", in.TenantID, "err", err)
}
writeJSON(w, http.StatusAccepted, map[string]string{
"status": "accepted",
"message": "request recorded; sales will be in touch",
})
}
// catalogTrialRequest — self-serve trial of a product that supports it.
// Provisions the entitlement immediately (trial_days from the catalog).
func (s *Server) catalogTrialRequest(w http.ResponseWriter, r *http.Request) {
if s.notOnPrem(w) {
return
}
var in catalogRequestReq
if !decodeJSON(w, r, &in) {
return
}
if in.TenantID == "" || in.Product == "" {
writeError(w, http.StatusBadRequest, "invalid_input", "tenant_id and product are required")
return
}
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
entry, err := s.product(ctx, in.Product)
if err != nil {
if errors.Is(err, store.ErrNotFound) {
writeError(w, http.StatusBadRequest, "unknown_product", "product is not in the catalog")
return
}
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
if !entry.SupportsTrial {
writeError(w, http.StatusBadRequest, "trial_unavailable", "product does not support self-serve trial")
return
}
t, err := s.Store.GetTenant(ctx, in.TenantID)
if err != nil {
if mapStoreError(w, err) {
return
}
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
days := entry.TrialDays
if days <= 0 {
days = 14
}
expiresAt := productTrialEnd(t, time.Now().UTC(), days)
tp, err := s.Store.UpsertTenantProduct(ctx, store.TenantProduct{
TenantID: in.TenantID, Product: in.Product, Enabled: true,
Config: map[string]interface{}{"source": "trial"}, ExpiresAt: &expiresAt,
})
if err != nil {
if mapStoreError(w, err) {
return
}
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
s.emitAudit(ctx, r, store.AuditEvent{
TenantID: in.TenantID, Action: "catalog.trial_started",
TargetID: in.Product, TargetType: "product",
Metadata: map[string]interface{}{"product": in.Product, "expires_at": expiresAt.Format(time.RFC3339)},
})
s.provisionProduct(ctx, r, t, entry, tp)
s.enqueueBranding(ctx, t)
writeJSON(w, http.StatusCreated, tp)
}
// productTrialEnd is when a product trial started now ends. In a workspace on
// trial it ends with the workspace's trial, which staff set or extended for
// the customer; a product of its own default length would end before or
// after what was agreed. Otherwise (a paying workspace trying another
// product) it runs `days` days.
func productTrialEnd(t *store.Tenant, now time.Time, days int) time.Time {
if t != nil && t.Status == store.StatusTrial && t.TrialEndsAt != nil && t.TrialEndsAt.After(now) {
return t.TrialEndsAt.UTC()
}
return now.Add(time.Duration(days) * 24 * time.Hour)
}