Migration 0021 (company_profiles + company_profile_revisions), GET/PUT /v1/tenants/{id}/company-profile, POST …/submit with optimistic revisions (409 + current revision; unchanged saves are no new revision), staff import via /v1/admin/tenants/{id}/company-profile (named staff member only), outline validation of the form document, audit without answers, OpenAPI.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
262 lines
8.3 KiB
Go
262 lines
8.3 KiB
Go
package server
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"time"
|
|
|
|
"git.breakpilot.com/platform/tenant-registry/internal/store"
|
|
)
|
|
|
|
// Unternehmensprofil (0021, decided 2026-10-20): the portal's onboarding
|
|
// form, one document per tenant, kept as the form writes it. The registry is
|
|
// the authority and versions every state; the portal owns the form's schema
|
|
// and checks the answers against it, and it checks the user's org role
|
|
// (IT_ADMIN, CXO, LEGAL write) as it does for projects. Staff import a
|
|
// customer's existing profile from the admin area.
|
|
//
|
|
// GET /v1/tenants/{id}/company-profile (tenants.read; 404 when none)
|
|
// PUT /v1/tenants/{id}/company-profile (tenants.write) save
|
|
// POST /v1/tenants/{id}/company-profile/submit (tenants.write) submit
|
|
// GET /v1/admin/tenants/{id}/company-profile (admin)
|
|
// PUT /v1/admin/tenants/{id}/company-profile (admin, staff only) import
|
|
|
|
// maxProfileBytes caps a profile document: the full form is a few KB.
|
|
const maxProfileBytes = 256 << 10
|
|
|
|
type profileSaveReq struct {
|
|
Data json.RawMessage `json:"data"`
|
|
SchemaVersion string `json:"schema_version"`
|
|
ExpectedRevision *int `json:"expected_revision"`
|
|
}
|
|
|
|
type profileSubmitReq struct {
|
|
ExpectedRevision *int `json:"expected_revision"`
|
|
}
|
|
|
|
type profileConflict struct {
|
|
Error string `json:"error"`
|
|
Message string `json:"message"`
|
|
CurrentRevision int `json:"current_revision"`
|
|
}
|
|
|
|
// getCompanyProfile is GET /v1/tenants/{id}/company-profile and the admin GET.
|
|
func (s *Server) getCompanyProfile(w http.ResponseWriter, r *http.Request) {
|
|
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
|
|
defer cancel()
|
|
t, ok := s.tenantInScope(ctx, w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
p, err := s.Store.GetCompanyProfile(ctx, t.ID)
|
|
if err != nil {
|
|
s.writeProfileError(w, err)
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, p)
|
|
}
|
|
|
|
// saveCompanyProfile is PUT /v1/tenants/{id}/company-profile.
|
|
func (s *Server) saveCompanyProfile(w http.ResponseWriter, r *http.Request) {
|
|
s.writeCompanyProfile(w, r, store.ProfileSourcePortal)
|
|
}
|
|
|
|
// importCompanyProfile is PUT /v1/admin/tenants/{id}/company-profile: staff
|
|
// bring in a profile the customer filled in elsewhere. Only a named staff
|
|
// member may, so the history says who imported it.
|
|
func (s *Server) importCompanyProfile(w http.ResponseWriter, r *http.Request) {
|
|
if _, _, ok := s.staffActor(r); !ok {
|
|
writeError(w, http.StatusForbidden, "staff_only", "an import needs a staff member (X-Staff-Subject)")
|
|
return
|
|
}
|
|
s.writeCompanyProfile(w, r, store.ProfileSourceImport)
|
|
}
|
|
|
|
func (s *Server) writeCompanyProfile(w http.ResponseWriter, r *http.Request, source string) {
|
|
r.Body = http.MaxBytesReader(w, r.Body, maxProfileBytes+4096)
|
|
var in profileSaveReq
|
|
if !decodeJSON(w, r, &in) {
|
|
return
|
|
}
|
|
if in.ExpectedRevision == nil {
|
|
writeError(w, http.StatusBadRequest, "expected_revision_required", "expected_revision is required (0 when there is no profile yet)")
|
|
return
|
|
}
|
|
if n := len(in.SchemaVersion); n < 1 || n > 40 {
|
|
writeError(w, http.StatusBadRequest, "invalid_schema_version", "schema_version must be 1..40 characters")
|
|
return
|
|
}
|
|
if len(in.Data) > maxProfileBytes {
|
|
writeError(w, http.StatusRequestEntityTooLarge, "too_large", "profile document exceeds 256 KiB")
|
|
return
|
|
}
|
|
if msg := validateProfileDocument(in.Data); msg != "" {
|
|
writeError(w, http.StatusBadRequest, "invalid_profile", msg)
|
|
return
|
|
}
|
|
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
|
|
defer cancel()
|
|
t, ok := s.tenantInScope(ctx, w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
actor := s.projectActor(r)
|
|
p, changed, err := s.Store.SaveCompanyProfile(ctx, store.CompanyProfileWrite{
|
|
TenantID: t.ID, Data: in.Data, SchemaVersion: in.SchemaVersion, ExpectedRevision: *in.ExpectedRevision,
|
|
Source: source, By: actor, At: time.Now(),
|
|
})
|
|
if err != nil {
|
|
s.writeProfileError(w, err)
|
|
return
|
|
}
|
|
if changed {
|
|
action := "company_profile.saved"
|
|
if source == store.ProfileSourceImport {
|
|
action = "company_profile.imported"
|
|
}
|
|
// The answers stay out of the audit log; the revision points to them.
|
|
s.emitAudit(ctx, r, store.AuditEvent{
|
|
TenantID: t.ID, Action: action, TargetID: t.ID, TargetType: "company_profile", TargetName: "Unternehmensprofil",
|
|
ActorType: s.projectActorType(r), ActorName: actor,
|
|
Metadata: map[string]interface{}{"revision": p.Revision, "schema_version": p.SchemaVersion},
|
|
})
|
|
}
|
|
writeJSON(w, http.StatusOK, p)
|
|
}
|
|
|
|
// submitCompanyProfile is POST /v1/tenants/{id}/company-profile/submit. The
|
|
// portal only offers it once every required answer is given.
|
|
func (s *Server) submitCompanyProfile(w http.ResponseWriter, r *http.Request) {
|
|
var in profileSubmitReq
|
|
if !decodeJSON(w, r, &in) {
|
|
return
|
|
}
|
|
if in.ExpectedRevision == nil {
|
|
writeError(w, http.StatusBadRequest, "expected_revision_required", "expected_revision is required")
|
|
return
|
|
}
|
|
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
|
|
defer cancel()
|
|
t, ok := s.tenantInScope(ctx, w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
actor := s.projectActor(r)
|
|
p, err := s.Store.SubmitCompanyProfile(ctx, t.ID, *in.ExpectedRevision, actor, time.Now())
|
|
if err != nil {
|
|
s.writeProfileError(w, err)
|
|
return
|
|
}
|
|
s.emitAudit(ctx, r, store.AuditEvent{
|
|
TenantID: t.ID, Action: "company_profile.submitted", TargetID: t.ID, TargetType: "company_profile", TargetName: "Unternehmensprofil",
|
|
ActorType: s.projectActorType(r), ActorName: actor, Metadata: map[string]interface{}{"revision": p.Revision},
|
|
})
|
|
writeJSON(w, http.StatusOK, p)
|
|
}
|
|
|
|
func (s *Server) writeProfileError(w http.ResponseWriter, err error) {
|
|
var rc *store.RevisionConflict
|
|
if errors.As(err, &rc) {
|
|
writeJSON(w, http.StatusConflict, profileConflict{
|
|
Error: "revision_conflict", CurrentRevision: rc.Current,
|
|
Message: fmt.Sprintf("the profile was changed in the meantime (current revision %d); reload it", rc.Current),
|
|
})
|
|
return
|
|
}
|
|
if mapStoreError(w, err) {
|
|
return
|
|
}
|
|
writeError(w, http.StatusInternalServerError, "internal", err.Error())
|
|
}
|
|
|
|
// The form's document, as the portal (and the workspace prototype before it)
|
|
// writes it. Only its outline is checked here; the fields and their options
|
|
// are the portal's schema.
|
|
var (
|
|
profileTopKeys = map[string]bool{
|
|
"audience": true, "clientRef": true, "sections": true, "documents": true, "suggested": true, "lastStep": true,
|
|
}
|
|
profileSections = map[string]bool{"company_profile": true, "compliance_scope": true, "ai_act": true}
|
|
)
|
|
|
|
// validateProfileDocument returns "" for a well-formed document, else what is
|
|
// wrong with it.
|
|
func validateProfileDocument(raw json.RawMessage) string {
|
|
var doc map[string]json.RawMessage
|
|
if err := json.Unmarshal(raw, &doc); err != nil || doc == nil {
|
|
return "data must be a JSON object"
|
|
}
|
|
for k := range doc {
|
|
if !profileTopKeys[k] {
|
|
return fmt.Sprintf("unknown key %q", k)
|
|
}
|
|
}
|
|
if a, ok := doc["audience"]; ok {
|
|
var v *string
|
|
if json.Unmarshal(a, &v) != nil || (v != nil && *v != "own_company") {
|
|
return `audience must be "own_company" or null`
|
|
}
|
|
}
|
|
for _, k := range []string{"clientRef", "lastStep"} {
|
|
if v, ok := doc[k]; ok {
|
|
var str string
|
|
if json.Unmarshal(v, &str) != nil || len(str) > 200 {
|
|
return k + " must be a string of at most 200 characters"
|
|
}
|
|
}
|
|
}
|
|
if v, ok := doc["suggested"]; ok {
|
|
var ids []string
|
|
if json.Unmarshal(v, &ids) != nil {
|
|
return "suggested must be a list of field ids"
|
|
}
|
|
}
|
|
if v, ok := doc["documents"]; ok {
|
|
var docs []map[string]any
|
|
if json.Unmarshal(v, &docs) != nil {
|
|
return "documents must be a list of objects"
|
|
}
|
|
}
|
|
rawSections, ok := doc["sections"]
|
|
if !ok {
|
|
return "sections is required"
|
|
}
|
|
var sections map[string]map[string]json.RawMessage
|
|
if json.Unmarshal(rawSections, §ions) != nil || sections == nil {
|
|
return "sections must be an object of sections"
|
|
}
|
|
for name, answers := range sections {
|
|
if !profileSections[name] {
|
|
return fmt.Sprintf("unknown section %q", name)
|
|
}
|
|
for field, v := range answers {
|
|
if !validAnswer(v) {
|
|
return fmt.Sprintf("%s.%s: an answer is text, a number, yes/no, a list of texts or empty", name, field)
|
|
}
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func validAnswer(v json.RawMessage) bool {
|
|
var x any
|
|
if json.Unmarshal(v, &x) != nil {
|
|
return false
|
|
}
|
|
switch val := x.(type) {
|
|
case nil, string, float64, bool:
|
|
return true
|
|
case []any:
|
|
for _, e := range val {
|
|
if _, ok := e.(string); !ok {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
return false
|
|
}
|