feat(company-profile): Unternehmensprofil per tenant, registry as the authority (#85)
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>
This commit was merged in pull request #85.
This commit is contained in:
1 parent
f024a4042d
commit
174a2f1e01
13 files changed
+1020
No files matched your search
@@ -0,0 +1,261 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package server_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/store"
|
||||
)
|
||||
|
||||
// The store contract on both stores: revisions, the unchanged save, conflicts
|
||||
// with the current revision, submit, and a document that survives JSONB.
|
||||
func TestCompanyProfileStore(t *testing.T) {
|
||||
eachStore(t, func(t *testing.T, h *testHarness) {
|
||||
ctx := context.Background()
|
||||
doc := json.RawMessage(`{"audience":"own_company","sections":{"company_profile":{"companyName":"Muster","industry":["Robotik","Maschinenbau"],"foundedYear":2001,"legalNote":null},"compliance_scope":{"data_hr":true},"ai_act":{}},"documents":[],"suggested":["data_hr"]}`)
|
||||
write := func(data json.RawMessage, expected int) (*store.CompanyProfile, bool, error) {
|
||||
return h.store.SaveCompanyProfile(ctx, store.CompanyProfileWrite{
|
||||
TenantID: h.tenant.ID, Data: data, SchemaVersion: "v2", ExpectedRevision: expected,
|
||||
Source: store.ProfileSourcePortal, By: "a@acme.test", At: time.Now(),
|
||||
})
|
||||
}
|
||||
|
||||
if _, err := h.store.GetCompanyProfile(ctx, h.tenant.ID); !errors.Is(err, store.ErrNotFound) {
|
||||
t.Fatalf("none yet: %v", err)
|
||||
}
|
||||
p, changed, err := write(doc, 0)
|
||||
if err != nil || !changed || p.Revision != 1 || p.Status != store.ProfileDraft || p.UpdatedBy != "a@acme.test" {
|
||||
t.Fatalf("first save: %+v %v %v", p, changed, err)
|
||||
}
|
||||
if mustCanon(t, p.Data) != mustCanon(t, doc) {
|
||||
t.Fatalf("document changed on the way:\n%s\n%s", p.Data, doc)
|
||||
}
|
||||
|
||||
// Same answers in another key order: no new revision.
|
||||
reordered := json.RawMessage(`{"suggested":["data_hr"],"documents":[],"sections":{"ai_act":{},"compliance_scope":{"data_hr":true},"company_profile":{"legalNote":null,"foundedYear":2001,"industry":["Robotik","Maschinenbau"],"companyName":"Muster"}},"audience":"own_company"}`)
|
||||
if p, changed, err := write(reordered, 1); err != nil || changed || p.Revision != 1 {
|
||||
t.Fatalf("unchanged save: %+v %v %v", p, changed, err)
|
||||
}
|
||||
var rc *store.RevisionConflict
|
||||
if _, _, err := write(json.RawMessage(`{"sections":{}}`), 0); !errors.As(err, &rc) || rc.Current != 1 || !errors.Is(err, store.ErrConflict) {
|
||||
t.Fatalf("stale save: %v", err)
|
||||
}
|
||||
if _, err := h.store.SubmitCompanyProfile(ctx, h.tenant.ID, 5, "a@acme.test", time.Now()); !errors.As(err, &rc) || rc.Current != 1 {
|
||||
t.Fatalf("stale submit: %v", err)
|
||||
}
|
||||
p, err = h.store.SubmitCompanyProfile(ctx, h.tenant.ID, 1, "b@acme.test", time.Now())
|
||||
if err != nil || p.Revision != 2 || p.Status != store.ProfileSubmitted || p.SubmittedBy != "b@acme.test" || p.SubmittedAt == nil {
|
||||
t.Fatalf("submit: %+v %v", p, err)
|
||||
}
|
||||
p, changed, err = write(json.RawMessage(`{"sections":{"company_profile":{"companyName":"Muster AG"}}}`), 2)
|
||||
if err != nil || !changed || p.Revision != 3 || p.Status != store.ProfileSubmitted {
|
||||
t.Fatalf("edit after submit: %+v %v %v", p, changed, err)
|
||||
}
|
||||
if _, _, err := h.store.SaveCompanyProfile(ctx, store.CompanyProfileWrite{
|
||||
TenantID: "00000000-0000-0000-0000-00000000beef", Data: doc, SchemaVersion: "v2", Source: store.ProfileSourcePortal, At: time.Now(),
|
||||
}); !errors.Is(err, store.ErrNotFound) {
|
||||
t.Fatalf("unknown tenant: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func mustCanon(t *testing.T, raw json.RawMessage) string {
|
||||
t.Helper()
|
||||
var v any
|
||||
if err := json.Unmarshal(raw, &v); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, _ := json.Marshal(v)
|
||||
return string(b)
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/authn"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/store"
|
||||
)
|
||||
|
||||
// A profile as the form writes it: values, a list, yes/no, empty, and three
|
||||
// unconfirmed suggestions.
|
||||
const profileDoc = `{"audience":"own_company","sections":{"company_profile":{"companyName":"Muster","legalForm":"gmbh","industry":["Maschinenbau","Robotik"],"foundedYear":2001},"compliance_scope":{"data_hr":true,"data_communication":true,"data_financial":true,"uses_tracking":false,"cloud_providers":null},"ai_act":{}},"documents":[],"suggested":["data_hr","data_communication","data_financial"],"lastStep":"company_profile"}`
|
||||
|
||||
func profileBody(doc string, expected int) string {
|
||||
return `{"schema_version":"onboarding-product-v2","expected_revision":` + itoa(expected) + `,"data":` + doc + `}`
|
||||
}
|
||||
|
||||
func itoa(n int) string { b, _ := json.Marshal(n); return string(b) }
|
||||
|
||||
func TestCompanyProfileLifecycle(t *testing.T) {
|
||||
f := newTeamFixture(t, portal, "portal-svc:*")
|
||||
path := "/v1/tenants/" + f.tenant.ID + "/company-profile"
|
||||
user := map[string]string{"X-Portal-User-Email": "cxo@acme.test"}
|
||||
|
||||
if code, _, _ := f.call(t, "GET", path, "", nil); code != http.StatusNotFound {
|
||||
t.Fatalf("no profile yet: %d", code)
|
||||
}
|
||||
if code, _, raw := f.call(t, "PUT", path, `{"schema_version":"v2","data":`+profileDoc+`}`, user); code != http.StatusBadRequest || !strings.Contains(raw, "expected_revision_required") {
|
||||
t.Fatalf("without expected_revision: %d %s", code, raw)
|
||||
}
|
||||
|
||||
code, _, raw := f.call(t, "PUT", path, profileBody(profileDoc, 0), user)
|
||||
if code != http.StatusOK {
|
||||
t.Fatalf("first save: %d %s", code, raw)
|
||||
}
|
||||
var p store.CompanyProfile
|
||||
_ = json.Unmarshal([]byte(raw), &p)
|
||||
if p.Revision != 1 || p.Status != store.ProfileDraft || p.UpdatedBy != "cxo@acme.test" || p.SchemaVersion != "onboarding-product-v2" {
|
||||
t.Fatalf("saved: %+v", p)
|
||||
}
|
||||
|
||||
// Read back: the same document, suggestions included.
|
||||
_, _, raw = f.call(t, "GET", path, "", nil)
|
||||
_ = json.Unmarshal([]byte(raw), &p)
|
||||
var got, want any
|
||||
_ = json.Unmarshal(p.Data, &got)
|
||||
_ = json.Unmarshal([]byte(profileDoc), &want)
|
||||
if !sameValue(got, want) {
|
||||
t.Fatalf("stored document differs:\n got %s\nwant %s", p.Data, profileDoc)
|
||||
}
|
||||
|
||||
// Saving the same answers again (autosave) is not a new revision.
|
||||
if code, _, raw := f.call(t, "PUT", path, profileBody(profileDoc, 1), user); code != http.StatusOK || !strings.Contains(raw, `"revision":1`) {
|
||||
t.Fatalf("unchanged save: %d %s", code, raw)
|
||||
}
|
||||
// A writer that has not seen revision 1 is refused, with the revision to reload.
|
||||
changed := strings.Replace(profileDoc, `"Muster"`, `"Muster AG"`, 1)
|
||||
if code, _, raw := f.call(t, "PUT", path, profileBody(changed, 0), user); code != http.StatusConflict || !strings.Contains(raw, `"current_revision":1`) {
|
||||
t.Fatalf("stale save: %d %s", code, raw)
|
||||
}
|
||||
|
||||
// Submit, then keep editing: the profile stays submitted.
|
||||
if code, _, raw := f.call(t, "POST", path+"/submit", `{"expected_revision":0}`, user); code != http.StatusConflict {
|
||||
t.Fatalf("stale submit: %d %s", code, raw)
|
||||
}
|
||||
code, _, raw = f.call(t, "POST", path+"/submit", `{"expected_revision":1}`, user)
|
||||
_ = json.Unmarshal([]byte(raw), &p)
|
||||
if code != http.StatusOK || p.Revision != 2 || p.Status != store.ProfileSubmitted || p.SubmittedBy != "cxo@acme.test" || p.SubmittedAt == nil {
|
||||
t.Fatalf("submit: %d %s", code, raw)
|
||||
}
|
||||
code, _, raw = f.call(t, "PUT", path, profileBody(changed, 2), user)
|
||||
_ = json.Unmarshal([]byte(raw), &p)
|
||||
if code != http.StatusOK || p.Revision != 3 || p.Status != store.ProfileSubmitted {
|
||||
t.Fatalf("edit after submit: %d %s", code, raw)
|
||||
}
|
||||
|
||||
revs := f.s.Store.(*store.Memory).CompanyProfileRevisions(f.tenant.ID)
|
||||
if len(revs) != 3 || revs[0].Status != store.ProfileDraft || revs[1].Status != store.ProfileSubmitted || revs[2].Revision != 3 {
|
||||
t.Fatalf("history: %+v", revs)
|
||||
}
|
||||
saved, submitted := f.audit(t, "company_profile.saved"), f.audit(t, "company_profile.submitted")
|
||||
if len(saved) != 2 || len(submitted) != 1 {
|
||||
t.Fatalf("audit: %d saved, %d submitted", len(saved), len(submitted))
|
||||
}
|
||||
for _, e := range append(saved, submitted...) {
|
||||
if b, _ := json.Marshal(e.Metadata); strings.Contains(string(b), "Muster") {
|
||||
t.Fatalf("answers leaked into the audit log: %s", b)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompanyProfileRejectsMalformedDocuments(t *testing.T) {
|
||||
f := newTeamFixture(t, portal, "portal-svc:*")
|
||||
path := "/v1/tenants/" + f.tenant.ID + "/company-profile"
|
||||
for name, doc := range map[string]string{
|
||||
"not an object": `[1,2]`,
|
||||
"unknown key": `{"sections":{},"facts":{}}`,
|
||||
"client audience": `{"audience":"client","sections":{}}`,
|
||||
"no sections": `{"audience":"own_company"}`,
|
||||
"unknown section": `{"sections":{"pricing":{}}}`,
|
||||
"nested answer": `{"sections":{"company_profile":{"address":{"street":"x"}}}}`,
|
||||
"list of numbers": `{"sections":{"company_profile":{"industry":[1,2]}}}`,
|
||||
"suggested object": `{"sections":{},"suggested":{"a":1}}`,
|
||||
} {
|
||||
if code, _, raw := f.call(t, "PUT", path, profileBody(doc, 0), nil); code != http.StatusBadRequest {
|
||||
t.Errorf("%s: %d %s", name, code, raw)
|
||||
}
|
||||
}
|
||||
big := `{"sections":{"company_profile":{"notes":"` + strings.Repeat("x", maxProfileBytes) + `"}}}`
|
||||
if code, _, _ := f.call(t, "PUT", path, profileBody(big, 0), nil); code == http.StatusOK {
|
||||
t.Error("an oversized document was stored")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompanyProfileImportIsStaffOnly(t *testing.T) {
|
||||
f := newTeamFixture(t, portal, "portal-svc:*")
|
||||
path := "/v1/admin/tenants/" + f.tenant.ID + "/company-profile"
|
||||
staff := map[string]string{"X-Staff-Subject": "staff-1", "X-Staff-Email": "staff@breakpilot.test"}
|
||||
|
||||
if code, _, _ := f.call(t, "PUT", path, profileBody(profileDoc, 0), nil); code != http.StatusForbidden {
|
||||
t.Fatalf("import without a staff member: %d", code)
|
||||
}
|
||||
code, _, raw := f.call(t, "PUT", path, profileBody(profileDoc, 0), staff)
|
||||
if code != http.StatusOK || !strings.Contains(raw, `"status":"draft"`) {
|
||||
t.Fatalf("import: %d %s", code, raw)
|
||||
}
|
||||
if code, _, raw := f.call(t, "GET", path, "", staff); code != http.StatusOK || !strings.Contains(raw, `"revision":1`) {
|
||||
t.Fatalf("admin read: %d %s", code, raw)
|
||||
}
|
||||
ev := f.audit(t, "company_profile.imported")
|
||||
if len(ev) != 1 || ev[0].ActorType != "staff" || ev[0].ActorID != "staff-1" {
|
||||
t.Fatalf("import audit: %+v", ev)
|
||||
}
|
||||
if revs := f.s.Store.(*store.Memory).CompanyProfileRevisions(f.tenant.ID); len(revs) != 1 {
|
||||
t.Fatalf("history after import: %d", len(revs))
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompanyProfileAccess(t *testing.T) {
|
||||
// A product client may read the profile but not write it.
|
||||
product := &authn.Principal{Subject: "svc-pw", ClientID: "pruefwerk-svc"}
|
||||
f := newTeamFixture(t, product, "pruefwerk-svc:tenants.read")
|
||||
path := "/v1/tenants/" + f.tenant.ID + "/company-profile"
|
||||
if code, _, _ := f.call(t, "PUT", path, profileBody(profileDoc, 0), nil); code != http.StatusForbidden {
|
||||
t.Fatalf("product write: %d", code)
|
||||
}
|
||||
if code, _, _ := f.call(t, "GET", path, "", nil); code != http.StatusNotFound {
|
||||
t.Fatalf("product read (none yet): %d", code)
|
||||
}
|
||||
|
||||
// A signed-in user of another tenant does not see it.
|
||||
other := &authn.Principal{Subject: "u-x", ClientID: "portal", TenantID: "00000000-0000-0000-0000-00000000beef"}
|
||||
g := newTeamFixture(t, other)
|
||||
if _, _, err := g.s.Store.SaveCompanyProfile(context.Background(), store.CompanyProfileWrite{
|
||||
TenantID: g.tenant.ID, Data: json.RawMessage(profileDoc), SchemaVersion: "v2", Source: store.ProfileSourcePortal, At: time.Now(),
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if code, _, _ := g.call(t, "GET", "/v1/tenants/"+g.tenant.ID+"/company-profile", "", nil); code != http.StatusNotFound {
|
||||
t.Fatalf("cross-tenant read: %d", code)
|
||||
}
|
||||
// ... while the tenant's own user does.
|
||||
own := &authn.Principal{Subject: "u-a", ClientID: "portal", TenantID: g.tenant.ID}
|
||||
h := newTeamFixture(t, own)
|
||||
if _, _, err := h.s.Store.SaveCompanyProfile(context.Background(), store.CompanyProfileWrite{
|
||||
TenantID: h.tenant.ID, Data: json.RawMessage(profileDoc), SchemaVersion: "v2", Source: store.ProfileSourcePortal, At: time.Now(),
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if code, _, raw := h.call(t, "GET", "/v1/tenants/"+h.tenant.ID+"/company-profile", "", nil); code != http.StatusOK {
|
||||
t.Fatalf("own read: %d %s", code, raw)
|
||||
}
|
||||
}
|
||||
|
||||
func sameValue(a, b any) bool {
|
||||
x, _ := json.Marshal(a)
|
||||
y, _ := json.Marshal(b)
|
||||
return string(x) == string(y)
|
||||
}
|
||||
@@ -84,6 +84,8 @@ func (s *Server) tenantSubresource(w http.ResponseWriter, r *http.Request) {
|
||||
s.listTenantContracts(w, r)
|
||||
case "managed-services":
|
||||
s.listTenantManagedServices(w, r)
|
||||
case "company-profile":
|
||||
s.getCompanyProfile(w, r)
|
||||
default:
|
||||
writeError(w, http.StatusNotFound, "not_found", "no such tenant sub-resource")
|
||||
}
|
||||
|
||||
@@ -139,6 +139,9 @@ func NewRouter(s *Server) http.Handler {
|
||||
mux.HandleFunc("PATCH /v1/tenants/{id}/projects/{pid}", s.updateTenantProject)
|
||||
mux.HandleFunc("DELETE /v1/tenants/{id}/projects/{pid}", s.deleteTenantProject)
|
||||
mux.HandleFunc("GET /v1/tenants/{id}/projects/{pid}/targets", s.listProjectTargets)
|
||||
// Unternehmensprofil (0021): the GET is a {sub} of tenantSubresource.
|
||||
mux.HandleFunc("PUT /v1/tenants/{id}/company-profile", s.saveCompanyProfile)
|
||||
mux.HandleFunc("POST /v1/tenants/{id}/company-profile/submit", s.submitCompanyProfile)
|
||||
|
||||
// entitlements
|
||||
mux.HandleFunc("GET /v1/entitlements", s.listTenantProducts)
|
||||
@@ -194,6 +197,8 @@ func NewRouter(s *Server) http.Handler {
|
||||
mux.HandleFunc("POST /v1/admin/tenants/{id}/preview-grants", s.adminGrantPreview)
|
||||
mux.HandleFunc("DELETE /v1/admin/tenants/{id}/preview-grants/{product}", s.adminRevokePreview)
|
||||
mux.HandleFunc("GET /v1/admin/audit", s.listAudit)
|
||||
mux.HandleFunc("GET /v1/admin/tenants/{id}/company-profile", s.getCompanyProfile)
|
||||
mux.HandleFunc("PUT /v1/admin/tenants/{id}/company-profile", s.importCompanyProfile)
|
||||
mux.HandleFunc("GET /v1/admin/tenants/{id}/documents", s.adminListDocuments)
|
||||
mux.HandleFunc("POST /v1/admin/tenants/{id}/documents", s.adminUploadDocument)
|
||||
mux.HandleFunc("POST /v1/admin/documents/{doc}/publish", s.adminPublishDocument)
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Company profile (0021): the portal's onboarding form ("Unternehmensprofil"
|
||||
// and "Compliance-Umfang") as one JSON document per tenant. The registry is
|
||||
// the authority; the portal owns the schema, so the store keeps the document
|
||||
// as written and only versions it.
|
||||
const (
|
||||
ProfileDraft = "draft"
|
||||
ProfileSubmitted = "submitted"
|
||||
|
||||
ProfileSourcePortal = "portal" // saved from the form
|
||||
ProfileSourceSubmit = "submit" // submitted from the form
|
||||
ProfileSourceImport = "import" // imported by staff
|
||||
)
|
||||
|
||||
type CompanyProfile struct {
|
||||
TenantID string `json:"tenant_id"`
|
||||
Data json.RawMessage `json:"data"`
|
||||
SchemaVersion string `json:"schema_version"`
|
||||
Revision int `json:"revision"`
|
||||
Status string `json:"status"`
|
||||
UpdatedBy string `json:"updated_by"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
SubmittedBy string `json:"submitted_by,omitempty"`
|
||||
SubmittedAt *time.Time `json:"submitted_at,omitempty"`
|
||||
}
|
||||
|
||||
// CompanyProfileWrite is one save. ExpectedRevision is the revision the
|
||||
// writer last read, 0 when it saw no profile: a save never overwrites a state
|
||||
// its writer has not seen.
|
||||
type CompanyProfileWrite struct {
|
||||
TenantID string
|
||||
Data json.RawMessage
|
||||
SchemaVersion string
|
||||
ExpectedRevision int
|
||||
Source string // ProfileSourcePortal or ProfileSourceImport
|
||||
By string
|
||||
At time.Time
|
||||
}
|
||||
|
||||
// RevisionConflict is returned when ExpectedRevision is not the stored
|
||||
// revision (Current, 0 when there is no profile). It matches ErrConflict.
|
||||
type RevisionConflict struct{ Current int }
|
||||
|
||||
func (e *RevisionConflict) Error() string {
|
||||
return fmt.Sprintf("company profile revision conflict: current revision is %d", e.Current)
|
||||
}
|
||||
|
||||
func (e *RevisionConflict) Is(target error) bool { return target == ErrConflict }
|
||||
|
||||
// sameJSON reports whether a and b are the same JSON value, regardless of key
|
||||
// order and whitespace (JSONB does not keep either).
|
||||
func sameJSON(a, b json.RawMessage) bool {
|
||||
var x, y any
|
||||
if json.Unmarshal(a, &x) != nil || json.Unmarshal(b, &y) != nil {
|
||||
return false
|
||||
}
|
||||
ca, _ := json.Marshal(x)
|
||||
cb, _ := json.Marshal(y)
|
||||
return bytes.Equal(ca, cb)
|
||||
}
|
||||
@@ -38,6 +38,8 @@ type Memory struct {
|
||||
projects map[string]*Project
|
||||
offers map[string]*TrialOffer
|
||||
services map[string]*ManagedService
|
||||
profiles map[string]*CompanyProfile // tenant_id → current
|
||||
profRevs map[string][]CompanyProfile // tenant_id → every revision
|
||||
mail []*MailItem
|
||||
mailID int64
|
||||
}
|
||||
@@ -63,6 +65,8 @@ func NewMemory() *Memory {
|
||||
projects: make(map[string]*Project),
|
||||
offers: make(map[string]*TrialOffer),
|
||||
services: make(map[string]*ManagedService),
|
||||
profiles: make(map[string]*CompanyProfile),
|
||||
profRevs: make(map[string][]CompanyProfile),
|
||||
|
||||
documents: make(map[string]*Document),
|
||||
}
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (m *Memory) GetCompanyProfile(_ context.Context, tenantID string) (*CompanyProfile, error) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
p, ok := m.profiles[tenantID]
|
||||
if !ok {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
cp := *p
|
||||
return &cp, nil
|
||||
}
|
||||
|
||||
func (m *Memory) SaveCompanyProfile(_ context.Context, w CompanyProfileWrite) (*CompanyProfile, bool, error) {
|
||||
if !json.Valid(w.Data) || w.SchemaVersion == "" {
|
||||
return nil, false, ErrInvalidInput
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if _, ok := m.tenants[w.TenantID]; !ok {
|
||||
return nil, false, ErrNotFound
|
||||
}
|
||||
cur := m.profiles[w.TenantID]
|
||||
current := 0
|
||||
if cur != nil {
|
||||
current = cur.Revision
|
||||
}
|
||||
if w.ExpectedRevision != current {
|
||||
return nil, false, &RevisionConflict{Current: current}
|
||||
}
|
||||
if cur != nil && cur.SchemaVersion == w.SchemaVersion && sameJSON(cur.Data, w.Data) {
|
||||
cp := *cur
|
||||
return &cp, false, nil
|
||||
}
|
||||
next := CompanyProfile{TenantID: w.TenantID, Status: ProfileDraft}
|
||||
if cur != nil {
|
||||
next = *cur
|
||||
}
|
||||
next.Data = append(json.RawMessage(nil), w.Data...)
|
||||
next.SchemaVersion = w.SchemaVersion
|
||||
next.Revision = current + 1
|
||||
next.UpdatedBy, next.UpdatedAt = w.By, w.At.UTC()
|
||||
m.profiles[w.TenantID] = &next
|
||||
m.profRevs[w.TenantID] = append(m.profRevs[w.TenantID], next)
|
||||
cp := next
|
||||
return &cp, true, nil
|
||||
}
|
||||
|
||||
func (m *Memory) SubmitCompanyProfile(_ context.Context, tenantID string, expectedRevision int, by string, at time.Time) (*CompanyProfile, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
cur, ok := m.profiles[tenantID]
|
||||
if !ok {
|
||||
if _, known := m.tenants[tenantID]; !known {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, &RevisionConflict{Current: 0}
|
||||
}
|
||||
if expectedRevision != cur.Revision {
|
||||
return nil, &RevisionConflict{Current: cur.Revision}
|
||||
}
|
||||
next := *cur
|
||||
t := at.UTC()
|
||||
next.Revision++
|
||||
next.Status = ProfileSubmitted
|
||||
next.UpdatedBy, next.UpdatedAt = by, t
|
||||
next.SubmittedBy, next.SubmittedAt = by, &t
|
||||
m.profiles[tenantID] = &next
|
||||
m.profRevs[tenantID] = append(m.profRevs[tenantID], next)
|
||||
cp := next
|
||||
return &cp, nil
|
||||
}
|
||||
|
||||
// CompanyProfileRevisions returns every stored revision, oldest first (tests).
|
||||
func (m *Memory) CompanyProfileRevisions(tenantID string) []CompanyProfile {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
return append([]CompanyProfile(nil), m.profRevs[tenantID]...)
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
const profileSelect = `
|
||||
SELECT tenant_id::text, data, schema_version, revision, status, updated_by, updated_at, submitted_by, submitted_at
|
||||
FROM company_profiles `
|
||||
|
||||
func scanProfile(row pgx.Row) (*CompanyProfile, error) {
|
||||
var p CompanyProfile
|
||||
var data []byte
|
||||
if err := row.Scan(&p.TenantID, &data, &p.SchemaVersion, &p.Revision, &p.Status, &p.UpdatedBy, &p.UpdatedAt, &p.SubmittedBy, &p.SubmittedAt); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
p.Data = json.RawMessage(data)
|
||||
return &p, nil
|
||||
}
|
||||
|
||||
func (p *Postgres) GetCompanyProfile(ctx context.Context, tenantID string) (*CompanyProfile, error) {
|
||||
pr, err := scanProfile(p.pool.QueryRow(ctx, profileSelect+`WHERE tenant_id = $1::uuid`, tenantID))
|
||||
if isInvalidUUID(err) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return pr, err
|
||||
}
|
||||
|
||||
// currentProfile locks the tenant's profile row for the transaction; nil
|
||||
// when there is none yet.
|
||||
func currentProfile(ctx context.Context, tx pgx.Tx, tenantID string) (*CompanyProfile, error) {
|
||||
cur, err := scanProfile(tx.QueryRow(ctx, profileSelect+`WHERE tenant_id = $1::uuid FOR UPDATE`, tenantID))
|
||||
switch {
|
||||
case errors.Is(err, ErrNotFound):
|
||||
return nil, nil
|
||||
case isInvalidUUID(err):
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return cur, err
|
||||
}
|
||||
|
||||
func (p *Postgres) SaveCompanyProfile(ctx context.Context, w CompanyProfileWrite) (*CompanyProfile, bool, error) {
|
||||
if !json.Valid(w.Data) || w.SchemaVersion == "" {
|
||||
return nil, false, ErrInvalidInput
|
||||
}
|
||||
tx, err := p.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
cur, err := currentProfile(ctx, tx, w.TenantID)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
current := 0
|
||||
if cur != nil {
|
||||
current = cur.Revision
|
||||
}
|
||||
if w.ExpectedRevision != current {
|
||||
return nil, false, &RevisionConflict{Current: current}
|
||||
}
|
||||
if cur != nil && cur.SchemaVersion == w.SchemaVersion && sameJSON(cur.Data, w.Data) {
|
||||
return cur, false, nil
|
||||
}
|
||||
next := current + 1
|
||||
if cur == nil {
|
||||
_, err = tx.Exec(ctx, `
|
||||
INSERT INTO company_profiles (tenant_id, data, schema_version, revision, updated_by, updated_at)
|
||||
VALUES ($1::uuid, $2::jsonb, $3, $4, $5, $6)`,
|
||||
w.TenantID, string(w.Data), w.SchemaVersion, next, w.By, w.At.UTC())
|
||||
} else {
|
||||
_, err = tx.Exec(ctx, `
|
||||
UPDATE company_profiles SET data = $2::jsonb, schema_version = $3, revision = $4, updated_by = $5, updated_at = $6
|
||||
WHERE tenant_id = $1::uuid`,
|
||||
w.TenantID, string(w.Data), w.SchemaVersion, next, w.By, w.At.UTC())
|
||||
}
|
||||
switch {
|
||||
case err == nil:
|
||||
case isFKViolation(err):
|
||||
return nil, false, ErrNotFound
|
||||
case isUniqueViolation(err):
|
||||
// A concurrent first save won: report its revision.
|
||||
return nil, false, &RevisionConflict{Current: 1}
|
||||
case isCheckViolation(err):
|
||||
return nil, false, ErrInvalidInput
|
||||
default:
|
||||
return nil, false, err
|
||||
}
|
||||
if err := insertProfileRevision(ctx, tx, w.TenantID, next, w.Source, w.By, w.At); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
saved, err := p.GetCompanyProfile(ctx, w.TenantID)
|
||||
return saved, true, err
|
||||
}
|
||||
|
||||
func (p *Postgres) SubmitCompanyProfile(ctx context.Context, tenantID string, expectedRevision int, by string, at time.Time) (*CompanyProfile, error) {
|
||||
tx, err := p.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
cur, err := currentProfile(ctx, tx, tenantID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if cur == nil {
|
||||
var exists bool
|
||||
if err := tx.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM tenants WHERE id = $1::uuid)`, tenantID).Scan(&exists); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !exists {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, &RevisionConflict{Current: 0}
|
||||
}
|
||||
if expectedRevision != cur.Revision {
|
||||
return nil, &RevisionConflict{Current: cur.Revision}
|
||||
}
|
||||
next := cur.Revision + 1
|
||||
if _, err := tx.Exec(ctx, `
|
||||
UPDATE company_profiles SET revision = $2, status = 'submitted', updated_by = $3, updated_at = $4, submitted_by = $3, submitted_at = $4
|
||||
WHERE tenant_id = $1::uuid`, tenantID, next, by, at.UTC()); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := insertProfileRevision(ctx, tx, tenantID, next, ProfileSourceSubmit, by, at); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return p.GetCompanyProfile(ctx, tenantID)
|
||||
}
|
||||
|
||||
// insertProfileRevision copies the row just written into the history.
|
||||
func insertProfileRevision(ctx context.Context, tx pgx.Tx, tenantID string, revision int, source, by string, at time.Time) error {
|
||||
_, err := tx.Exec(ctx, `
|
||||
INSERT INTO company_profile_revisions (tenant_id, revision, data, schema_version, status, source, changed_by, changed_at)
|
||||
SELECT tenant_id, revision, data, schema_version, status, $3, $4, $5
|
||||
FROM company_profiles WHERE tenant_id = $1::uuid AND revision = $2`,
|
||||
tenantID, revision, source, by, at.UTC())
|
||||
return err
|
||||
}
|
||||
@@ -205,6 +205,16 @@ type Store interface {
|
||||
UpdateProject(ctx context.Context, p Project) (*Project, error)
|
||||
DeleteProject(ctx context.Context, id string) error
|
||||
|
||||
// Company profile (0021): one per tenant. GetCompanyProfile is
|
||||
// ErrNotFound when the tenant has none. SaveCompanyProfile writes a new
|
||||
// revision unless data and schema version are unchanged (changed=false);
|
||||
// the status stays as it was. SubmitCompanyProfile marks the current
|
||||
// state submitted as a new revision. Both return a *RevisionConflict
|
||||
// (matches ErrConflict) when the expected revision is not the stored one.
|
||||
GetCompanyProfile(ctx context.Context, tenantID string) (*CompanyProfile, error)
|
||||
SaveCompanyProfile(ctx context.Context, w CompanyProfileWrite) (profile *CompanyProfile, changed bool, err error)
|
||||
SubmitCompanyProfile(ctx context.Context, tenantID string, expectedRevision int, by string, at time.Time) (*CompanyProfile, error)
|
||||
|
||||
// Managed services (0012, portal#77), listed by created_at. One row per
|
||||
// (tenant, kind, url): ErrConflict otherwise.
|
||||
ListManagedServices(ctx context.Context, tenantID string) ([]ManagedService, error)
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
DROP TABLE IF EXISTS company_profile_revisions;
|
||||
DROP TABLE IF EXISTS company_profiles;
|
||||
@@ -0,0 +1,31 @@
|
||||
-- Unternehmensprofil (portal onboarding, decided 2026-10-20): a tenant's
|
||||
-- company profile and compliance scope as the portal form saves them. The
|
||||
-- registry is the authority; the portal owns the form's schema, so the
|
||||
-- answers are kept as the form's document (JSONB), every answer, option and
|
||||
-- "Vorschlag" mark unchanged. One profile per tenant (the tenant is the
|
||||
-- company); advisors' client profiles come later as separate records.
|
||||
CREATE TABLE company_profiles (
|
||||
tenant_id UUID PRIMARY KEY REFERENCES tenants(id) ON DELETE CASCADE,
|
||||
data JSONB NOT NULL CHECK (jsonb_typeof(data) = 'object'),
|
||||
schema_version TEXT NOT NULL CHECK (char_length(schema_version) BETWEEN 1 AND 40),
|
||||
revision INTEGER NOT NULL CHECK (revision >= 1),
|
||||
status TEXT NOT NULL DEFAULT 'draft' CHECK (status IN ('draft', 'submitted')),
|
||||
updated_by TEXT NOT NULL DEFAULT '',
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
submitted_by TEXT NOT NULL DEFAULT '',
|
||||
submitted_at TIMESTAMPTZ
|
||||
);
|
||||
|
||||
-- Every saved state, never changed afterwards: who changed what when, and
|
||||
-- whether it came from the form, a submission or a staff import.
|
||||
CREATE TABLE company_profile_revisions (
|
||||
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||
revision INTEGER NOT NULL CHECK (revision >= 1),
|
||||
data JSONB NOT NULL,
|
||||
schema_version TEXT NOT NULL,
|
||||
status TEXT NOT NULL CHECK (status IN ('draft', 'submitted')),
|
||||
source TEXT NOT NULL CHECK (source IN ('portal', 'submit', 'import')),
|
||||
changed_by TEXT NOT NULL DEFAULT '',
|
||||
changed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (tenant_id, revision)
|
||||
);
|
||||
+142
@@ -333,6 +333,63 @@ paths:
|
||||
url: { type: string, description: The object in the Prüfwerk dashboard. }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
|
||||
/v1/tenants/{id}/company-profile:
|
||||
get:
|
||||
summary: The tenant's company profile (Unternehmensprofil), current revision.
|
||||
description: |
|
||||
Served by the `{id}/{sub}` route; user tokens reach their own tenant
|
||||
only. The answers are the portal form's document, unchanged.
|
||||
parameters:
|
||||
- { in: path, name: id, required: true, schema: { type: string, format: uuid } }
|
||||
responses:
|
||||
"200":
|
||||
description: The profile.
|
||||
content:
|
||||
application/json: { schema: { $ref: "#/components/schemas/CompanyProfile" } }
|
||||
"404": { description: The tenant does not exist or has no profile yet. }
|
||||
put:
|
||||
summary: Save the company profile (a new revision).
|
||||
description: |
|
||||
The portal calls this for users it allowed to edit (IT_ADMIN, CXO,
|
||||
LEGAL; named in X-Portal-User-Email). expected_revision is the
|
||||
revision the writer last read (0 for none); anything else is refused
|
||||
with 409 and the current revision. A save that changes nothing
|
||||
returns the profile without a new revision. The status is kept.
|
||||
parameters:
|
||||
- { in: path, name: id, required: true, schema: { type: string, format: uuid } }
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json: { schema: { $ref: "#/components/schemas/CompanyProfileWrite" } }
|
||||
responses:
|
||||
"200":
|
||||
description: Saved (or unchanged).
|
||||
content:
|
||||
application/json: { schema: { $ref: "#/components/schemas/CompanyProfile" } }
|
||||
"400": { description: "expected_revision_required, invalid_schema_version or invalid_profile." }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
"409": { $ref: "#/components/responses/ProfileRevisionConflict" }
|
||||
"413": { description: The document exceeds 256 KiB (too_large). }
|
||||
|
||||
/v1/tenants/{id}/company-profile/submit:
|
||||
post:
|
||||
summary: Submit the company profile (status submitted, a new revision).
|
||||
description: The portal offers it once every required answer is given.
|
||||
parameters:
|
||||
- { in: path, name: id, required: true, schema: { type: string, format: uuid } }
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema: { type: object, required: [expected_revision], properties: { expected_revision: { type: integer, minimum: 0 } } }
|
||||
responses:
|
||||
"200":
|
||||
description: Submitted.
|
||||
content:
|
||||
application/json: { schema: { $ref: "#/components/schemas/CompanyProfile" } }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
"409": { $ref: "#/components/responses/ProfileRevisionConflict" }
|
||||
|
||||
/v1/tenants/{id}/managed-services:
|
||||
get:
|
||||
summary: A tenant's managed services (Verwaltete Infrastruktur), oldest first.
|
||||
@@ -832,6 +889,40 @@ paths:
|
||||
"204": { description: Deleted. }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
|
||||
/v1/admin/tenants/{id}/company-profile:
|
||||
get:
|
||||
summary: A tenant's company profile (staff).
|
||||
parameters:
|
||||
- { in: path, name: id, required: true, schema: { type: string, format: uuid } }
|
||||
responses:
|
||||
"200":
|
||||
description: The profile.
|
||||
content:
|
||||
application/json: { schema: { $ref: "#/components/schemas/CompanyProfile" } }
|
||||
"404": { description: The tenant does not exist or has no profile yet. }
|
||||
put:
|
||||
summary: Import a company profile (staff only).
|
||||
description: |
|
||||
Staff bring in a profile the customer filled in elsewhere. Needs a
|
||||
named staff member (X-Staff-Subject); recorded as source "import"
|
||||
in the history and as company_profile.imported in the audit log.
|
||||
Same rules as the tenant PUT.
|
||||
parameters:
|
||||
- { in: path, name: id, required: true, schema: { type: string, format: uuid } }
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json: { schema: { $ref: "#/components/schemas/CompanyProfileWrite" } }
|
||||
responses:
|
||||
"200":
|
||||
description: Imported (or unchanged).
|
||||
content:
|
||||
application/json: { schema: { $ref: "#/components/schemas/CompanyProfile" } }
|
||||
"400": { description: "expected_revision_required, invalid_schema_version or invalid_profile." }
|
||||
"403": { description: No named staff member (staff_only). }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
"409": { $ref: "#/components/responses/ProfileRevisionConflict" }
|
||||
|
||||
/v1/admin/tenants/{id}/preview-grants:
|
||||
post:
|
||||
summary: Grant a preview of a product not for sale yet (staff only, audited).
|
||||
@@ -1620,6 +1711,16 @@ components:
|
||||
content:
|
||||
application/json: { schema: { $ref: "#/components/schemas/Error" } }
|
||||
|
||||
ProfileRevisionConflict:
|
||||
description: The profile was changed since the writer read it (revision_conflict).
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
error: { type: string, example: revision_conflict }
|
||||
message: { type: string }
|
||||
current_revision: { type: integer, description: "The revision to reload; 0 when there is no profile." }
|
||||
schemas:
|
||||
ErpWebhookEvent:
|
||||
type: object
|
||||
@@ -1816,6 +1917,47 @@ components:
|
||||
description: { type: string, maxLength: 1000 }
|
||||
level: { type: string, enum: [family, product, component], description: "Products only; defaults to product. A family has no parent, a product sits below a family or nothing, a component below a product or component; at most 4 levels." }
|
||||
parent_id: { type: string, description: "uuid of the project above, \"\" to detach. Must be a product project of the same tenant that fits the level." }
|
||||
CompanyProfile:
|
||||
type: object
|
||||
required: [tenant_id, data, schema_version, revision, status, updated_by, updated_at]
|
||||
properties:
|
||||
tenant_id: { type: string, format: uuid }
|
||||
data: { $ref: "#/components/schemas/CompanyProfileDocument" }
|
||||
schema_version: { type: string, description: "The portal form's schema the answers follow." }
|
||||
revision: { type: integer, minimum: 1 }
|
||||
status: { type: string, enum: [draft, submitted] }
|
||||
updated_by: { type: string }
|
||||
updated_at: { type: string, format: date-time }
|
||||
submitted_by: { type: string }
|
||||
submitted_at: { type: string, format: date-time }
|
||||
CompanyProfileWrite:
|
||||
type: object
|
||||
required: [data, schema_version, expected_revision]
|
||||
properties:
|
||||
data: { $ref: "#/components/schemas/CompanyProfileDocument" }
|
||||
schema_version: { type: string, minLength: 1, maxLength: 40 }
|
||||
expected_revision: { type: integer, minimum: 0 }
|
||||
CompanyProfileDocument:
|
||||
type: object
|
||||
description: |
|
||||
The portal form's document. The registry checks only its outline;
|
||||
the fields and their options are the portal's schema. Answers are
|
||||
text, a number, yes/no, a list of texts or null.
|
||||
required: [sections]
|
||||
additionalProperties: false
|
||||
properties:
|
||||
audience: { type: string, enum: [own_company], nullable: true }
|
||||
clientRef: { type: string, maxLength: 200 }
|
||||
sections:
|
||||
type: object
|
||||
additionalProperties: false
|
||||
properties:
|
||||
company_profile: { type: object, additionalProperties: true }
|
||||
compliance_scope: { type: object, additionalProperties: true }
|
||||
ai_act: { type: object, additionalProperties: true }
|
||||
documents: { type: array, items: { type: object } }
|
||||
suggested: { type: array, items: { type: string }, description: "Field ids holding an unconfirmed system suggestion." }
|
||||
lastStep: { type: string, maxLength: 200 }
|
||||
ManagedService:
|
||||
type: object
|
||||
required: [id, tenant_id, kind, name, url, sku, status, created_at, updated_at]
|
||||
|
||||
Reference in new issue
Block a user