Files
tenant-registry/internal/server/trialoffers.go
T
sharang 5525759392
ci / shared (push) Successful in 12s
ci / test (push) Successful in 25m50s
ci / image (push) Successful in 35s
feat(contracts): serve contract documents in Vertragsunterlagen (#118)
2026-11-09 12:59:20 +00:00

670 lines
25 KiB
Go

package server
// Free trial signup (portal#64, phase A). The contract states:
//
// offer submitted (binding offer, § 2 Abs. 1 Testbedingungen)
// → e-mail confirmation pending (receipt mail sent at once, § 312i Abs. 1 Nr. 3 BGB)
// → trial active (Breakpilot accepts by activating: contract concluded,
// the 14 days start, § 2 Abs. 2 / § 3 Abs. 1)
// → trial ended (the tenant ladder: trial_ends_at passes)
//
// The offer row is the evidence: who offered, for which company, under which
// exact contract text (version + SHA-256 of the committed PDF), when. No IP
// address or browser fingerprint is stored.
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"errors"
"net/http"
"net/mail"
"regexp"
"strconv"
"strings"
"time"
"unicode"
"git.breakpilot.com/platform/tenant-registry/internal/legal/trialterms"
bpmail "git.breakpilot.com/platform/tenant-registry/internal/mail"
"git.breakpilot.com/platform/tenant-registry/internal/store"
)
const (
trialDays = 14
offerTokenValidity = 72 * time.Hour
offerRepeatWindow = 10 * time.Minute
offerResendWait = time.Minute
)
// ─── public contract documents ─────────────────────────────────────────────
type trialTermsMeta struct {
DocumentID string `json:"document_id"`
Title string `json:"title"`
Version string `json:"version"`
Date string `json:"date"`
SHA256PDF string `json:"sha256_pdf"`
SHA256HTML string `json:"sha256_html"`
PDFName string `json:"pdf_filename"`
NoticeVersion string `json:"notice_version"`
FlowVersion string `json:"flow_version"`
}
func termsMeta(v *trialterms.Version) trialTermsMeta {
return trialTermsMeta{
DocumentID: trialterms.DocumentID, Title: v.Title, Version: v.Version, Date: v.Date,
SHA256PDF: v.SHA256PDF, SHA256HTML: v.SHA256HTML, PDFName: v.PDFName,
NoticeVersion: trialterms.NoticeVersion, FlowVersion: trialterms.FlowVersion,
}
}
// legalTrialTerms is GET /v1/legal/trial-terms (public): the current version.
func (s *Server) legalTrialTerms(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, termsMeta(trialterms.Current()))
}
// legalTrialTermsFile is GET /v1/legal/trial-terms/{file} (public) with file
// "<version>.pdf", "<version>.html" or "<version>.md": the committed bytes.
func (s *Server) legalTrialTermsFile(w http.ResponseWriter, r *http.Request) {
file := r.PathValue("file")
dot := strings.LastIndex(file, ".")
if dot < 0 {
writeError(w, http.StatusNotFound, "not_found", "no such document")
return
}
v := trialterms.Get(file[:dot])
if v == nil {
writeError(w, http.StatusNotFound, "unknown_version", "no such version of the trial terms")
return
}
switch file[dot+1:] {
case "pdf":
serveTermsPDF(w, v, "inline")
case "html":
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("ETag", `"`+v.SHA256HTML+`"`)
w.Header().Set("Cache-Control", "public, max-age=3600")
_, _ = w.Write(v.HTML)
case "md":
w.Header().Set("Content-Type", "text/markdown; charset=utf-8")
_, _ = w.Write(v.Markdown)
default:
writeError(w, http.StatusNotFound, "not_found", "no such document")
}
}
func serveTermsPDF(w http.ResponseWriter, v *trialterms.Version, disposition string) {
w.Header().Set("Content-Type", "application/pdf")
w.Header().Set("Content-Disposition", disposition+`; filename="`+v.PDFName+`"`)
w.Header().Set("ETag", `"`+v.SHA256PDF+`"`)
w.Header().Set("Content-Length", strconv.Itoa(len(v.PDF)))
w.Header().Set("Cache-Control", "public, max-age=3600")
_, _ = w.Write(v.PDF)
}
// ─── offer ─────────────────────────────────────────────────────────────────
type trialOfferReq struct {
CompanyName string `json:"company_name"`
Street string `json:"street"`
Postcode string `json:"postcode"`
City string `json:"city"`
Country string `json:"country"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Email string `json:"email"`
TermsVersion string `json:"terms_version"`
TermsSHA256 string `json:"terms_sha256"`
NoticeVersion string `json:"notice_version"`
FlowVersion string `json:"flow_version"`
TermsAccepted bool `json:"terms_accepted"`
}
var (
countryRE = regexp.MustCompile(`^[A-Z]{2}$`)
dePostcodeRE = regexp.MustCompile(`^[0-9]{5}$`)
)
// validate trims the fields and returns the first invalid one ("" = ok).
func (in *trialOfferReq) validate() string {
for _, f := range []*string{&in.CompanyName, &in.Street, &in.Postcode, &in.City, &in.FirstName, &in.LastName} {
*f = strings.Join(strings.Fields(*f), " ")
}
in.Country = strings.ToUpper(strings.TrimSpace(in.Country))
in.Email = strings.ToLower(strings.TrimSpace(in.Email))
runes := func(s string) int { return len([]rune(s)) }
switch {
case runes(in.CompanyName) < 1 || runes(in.CompanyName) > 255:
return "company_name"
case runes(in.Street) < 1 || runes(in.Street) > 200:
return "street"
case !countryRE.MatchString(in.Country):
return "country"
case runes(in.Postcode) < 1 || runes(in.Postcode) > 20 || (in.Country == "DE" && !dePostcodeRE.MatchString(in.Postcode)):
return "postcode"
case runes(in.City) < 1 || runes(in.City) > 100:
return "city"
case runes(in.FirstName) < 1 || runes(in.FirstName) > 100:
return "first_name"
case runes(in.LastName) < 1 || runes(in.LastName) > 100:
return "last_name"
}
if addr, err := mail.ParseAddress(in.Email); err != nil || addr.Address != in.Email || len(in.Email) > 254 {
return "email"
}
return ""
}
type trialOfferResp struct {
OfferID string `json:"offer_id"`
State string `json:"state"`
Email string `json:"email"`
OfferedAt time.Time `json:"offered_at"`
ReceiptMailSent bool `json:"receipt_mail_sent"`
}
// createTrialOffer is POST /v1/trial-offers (portal-svc): the customer's
// binding offer. Records the snapshot and sends the receipt, which carries
// the confirmation link.
func (s *Server) createTrialOffer(w http.ResponseWriter, r *http.Request) {
var in trialOfferReq
if !decodeJSON(w, r, &in) {
return
}
if f := in.validate(); f != "" {
writeError(w, http.StatusBadRequest, "invalid_field", f)
return
}
if !in.TermsAccepted {
writeError(w, http.StatusBadRequest, "terms_not_accepted", "the trial terms must be accepted")
return
}
cur := trialterms.Current()
if in.TermsVersion != cur.Version || in.TermsSHA256 != cur.SHA256PDF ||
in.NoticeVersion != trialterms.NoticeVersion || in.FlowVersion != trialterms.FlowVersion {
writeError(w, http.StatusConflict, "version_mismatch", "the terms or the notice shown are not the current version")
return
}
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
defer cancel()
if s.Keycloak != nil {
if taken, err := s.Keycloak.UserExists(ctx, in.Email); err == nil && taken {
writeError(w, http.StatusConflict, "email_taken", "an account with this email already exists")
return
} else if err != nil {
s.Log.Warn("keycloak user lookup failed", "err", err)
}
}
now := s.now()
if last, err := s.Store.LatestTrialOffer(ctx, in.Email); err == nil &&
last.State == store.OfferPending && now.Sub(last.OfferedAt) < offerRepeatWindow {
writeError(w, http.StatusTooManyRequests, "too_many_offers", "an unconfirmed offer for this address is less than 10 minutes old")
return
}
token, hash, err := newOfferToken()
if err != nil {
writeError(w, http.StatusInternalServerError, "internal", "token")
return
}
o, err := s.Store.CreateTrialOffer(ctx, store.TrialOffer{
CompanyName: in.CompanyName, Street: in.Street, Postcode: in.Postcode, City: in.City, Country: in.Country,
FirstName: in.FirstName, LastName: in.LastName, Email: in.Email,
TermsDocumentID: trialterms.DocumentID, TermsVersion: cur.Version, TermsSHA256: cur.SHA256PDF,
NoticeVersion: trialterms.NoticeVersion, FlowVersion: trialterms.FlowVersion, ContractLanguage: "de",
TermsAccepted: true, OfferedAt: now,
VerifyTokenHash: hash, VerifyExpiresAt: now.Add(offerTokenValidity),
})
if err != nil {
s.Log.Error("create trial offer failed", "err", err)
writeError(w, http.StatusInternalServerError, "internal", "offer not recorded")
return
}
s.Log.Info("trial offer submitted", "offer_id", o.ID, "terms_version", o.TermsVersion)
sent := s.sendReceipt(ctx, o, token)
writeJSON(w, http.StatusCreated, trialOfferResp{OfferID: o.ID, State: o.State, Email: o.Email, OfferedAt: o.OfferedAt, ReceiptMailSent: sent})
}
func newOfferToken() (token, hash string, err error) {
b := make([]byte, 32)
if _, err = rand.Read(b); err != nil {
return "", "", err
}
token = base64.RawURLEncoding.EncodeToString(b)
return token, hashOfferToken(token), nil
}
func hashOfferToken(token string) string {
h := sha256.Sum256([]byte(token))
return hex.EncodeToString(h[:])
}
// sendReceipt sends the receipt with the confirmation link and records it.
func (s *Server) sendReceipt(ctx context.Context, o *store.TrialOffer, token string) bool {
if s.Mail == nil {
s.Log.Warn("no mail relay: trial receipt not sent", "offer_id", o.ID)
return false
}
msg, err := bpmail.Render(bpmail.KindTrialReceived, "de", bpmail.View{
Tenant: o.CompanyName,
URL: s.portalURL() + "/start/bestaetigen?token=" + token,
D: map[string]any{
"company_name": o.CompanyName, "street": o.Street, "postcode": o.Postcode, "city": o.City,
"person_name": o.FirstName + " " + o.LastName, "email": o.Email,
"terms_version": o.TermsVersion, "valid_hours": int(offerTokenValidity.Hours()),
},
})
if err == nil {
msg.To = o.Email
err = s.Mail.Send(ctx, msg)
}
if err != nil {
s.Log.Error("trial receipt mail failed", "offer_id", o.ID, "err", err)
return false
}
_ = s.Store.MarkTrialOfferMail(ctx, o.ID, "receipt", s.now())
return true
}
// resendTrialOffer is POST /v1/trial-offers/{id}/resend: a new confirmation
// link for the same offer (the old one stops working).
func (s *Server) resendTrialOffer(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
defer cancel()
o, err := s.Store.GetTrialOffer(ctx, r.PathValue("id"))
if err != nil {
if mapStoreError(w, err) {
return
}
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
if o.State != store.OfferPending {
writeError(w, http.StatusConflict, "already_activated", "the offer is already confirmed")
return
}
if o.ReceiptMailSentAt != nil && s.now().Sub(*o.ReceiptMailSentAt) < offerResendWait {
writeError(w, http.StatusTooManyRequests, "too_many_offers", "a link was sent less than a minute ago")
return
}
token, hash, err := newOfferToken()
if err != nil {
writeError(w, http.StatusInternalServerError, "internal", "token")
return
}
if o, err = s.Store.SetTrialOfferToken(ctx, o.ID, hash, s.now().Add(offerTokenValidity)); err != nil {
if errors.Is(err, store.ErrConflict) {
writeError(w, http.StatusConflict, "already_activated", "the offer is already confirmed")
return
}
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
sent := s.sendReceipt(ctx, o, token)
writeJSON(w, http.StatusAccepted, trialOfferResp{OfferID: o.ID, State: o.State, Email: o.Email, OfferedAt: o.OfferedAt, ReceiptMailSent: sent})
}
// ─── confirmation and activation ───────────────────────────────────────────
type verifyReq struct {
Token string `json:"token"`
}
type verifyResp struct {
Outcome string `json:"outcome"` // activated | already_activated
TenantSlug string `json:"tenant_slug"`
CompanyName string `json:"company_name"`
Email string `json:"email"`
TrialStartedAt *time.Time `json:"trial_started_at"`
TrialExpiresAt *time.Time `json:"trial_expires_at"`
TermsVersion string `json:"terms_version"`
}
// verifyTrialOffer is POST /v1/trial-offers/verify: the confirmation click.
// It confirms the address and, at once, Breakpilot accepts the offer by
// activating the trial.
func (s *Server) verifyTrialOffer(w http.ResponseWriter, r *http.Request) {
var in verifyReq
if !decodeJSON(w, r, &in) {
return
}
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
o, err := s.Store.GetTrialOfferByToken(ctx, hashOfferToken(strings.TrimSpace(in.Token)))
if err != nil || strings.TrimSpace(in.Token) == "" {
writeError(w, http.StatusNotFound, "token_invalid", "unknown confirmation link")
return
}
if o.State == store.OfferActivated {
s.writeVerified(ctx, w, "already_activated", o)
return
}
now := s.now()
if o.State == store.OfferPending {
if now.After(o.VerifyExpiresAt) {
writeJSON(w, http.StatusGone, map[string]string{"error": "token_expired", "message": "the confirmation link has expired", "offer_id": o.ID})
return
}
if v, err := s.Store.VerifyTrialOffer(ctx, o.ID, now); err == nil {
o = v
} else if errors.Is(err, store.ErrConflict) {
// A concurrent click got there first.
if o, err = s.Store.GetTrialOffer(ctx, o.ID); err == nil && o.State == store.OfferActivated {
s.writeVerified(ctx, w, "already_activated", o)
return
}
writeError(w, http.StatusConflict, "in_progress", "the activation is in progress, please reload in a moment")
return
} else {
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
}
// verified: activate (also a retry after an earlier failed activation).
o, aerr := s.activateTrial(ctx, r, o)
if aerr != nil {
writeError(w, aerr.status, aerr.code, aerr.msg)
return
}
s.writeVerified(ctx, w, "activated", o)
}
func (s *Server) writeVerified(ctx context.Context, w http.ResponseWriter, outcome string, o *store.TrialOffer) {
resp := verifyResp{Outcome: outcome, CompanyName: o.CompanyName, Email: o.Email,
TrialStartedAt: o.TrialStartedAt, TrialExpiresAt: o.TrialExpiresAt, TermsVersion: o.TermsVersion}
if t, err := s.Store.GetTenant(ctx, o.TenantID); err == nil {
resp.TenantSlug = t.Slug
if t.TrialEndsAt != nil && o.TrialExpiresAt != nil && t.TrialEndsAt.After(*o.TrialExpiresAt) {
resp.TrialExpiresAt = t.TrialEndsAt // extended by staff
}
}
writeJSON(w, http.StatusOK, resp)
}
// trialEnd is 14 calendar days after start, same clock time in Berlin, so the
// date shown ("Ende: …") and the ladder agree across a DST change.
func trialEnd(start time.Time) time.Time {
return start.In(erpZone).AddDate(0, 0, trialDays).UTC()
}
// activateTrial accepts the offer: tenant, Keycloak account (address already
// confirmed, the user only sets a password), trial times, audit chain and the
// activation mail with the contract PDF.
func (s *Server) activateTrial(ctx context.Context, r *http.Request, o *store.TrialOffer) (*store.TrialOffer, *apiError) {
slug, err := s.freeSlug(ctx, o.CompanyName)
if err != nil {
return nil, &apiError{http.StatusInternalServerError, "internal", err.Error()}
}
t, _, aerr := s.createTenantCore(ctx, r, createTenantReq{
Slug: slug, Name: o.CompanyName, AdminEmail: o.Email, AdminName: o.FirstName + " " + o.LastName,
adminFirst: o.FirstName, adminLast: o.LastName, emailVerified: true,
})
if aerr != nil {
s.Log.Error("trial activation failed", "offer_id", o.ID, "code", aerr.code)
if aerr.code == "email_taken" {
return nil, aerr
}
return nil, &apiError{http.StatusBadGateway, "activation_failed", "the trial could not be activated; Breakpilot has been informed"}
}
now := s.now()
end := trialEnd(now)
if t2, err := s.Store.UpdateTenant(ctx, t.ID, store.TenantUpdate{TrialEndsAt: &end}); err == nil {
t = t2
}
activated, err := s.Store.ActivateTrialOffer(ctx, o.ID, t.ID, now, end)
if err != nil {
s.Log.Error("trial offer not marked activated", "offer_id", o.ID, "tenant_id", t.ID, "err", err)
return nil, &apiError{http.StatusInternalServerError, "internal", "activation not recorded"}
}
offerMeta := map[string]interface{}{
"offer_id": o.ID, "offered_at": o.OfferedAt,
"company_name": o.CompanyName, "company_address": o.Street + ", " + o.Postcode + " " + o.City + ", " + o.Country,
"accepting_person_name": o.FirstName + " " + o.LastName, "accepting_email": o.Email,
"trial_terms_document_id": o.TermsDocumentID, "trial_terms_version": o.TermsVersion, "trial_terms_sha256": o.TermsSHA256,
"contract_language": o.ContractLanguage, "article_246c_notice_version": o.NoticeVersion,
"registration_flow_version": o.FlowVersion, "terms_accepted": true,
}
for _, ev := range []struct {
action string
meta map[string]interface{}
}{
{"trial.offer_submitted", offerMeta},
{"trial.email_verified", map[string]interface{}{"offer_id": o.ID, "verified_at": activated.VerifiedAt}},
{"trial.contract_accepted", map[string]interface{}{"offer_id": o.ID, "contract_accepted_at": now, "trial_terms_version": o.TermsVersion}},
{"trial.activated", map[string]interface{}{"offer_id": o.ID, "trial_started_at": now, "trial_expires_at": end}},
} {
s.emitAudit(ctx, r, store.AuditEvent{TenantID: t.ID, Action: ev.action, TargetID: t.ID, TargetType: "tenant",
TargetName: t.Slug, ActorType: "service", ActorName: o.Email, Metadata: ev.meta})
}
s.sendActivation(ctx, activated, t)
return activated, nil
}
func (s *Server) sendActivation(ctx context.Context, o *store.TrialOffer, t *store.Tenant) {
if s.Mail == nil {
s.Log.Warn("no mail relay: trial activation mail not sent", "offer_id", o.ID)
return
}
v := trialterms.Get(o.TermsVersion)
date := func(p *time.Time) string {
if p == nil {
return ""
}
return p.In(erpZone).Format("02.01.2006")
}
workspace := s.portalURL() + "/" + t.Slug
msg, err := bpmail.Render(bpmail.KindTrialActivated, "de", bpmail.View{
Tenant: o.CompanyName,
URL: workspace + "/dashboard",
D: map[string]any{
"company_name": o.CompanyName, "person_name": o.FirstName + " " + o.LastName,
"started": date(o.TrialStartedAt), "expires": date(o.TrialExpiresAt),
"workspace_url": workspace, "terms_version": v.Version, "terms_date": germanDate(v.Date),
},
})
if err == nil {
msg.To = o.Email
msg.Attachments = []bpmail.Attachment{{Name: v.PDFName, ContentType: "application/pdf", Data: v.PDF}}
err = s.Mail.Send(ctx, msg)
}
if err != nil {
s.Log.Error("trial activation mail failed", "offer_id", o.ID, "err", err)
return
}
_ = s.Store.MarkTrialOfferMail(ctx, o.ID, "activation", s.now())
}
// ─── workspace slug ────────────────────────────────────────────────────────
var legalForms = map[string]bool{
"gmbh": true, "mbh": true, "ag": true, "kg": true, "kgaa": true, "ug": true, "se": true, "ohg": true,
"gbr": true, "ev": true, "eg": true, "co": true, "und": true, "haftungsbeschraenkt": true,
"ltd": true, "llc": true, "inc": true, "sa": true, "sarl": true, "bv": true, "nv": true, "srl": true, "spa": true,
}
// slugFromCompany turns "Müller Maschinenbau GmbH & Co. KG" into
// "mueller-maschinenbau": lower case, umlauts spelled out, other characters
// as separators, trailing legal forms dropped, at most 40 characters.
func slugFromCompany(name string) string {
name = strings.NewReplacer("ä", "ae", "ö", "oe", "ü", "ue", "ß", "ss", "Ä", "ae", "Ö", "oe", "Ü", "ue").Replace(name)
var words []string
var cur strings.Builder
flush := func() {
if cur.Len() > 0 {
words = append(words, cur.String())
cur.Reset()
}
}
for _, r := range strings.ToLower(name) {
switch {
case r >= 'a' && r <= 'z' || r >= '0' && r <= '9':
cur.WriteRune(r)
case unicode.IsLetter(r):
// other accented letters: keep the base where it is ASCII-like
if b := foldAccent(r); b != 0 {
cur.WriteRune(b)
}
default:
flush()
}
}
flush()
for len(words) > 1 && legalForms[words[len(words)-1]] {
words = words[:len(words)-1]
}
slug := ""
for _, w := range words {
next := w
if slug != "" {
next = slug + "-" + w
}
if len(next) > 40 {
break
}
slug = next
}
if len(slug) < 3 {
slug = strings.Trim(slug+"-firma", "-")
}
return slug
}
func foldAccent(r rune) rune {
const from, to = "àáâãåèéêëìíîïòóôõøùúûýÿçñ", "aaaaaeeeeiiiiooooouuuyycn"
fr := []rune(from)
for i, c := range fr {
if c == r {
return rune(to[i])
}
}
return 0
}
// freeSlug is the company's slug, or the first free "<slug>-2" … "-99".
func (s *Server) freeSlug(ctx context.Context, company string) (string, error) {
base := slugFromCompany(company)
for i := 1; i < 100; i++ {
cand := base
if i > 1 {
cand = base + "-" + strconv.Itoa(i)
}
if reservedSlugs[cand] || !slugRE.MatchString(cand) {
continue
}
if _, err := s.Store.GetTenantBySlug(ctx, cand); errors.Is(err, store.ErrNotFound) {
return cand, nil
} else if err != nil {
return "", err
}
}
return "", errors.New("no free workspace name for " + base)
}
// ─── Vertragsunterlagen ────────────────────────────────────────────────────
type trialContract struct {
Status string `json:"status"` // active | ended
OfferedAt time.Time `json:"offered_at"`
ContractAcceptedAt *time.Time `json:"contract_accepted_at"`
TrialStartedAt *time.Time `json:"trial_started_at"`
TrialExpiresAt *time.Time `json:"trial_expires_at"`
TermsVersion string `json:"terms_version"`
TermsDate string `json:"terms_date"`
TermsSHA256 string `json:"terms_sha256"`
AcceptingPersonName string `json:"accepting_person_name"`
AcceptingEmail string `json:"accepting_email"`
CompanyName string `json:"company_name"`
}
type contractStatus struct {
Status string `json:"status"`
}
type contractsResp struct {
Trial *trialContract `json:"trial"`
AVV contractStatus `json:"avv"`
TOMs contractStatus `json:"toms"`
SaaS contractStatus `json:"saas"`
// Documents are the released contract documents for this tenant
// (contract_documents.go); empty while CONTRACT_DOCUMENTS is off.
Documents []contractDocument `json:"documents"`
}
// listTenantContracts is GET /v1/tenants/{id}/contracts: the tenant's contract
// documents. trial is null when the tenant never made a trial offer (created
// by staff), so nothing is shown that was not concluded.
func (s *Server) listTenantContracts(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
t, ok := s.tenantInScope(ctx, w, r)
if !ok {
return
}
resp := contractsResp{AVV: contractStatus{"not_concluded"}, TOMs: contractStatus{"pending"}, SaaS: contractStatus{"not_concluded"}}
o, err := s.Store.GetTrialOfferByTenant(ctx, t.ID)
if err == nil && o.State == store.OfferActivated {
end := o.TrialExpiresAt
if t.TrialEndsAt != nil && (end == nil || t.TrialEndsAt.After(*end)) {
end = t.TrialEndsAt
}
status := "ended"
if t.Status == store.StatusTrial && end != nil && s.now().Before(*end) {
status = "active"
}
date := ""
if v := trialterms.Get(o.TermsVersion); v != nil {
date = v.Date
}
resp.Trial = &trialContract{
Status: status, OfferedAt: o.OfferedAt, ContractAcceptedAt: o.ContractAcceptedAt,
TrialStartedAt: o.TrialStartedAt, TrialExpiresAt: end,
TermsVersion: o.TermsVersion, TermsDate: date, TermsSHA256: o.TermsSHA256,
AcceptingPersonName: o.FirstName + " " + o.LastName, AcceptingEmail: o.Email, CompanyName: o.CompanyName,
}
} else if err != nil && !errors.Is(err, store.ErrNotFound) {
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
if resp.Documents, err = s.tenantContractDocuments(ctx, t); err != nil {
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
writeJSON(w, http.StatusOK, resp)
}
// tenantTrialTermsPDF is GET /v1/tenants/{id}/contracts/trial/terms.pdf: the
// exact PDF of the version this tenant accepted.
func (s *Server) tenantTrialTermsPDF(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
t, ok := s.tenantInScope(ctx, w, r)
if !ok {
return
}
o, err := s.Store.GetTrialOfferByTenant(ctx, t.ID)
if err != nil || o.State != store.OfferActivated {
writeError(w, http.StatusNotFound, "not_found", "no trial contract for this tenant")
return
}
v := trialterms.Get(o.TermsVersion)
if v == nil || v.SHA256PDF != o.TermsSHA256 {
s.Log.Error("accepted trial terms not available", "tenant_id", t.ID, "version", o.TermsVersion)
writeError(w, http.StatusInternalServerError, "internal", "contract document missing")
return
}
serveTermsPDF(w, v, "attachment")
}
var germanMonths = [...]string{"Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"}
// germanDate turns "2026-10-01" into "1. Oktober 2026".
func germanDate(iso string) string {
d, err := time.Parse("2006-01-02", iso)
if err != nil {
return iso
}
return strconv.Itoa(d.Day()) + ". " + germanMonths[d.Month()-1] + " " + strconv.Itoa(d.Year())
}