package server import ( "bytes" "context" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "io" "net/http" "regexp" "slices" "strconv" "strings" "sync" "time" "github.com/google/uuid" "git.breakpilot.com/platform/tenant-registry/internal/legal/avvfill" "git.breakpilot.com/platform/tenant-registry/internal/keycloak" "git.breakpilot.com/platform/tenant-registry/internal/legal/contractdocs" "git.breakpilot.com/platform/tenant-registry/internal/roles" "git.breakpilot.com/platform/tenant-registry/internal/store" ) // Contract documents of the Vertragsunterlagen: the released AGB, AVV, TOM // and Leistungsbeschreibungen (internal/legal/contractdocs, embedded and // pinned) and a workspace's own filled AVV (0027, in the document bucket). // Behind the release gate CONTRACT_DOCUMENTS: off, the overview lists none // and the PDF route answers 404. // // GET /v1/tenants/{id}/contracts overview, "documents" (tenants.read) // GET /v1/tenants/{id}/contracts/documents/{doc}.pdf the PDF (tenants.read) // GET /v1/admin/tenants/{id}/avv-values the details for the AVV (admin, staff only) // // The AVV a workspace sees: the one staff uploaded for it, else the master // filled with its details (avvfill) once the company profile is submitted // and its Geschäftsleitung is named, else the master, with what is missing. // PUT /v1/admin/tenants/{id}/contract-documents/avv the filled AVV (admin, staff only) // maxContractPDFBytes caps a filled AVV upload. const maxContractPDFBytes = 5 << 20 type contractDocument struct { ID string `json:"id"` Kind string `json:"kind"` Title string `json:"title"` Version string `json:"version"` Date string `json:"date"` // Stand, DD.MM.YYYY SHA256 string `json:"sha256"` Product string `json:"product,omitempty"` ManagedService string `json:"managed_service,omitempty"` TenantSpecific bool `json:"tenant_specific"` // The AVV only. FilledFrom: "profile" (filled from the workspace's // details) or "staff" (uploaded). Missing: why the master is still blank, // as avvMissing* codes, so the portal can say what to complete. FilledFrom string `json:"filled_from,omitempty"` Missing []string `json:"missing,omitempty"` master *contractdocs.Doc own *store.ContractDocument filled []byte // the master filled from the profile } var contractKindOrder = map[string]int{contractdocs.KindAGB: 0, contractdocs.KindAVV: 1, contractdocs.KindTOM: 2, contractdocs.KindLB: 3} func (s *Server) contractCatalogue() *contractdocs.Catalogue { if s.Contracts != nil { return s.Contracts } return contractdocs.Default() } // contractHoldings is what decides a tenant's Leistungsbeschreibungen: the // products it has booked or on trial now (enabled, not expired; a staff // preview grant is no booking and brings in no Leistungsbeschreibung) and the // managed services it has (in any status: the contract stands while the // service is provisioned, restricted or halted). func contractHoldings(tps []store.TenantProduct, services []store.ManagedService, now time.Time) contractdocs.Holdings { h := contractdocs.Holdings{Products: map[string]bool{}, ManagedServices: map[string]bool{}} for _, tp := range tps { if tp.Preview || !tp.Enabled || (tp.ExpiresAt != nil && !tp.ExpiresAt.After(now)) { continue } h.Products[tp.Product] = true } for _, ms := range services { h.ManagedServices[ms.Kind] = true } return h } // tenantContractDocuments lists the contract documents of t: AGB, AVV, TOM, // then the Leistungsbeschreibungen that apply. The tenant's own filled AVV // takes the place of the master. Empty while the gate is off. func (s *Server) tenantContractDocuments(ctx context.Context, t *store.Tenant) ([]contractDocument, error) { out := []contractDocument{} if !s.cfg().ContractDocuments { return out, nil } tps, err := s.Store.ListTenantProducts(ctx, t.ID) if err != nil { return nil, err } services, err := s.Store.ListManagedServices(ctx, t.ID) if err != nil { return nil, err } own, err := s.Store.CurrentContractDocument(ctx, t.ID, store.ContractDocumentAVV) if errors.Is(err, store.ErrNotFound) { own, err = nil, nil } if err != nil { return nil, err } cat := s.contractCatalogue() for _, d := range cat.For(contractHoldings(tps, services, s.now())) { if d.Kind == contractdocs.KindAVV && own != nil { continue } doc := contractDocument{ ID: d.ID, Kind: d.Kind, Title: d.Title, Version: d.Version, Date: d.Date, SHA256: d.SHA256, Product: d.Product, ManagedService: d.ManagedService, master: d, } if d.Kind == contractdocs.KindAVV { s.fillAVV(ctx, t, &doc) } out = append(out, doc) } if own != nil { // The Stand of the master it was filled from; without that master in // the table, the day it was made. date := own.CreatedAt.In(berlin).Format("02.01.2006") if m := cat.Get(contractdocs.KindAVV); m != nil && m.Version == own.Version { date = m.Date } out = append(out, contractDocument{ ID: contractdocs.KindAVV, Kind: contractdocs.KindAVV, Title: contractdocs.Title(contractdocs.KindAVV), Version: own.Version, Date: date, SHA256: own.SHA256, TenantSpecific: true, FilledFrom: "staff", own: own, }) } slices.SortStableFunc(out, func(a, b contractDocument) int { return contractKindOrder[a.Kind] - contractKindOrder[b.Kind] }) return out, nil } var berlin = func() *time.Location { if loc, err := time.LoadLocation("Europe/Berlin"); err == nil { return loc } return time.FixedZone("CET", 3600) }() // tenantContractDocumentPDF is GET /v1/tenants/{id}/contracts/documents/{file} // with file ".pdf": the document as the overview lists it for this // tenant, byte for byte after its digest matched. func (s *Server) tenantContractDocumentPDF(w http.ResponseWriter, r *http.Request) { id, isPDF := strings.CutSuffix(r.PathValue("file"), ".pdf") if !isPDF || !s.cfg().ContractDocuments { writeError(w, http.StatusNotFound, "not_found", "no such contract document") return } ctx, cancel := context.WithTimeout(r.Context(), time.Minute) defer cancel() t, ok := s.tenantInScope(ctx, w, r) if !ok { return } docs, err := s.tenantContractDocuments(ctx, t) if err != nil { writeError(w, http.StatusInternalServerError, "internal", err.Error()) return } i := slices.IndexFunc(docs, func(d contractDocument) bool { return d.ID == id }) if i < 0 { writeError(w, http.StatusNotFound, "not_found", "no such contract document") return } d := docs[i] if d.own != nil { if !s.documentsReady(w) { return } s.serveVerified(ctx, w, d.own.ObjectKey, d.own.SHA256, "application/pdf", "Breakpilot_Auftragsverarbeitungsvertrag_"+d.own.Version+".pdf") return } if d.filled != nil { // The filled AVV is the master plus an update: the master's pin // holds for its first bytes. if contractdocs.Sum(d.master.PDF) != d.master.SHA256 || !bytes.HasPrefix(d.filled, d.master.PDF) { s.Log.Error("filled AVV does not start with its pinned master", "tenant_id", t.ID, "version", d.Version) writeError(w, http.StatusInternalServerError, "digest_mismatch", "the document does not match its digest; it is not served") return } h := w.Header() h.Set("Content-Type", "application/pdf") h.Set("Content-Disposition", inlineDisposition("Breakpilot_Auftragsverarbeitungsvertrag_"+d.Version+".pdf")) h.Set("Content-Length", strconv.Itoa(len(d.filled))) h.Set("ETag", `"`+d.SHA256+`"`) h.Set("X-Content-SHA256", d.SHA256) h.Set("X-Content-Type-Options", "nosniff") h.Set("Cache-Control", "private, no-cache") _, _ = w.Write(d.filled) return } if contractdocs.Sum(d.master.PDF) != d.master.SHA256 { s.Log.Error("contract document does not match its pin", "document", d.ID, "version", d.Version) writeError(w, http.StatusInternalServerError, "digest_mismatch", "the document does not match its digest; it is not served") return } h := w.Header() h.Set("Content-Type", "application/pdf") h.Set("Content-Disposition", inlineDisposition(d.master.File)) h.Set("Content-Length", strconv.Itoa(len(d.master.PDF))) h.Set("ETag", `"`+d.SHA256+`"`) h.Set("X-Content-SHA256", d.SHA256) h.Set("X-Content-Type-Options", "nosniff") h.Set("Cache-Control", "private, max-age=3600") _, _ = w.Write(d.master.PDF) } // ─── the filled AVV (staff) ──────────────────────────────────────────────── // avvValues are the customer's details the AVV master leaves blank: the // Auftraggeber's name, address, who represents it, and who gives // instructions. ValuesSHA256 is the SHA-256 of the JSON object of the four // fields in this order, for X-Values-SHA256 of the upload. type avvValues struct { Name string `json:"ag_name"` Anschrift string `json:"ag_anschrift"` Vertreten string `json:"ag_vertreten"` Weisung string `json:"ag_weisung"` ValuesSHA256 string `json:"values_sha256"` } // countryNames are the company profile's country codes (portal schema // companyProfile.ts, HQ_COUNTRY) as they appear in a contract. var countryNames = map[string]string{ "AT": "Österreich", "CH": "Schweiz", "LI": "Liechtenstein", "LU": "Luxemburg", "NL": "Niederlande", "FR": "Frankreich", "IT": "Italien", } // adminAVVValues is GET /v1/admin/tenants/{id}/avv-values. The values are // the customer's data: they are answered, never logged or audited. func (s *Server) adminAVVValues(w http.ResponseWriter, r *http.Request) { if _, _, ok := s.staffActor(r); !ok { writeError(w, http.StatusForbidden, "staff_only", "only a staff member (X-Staff-Subject) may read the AVV details") return } ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) defer cancel() t, ok := s.tenantInScope(ctx, w, r) if !ok { return } v, _, err := s.avvDetails(ctx, t) if errors.Is(err, errRoleDatasetUnreadable) { writeError(w, http.StatusInternalServerError, "internal", "the role dataset could not be read") return } if errors.Is(err, errProfileUnreadable) { writeError(w, http.StatusInternalServerError, "internal", "the company profile could not be read") return } if err != nil { s.writeKeycloakError(w, t.ID, "list members for the AVV", err) return } v.ValuesSHA256 = avvValuesDigest(v) writeJSON(w, http.StatusOK, v) } var errProfileUnreadable = errors.New("company profile unreadable") // Why a workspace's AVV is still the blank master. const ( avvMissingProfile = "profile" // the company profile is not submitted avvMissingName = "company_name" // no company name in it avvMissingAddress = "address" // street, postcode or city missing avvMissingManagement = "management" // nobody named as Geschäftsleitung (Verantwortliche) avvMissingManual = "manual" // the details do not fit the form; staff fill it in ) // avvDetails are the customer's details for the AVV, from the company // profile and the role dataset, and what is missing for an automatic fill. // The Weisung line names the function, Geschäftsleitung (owner 19.11.2026). func (s *Server) avvDetails(ctx context.Context, t *store.Tenant) (avvValues, []string, error) { var v avvValues var missing []string profile, submitted, err := s.companyProfile(ctx, t.ID) if err != nil { return v, nil, errProfileUnreadable } if !submitted { missing = append(missing, avvMissingProfile) } v.Name = companyWithLegalForm(profile["companyName"], profile["legalForm"]) if v.Name == "" { missing = append(missing, avvMissingName) } v.Anschrift = joinNonEmpty(", ", profile["headquartersStreet"], joinNonEmpty(" ", profile["headquartersZip"], profile["headquartersCity"]), profileCountry(profile["headquartersCountry"], profile["headquartersCountryOther"])) if profile["headquartersStreet"] == "" || profile["headquartersZip"] == "" || profile["headquartersCity"] == "" { missing = append(missing, avvMissingAddress) } v.Weisung = "Geschäftsleitung" names, err := s.managementNames(ctx, t) if err != nil { return v, nil, err } v.Vertreten = germanList(names) if v.Vertreten == "" { missing = append(missing, avvMissingManagement) } v.ValuesSHA256 = avvValuesDigest(v) return v, missing, nil } // fillAVV makes doc, the AVV master's entry, the master filled with the // workspace's details when they are complete, or names what is missing. A // failure to read the details leaves the plain master: the overview still // lists everything else. The details are the customer's data: never logged. func (s *Server) fillAVV(ctx context.Context, t *store.Tenant, doc *contractDocument) { v, missing, err := s.avvDetails(ctx, t) if err != nil { s.Log.Warn("AVV details unreadable; listing the blank master", "tenant_id", t.ID, "err", err) return } if len(missing) > 0 { doc.Missing = missing return } pdf, err := filledAVV(doc.master, v) if err != nil { // Not a value: only which rule refused it (too long, character set). s.Log.Warn("AVV not filled automatically; staff must fill it", "tenant_id", t.ID, "version", doc.Version, "reason", err) doc.Missing = []string{avvMissingManual} return } doc.filled = pdf doc.SHA256 = contractdocs.Sum(pdf) doc.TenantSpecific = true doc.FilledFrom = "profile" } // filledAVVs caches filled AVVs by master and details digest: the fill is // deterministic, so a hit is the same bytes. var filledAVVs = struct { sync.Mutex m map[string][]byte }{m: map[string][]byte{}} func filledAVV(master *contractdocs.Doc, v avvValues) ([]byte, error) { key := master.SHA256 + "/" + v.ValuesSHA256 filledAVVs.Lock() pdf, ok := filledAVVs.m[key] filledAVVs.Unlock() if ok { return pdf, nil } pdf, err := avvfill.Fill(master.PDF, avvfill.Values{Name: v.Name, Anschrift: v.Anschrift, Vertreten: v.Vertreten, Weisung: v.Weisung}) if err != nil { return nil, err } filledAVVs.Lock() if len(filledAVVs.m) >= 256 { clear(filledAVVs.m) } filledAVVs.m[key] = pdf filledAVVs.Unlock() return pdf, nil } func avvValuesDigest(v avvValues) string { b, _ := json.Marshal(struct { Name string `json:"ag_name"` Anschrift string `json:"ag_anschrift"` Vertreten string `json:"ag_vertreten"` Weisung string `json:"ag_weisung"` }{v.Name, v.Anschrift, v.Vertreten, v.Weisung}) h := sha256.Sum256(b) return hex.EncodeToString(h[:]) } // companyProfile returns the text answers of the profile's company_profile // section, trimmed (empty when there is no profile), and whether the profile // is submitted. func (s *Server) companyProfile(ctx context.Context, tenantID string) (map[string]string, bool, error) { out := map[string]string{} p, err := s.Store.GetCompanyProfile(ctx, tenantID) if errors.Is(err, store.ErrNotFound) { return out, false, nil } if err != nil { return nil, false, err } submitted := p.Status == store.ProfileSubmitted var doc struct { Sections struct { CompanyProfile map[string]json.RawMessage `json:"company_profile"` } `json:"sections"` } if json.Unmarshal(p.Data, &doc) != nil { return out, submitted, nil } for k, raw := range doc.Sections.CompanyProfile { var str string if json.Unmarshal(raw, &str) == nil { out[k] = strings.TrimSpace(str) } } return out, submitted, nil } // legalFormNames are the company profile's legal forms (portal schema // companyProfile.ts, LEGAL_FORM) as written after the company name; the // first is the form's label, the others are spellings that count as already // written. "Einzelunternehmen" and "Sonstige" are not appended; the e.V. is // written without the form's "(Verein)". var legalFormNames = map[string][]string{ "gbr": {"GbR"}, "ohg": {"OHG"}, "kg": {"KG"}, "gmbh": {"GmbH"}, "ug": {"UG (haftungsbeschränkt)", "UG"}, "ag": {"AG"}, "gmbh_co_kg": {"GmbH & Co. KG"}, "ev": {"e.V."}, "stiftung": {"Stiftung"}, } // companyWithLegalForm is the company name with its legal form ("Muster // GmbH"), unless the name already ends with it (case-insensitive), the form // is not appended, or there is no name. func companyWithLegalForm(name, form string) string { names := legalFormNames[form] if name == "" || len(names) == 0 { return name } // Spaces do not count: "UG(haftungsbeschränkt)" is the UG already. squash := func(x string) string { return strings.ToLower(strings.ReplaceAll(x, " ", "")) } for _, n := range names { if strings.HasSuffix(squash(name), squash(n)) { return name } } return name + " " + names[0] } // profileCountry is the country as written in the address: none for // Germany, the name for a listed code, the free text for "other". func profileCountry(code, other string) string { switch { case code == "other": code = other case countryNames[code] != "": return countryNames[code] } if c := strings.ToLower(code); c == "de" || c == "deutschland" { return "" } return code } var errRoleDatasetUnreadable = errors.New("role dataset unreadable") // managementNames are the holders of the management function // (r1.geschaeftsleitung) in the role dataset, by name: members as the portal // shows them (first and last name, else e-mail), external persons by name. func (s *Server) managementNames(ctx context.Context, t *store.Tenant) ([]string, error) { _, ds, err := s.currentRoleDataset(ctx, t.ID) if err != nil { return nil, errRoleDatasetUnreadable } var holders []roles.Holder needMembers := false for _, a := range ds.Assignments { if a.Function == roles.Management { holders = append(holders, a.Holder) needMembers = needMembers || a.Holder.Kind == roles.HolderMember } } byID := map[string]keycloak.OrgMember{} if needMembers { members, err := s.Keycloak.ListOrgMembers(ctx, t.Slug) if err != nil && !errors.Is(err, keycloak.ErrOrgNotFound) { return nil, err } for _, m := range members { byID[m.UserID] = m } } var names []string for _, h := range holders { name := "" switch h.Kind { case roles.HolderMember: if m, ok := byID[h.Sub]; ok { name = firstNonEmpty(joinNonEmpty(" ", strings.TrimSpace(m.FirstName), strings.TrimSpace(m.LastName)), m.Email) } case roles.HolderExternal: name = firstNonEmpty(strings.TrimSpace(h.Name), strings.TrimSpace(h.Organisation)) } if name != "" && !slices.Contains(names, name) { names = append(names, name) } } return names, nil } // germanList joins names as a German sentence does: "A", "A und B", // "A, B und C". func germanList(names []string) string { if len(names) < 2 { return strings.Join(names, "") } return strings.Join(names[:len(names)-1], ", ") + " und " + names[len(names)-1] } func joinNonEmpty(sep string, parts ...string) string { var out []string for _, p := range parts { if p != "" { out = append(out, p) } } return strings.Join(out, sep) } var hexSHA256 = regexp.MustCompile(`^[0-9a-f]{64}$`) // adminPutAVV is PUT /v1/admin/tenants/{id}/contract-documents/avv: staff // upload the AVV filled in for this tenant (body: the PDF, at most 5 MB; // X-Document-Version: the master's version; X-Values-SHA256: the digest of // the details filled in, as avv-values answers it). It becomes the tenant's // current AVV; earlier ones stay in the bucket and the table. func (s *Server) adminPutAVV(w http.ResponseWriter, r *http.Request) { staff, _, ok := s.staffActor(r) if !ok { writeError(w, http.StatusForbidden, "staff_only", "only a staff member (X-Staff-Subject) may upload a contract document") return } if !s.documentsReady(w) { return } version := strings.TrimSpace(r.Header.Get("X-Document-Version")) if !contractdocs.ValidVersion(version) { writeError(w, http.StatusBadRequest, "invalid_version", "X-Document-Version must be the master's version, e.g. 1.0.0") return } valuesSHA := strings.ToLower(strings.TrimSpace(r.Header.Get("X-Values-SHA256"))) if !hexSHA256.MatchString(valuesSHA) { writeError(w, http.StatusBadRequest, "invalid_values_sha256", "X-Values-SHA256 must be a hex SHA-256") return } ctx, cancel := context.WithTimeout(r.Context(), time.Minute) defer cancel() t, ok := s.tenantInScope(ctx, w, r) if !ok { return } body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxContractPDFBytes)) if err != nil { if isTooLarge(err) { writeError(w, http.StatusRequestEntityTooLarge, "too_large", "the PDF exceeds 5 MB") return } writeError(w, http.StatusBadRequest, "invalid_body", "the PDF could not be read") return } if !bytes.HasPrefix(body, []byte("%PDF")) { writeError(w, http.StatusUnsupportedMediaType, "not_a_pdf", "the body must be a PDF") return } key := "tenants/" + t.ID + "/contracts/avv/" + uuid.NewString() + ".pdf" if err := s.Objects.Put(ctx, key, bytes.NewReader(body), int64(len(body)), "application/pdf"); err != nil { s.Log.Error("contract document: store failed", "tenant_id", t.ID, "err", err) writeError(w, http.StatusBadGateway, "storage_failed", "the PDF could not be stored") return } sum := sha256.Sum256(body) row, err := s.Store.CreateContractDocument(ctx, store.ContractDocument{ TenantID: t.ID, Kind: store.ContractDocumentAVV, Version: version, SHA256: hex.EncodeToString(sum[:]), ObjectKey: key, ValuesSHA256: valuesSHA, CreatedBy: staff, CreatedAt: s.now(), }) if err != nil { _ = s.Objects.Delete(context.WithoutCancel(ctx), key) if mapStoreError(w, err) { return } writeError(w, http.StatusInternalServerError, "internal", err.Error()) return } s.emitAudit(ctx, r, store.AuditEvent{ TenantID: t.ID, Action: "contract_document.uploaded", TargetID: strconv.FormatInt(row.ID, 10), TargetType: "contract_document", TargetName: contractdocs.Title(contractdocs.KindAVV), ActorType: "staff", Metadata: map[string]interface{}{"kind": row.Kind, "version": row.Version, "sha256": row.SHA256, "values_sha256": row.ValuesSHA256}, }) writeJSON(w, http.StatusCreated, row) }