feat(projects): product hierarchy - family, product, component
A product project gets a level (family | product | component) and a parent (migration 0020), so a machine with its robot arm, PLC, edge server and Windows app, or a product family, can be modelled. Topics stay flat; kind is unchanged and old clients get level "product" at the top. The API checks the tree: allowed parents per level, same tenant, no cycles, at most 4 levels, children still fitting after a level change. The database keeps parents within the tenant and refuses to delete a project with children (409 has_children). The list stays flat with level and parent_id. A document's role follows the level of the project it is linked to; no document schema change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3f4dfa0cdc
commit
c4b7686cc5
9 files changed
+355
-36
No files matched your search
+149
-19
@@ -8,6 +8,7 @@ import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -26,6 +27,29 @@ type projectReq struct {
|
||||
Name *string `json:"name"`
|
||||
Kind *string `json:"kind"`
|
||||
Description *string `json:"description"`
|
||||
// Level and ParentID (0020): where a product sits in the hierarchy.
|
||||
// An empty parent_id detaches the project.
|
||||
Level *string `json:"level"`
|
||||
ParentID *string `json:"parent_id"`
|
||||
}
|
||||
|
||||
// apply copies the request's fields onto p.
|
||||
func (in projectReq) apply(p *store.Project) {
|
||||
if in.Name != nil {
|
||||
p.Name = *in.Name
|
||||
}
|
||||
if in.Kind != nil {
|
||||
p.Kind = *in.Kind
|
||||
}
|
||||
if in.Description != nil {
|
||||
p.Description = *in.Description
|
||||
}
|
||||
if in.Level != nil {
|
||||
p.Level = *in.Level
|
||||
}
|
||||
if in.ParentID != nil {
|
||||
p.ParentID = *in.ParentID
|
||||
}
|
||||
}
|
||||
|
||||
// projectActor names who changed a project for the audit trail and
|
||||
@@ -71,6 +95,11 @@ func normalizeProject(p *store.Project) (code, msg string) {
|
||||
p.Name = strings.Join(strings.Fields(p.Name), " ")
|
||||
p.Kind = strings.ToLower(strings.TrimSpace(p.Kind))
|
||||
p.Description = strings.TrimSpace(p.Description)
|
||||
p.Level = strings.ToLower(strings.TrimSpace(p.Level))
|
||||
p.ParentID = strings.TrimSpace(p.ParentID)
|
||||
if p.Kind == store.ProjectKindProduct && p.Level == "" {
|
||||
p.Level = store.ProjectLevelProduct // clients without the hierarchy
|
||||
}
|
||||
switch {
|
||||
case p.Name == "" || len([]rune(p.Name)) > 120:
|
||||
return "invalid_name", "name must be 1 to 120 characters"
|
||||
@@ -78,10 +107,116 @@ func normalizeProject(p *store.Project) (code, msg string) {
|
||||
return "invalid_kind", "kind must be product or topic"
|
||||
case len([]rune(p.Description)) > 1000:
|
||||
return "invalid_description", "description must be at most 1000 characters"
|
||||
case p.Kind == store.ProjectKindTopic && (p.Level != "" || p.ParentID != ""):
|
||||
return "invalid_level", "a topic has no level and no parent"
|
||||
case p.Kind == store.ProjectKindProduct && p.Level != store.ProjectLevelFamily && p.Level != store.ProjectLevelProduct && p.Level != store.ProjectLevelComponent:
|
||||
return "invalid_level", "level must be family, product or component"
|
||||
}
|
||||
return "", ""
|
||||
}
|
||||
|
||||
// maxProjectDepth: family -> product -> component -> component.
|
||||
const maxProjectDepth = 4
|
||||
|
||||
// allowedParent: which level a parent may have for each level ("" = none).
|
||||
var allowedParent = map[string][]string{
|
||||
store.ProjectLevelFamily: {""},
|
||||
store.ProjectLevelProduct: {"", store.ProjectLevelFamily},
|
||||
store.ProjectLevelComponent: {store.ProjectLevelProduct, store.ProjectLevelComponent},
|
||||
}
|
||||
|
||||
// checkHierarchy checks p's place in the tenant's tree (all = the tenant's
|
||||
// projects as stored, p possibly among them with its old values): the parent
|
||||
// exists and fits p's level, there is no cycle, the tree stays within
|
||||
// maxProjectDepth, and p's children still fit when p's level changes.
|
||||
func checkHierarchy(p store.Project, all []store.Project) (code, msg string) {
|
||||
byID := map[string]store.Project{}
|
||||
for _, x := range all {
|
||||
byID[x.ID] = x
|
||||
}
|
||||
byID[p.ID] = p
|
||||
if p.Kind != store.ProjectKindProduct {
|
||||
for _, x := range all {
|
||||
if x.ParentID == p.ID && p.ID != "" {
|
||||
return "has_children", "a project with components or products below it must stay a product"
|
||||
}
|
||||
}
|
||||
return "", ""
|
||||
}
|
||||
parentLevel := ""
|
||||
if p.ParentID != "" {
|
||||
parent, ok := byID[p.ParentID]
|
||||
if !ok || parent.ID == p.ID {
|
||||
return "invalid_parent", "the parent is not a product of this workspace"
|
||||
}
|
||||
if parent.Kind != store.ProjectKindProduct {
|
||||
return "invalid_parent", "a topic cannot be a parent"
|
||||
}
|
||||
parentLevel = parent.Level
|
||||
}
|
||||
if !slices.Contains(allowedParent[p.Level], parentLevel) {
|
||||
return "invalid_parent", fmt.Sprintf("a %s cannot sit below %s", p.Level, orNone(parentLevel))
|
||||
}
|
||||
// Walk up: no cycle, and count the depth above p.
|
||||
depth, seen := 1, map[string]bool{p.ID: true}
|
||||
for cur := p.ParentID; cur != ""; cur = byID[cur].ParentID {
|
||||
if seen[cur] {
|
||||
return "invalid_parent", "the parent is below this project"
|
||||
}
|
||||
seen[cur] = true
|
||||
depth++
|
||||
}
|
||||
// Children keep fitting, and the deepest branch below stays in bounds.
|
||||
var below func(id string) int
|
||||
below = func(id string) int {
|
||||
d := 0
|
||||
for _, x := range all {
|
||||
if x.ParentID == id && x.ID != id {
|
||||
d = max(d, 1+below(x.ID))
|
||||
}
|
||||
}
|
||||
return d
|
||||
}
|
||||
if p.ID != "" {
|
||||
for _, x := range all {
|
||||
if x.ParentID == p.ID && !slices.Contains(allowedParent[x.Level], p.Level) {
|
||||
return "invalid_level", fmt.Sprintf("%q (a %s) cannot sit below a %s", x.Name, x.Level, p.Level)
|
||||
}
|
||||
}
|
||||
depth += below(p.ID)
|
||||
}
|
||||
if depth > maxProjectDepth {
|
||||
return "too_deep", fmt.Sprintf("the hierarchy is at most %d levels deep", maxProjectDepth)
|
||||
}
|
||||
return "", ""
|
||||
}
|
||||
|
||||
func orNone(level string) string {
|
||||
if level == "" {
|
||||
return "nothing"
|
||||
}
|
||||
return "a " + level
|
||||
}
|
||||
|
||||
// placeProject checks p against the tenant's other projects and writes the
|
||||
// error when it does not fit.
|
||||
func (s *Server) placeProject(ctx context.Context, w http.ResponseWriter, p store.Project) bool {
|
||||
all, err := s.Store.ListProjects(ctx, p.TenantID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "internal", err.Error())
|
||||
return false
|
||||
}
|
||||
if code, msg := checkHierarchy(p, all); code != "" {
|
||||
status := http.StatusBadRequest
|
||||
if code == "has_children" {
|
||||
status = http.StatusConflict
|
||||
}
|
||||
writeError(w, status, code, msg)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// createTenantProject is POST /v1/tenants/{id}/projects.
|
||||
func (s *Server) createTenantProject(w http.ResponseWriter, r *http.Request) {
|
||||
var in projectReq
|
||||
@@ -95,19 +230,14 @@ func (s *Server) createTenantProject(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
p := store.Project{TenantID: t.ID, CreatedBy: s.projectActor(r)}
|
||||
if in.Name != nil {
|
||||
p.Name = *in.Name
|
||||
}
|
||||
if in.Kind != nil {
|
||||
p.Kind = *in.Kind
|
||||
}
|
||||
if in.Description != nil {
|
||||
p.Description = *in.Description
|
||||
}
|
||||
in.apply(&p)
|
||||
if code, msg := normalizeProject(&p); code != "" {
|
||||
writeError(w, http.StatusBadRequest, code, msg)
|
||||
return
|
||||
}
|
||||
if !s.placeProject(ctx, w, p) {
|
||||
return
|
||||
}
|
||||
created, err := s.Store.CreateProject(ctx, p)
|
||||
if err != nil {
|
||||
s.writeProjectError(w, err)
|
||||
@@ -115,7 +245,7 @@ func (s *Server) createTenantProject(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
s.emitAudit(ctx, r, store.AuditEvent{
|
||||
TenantID: t.ID, Action: "project.created", TargetID: created.ID, TargetType: "project", TargetName: created.Name,
|
||||
ActorType: s.projectActorType(r), ActorName: p.CreatedBy, Metadata: map[string]interface{}{"kind": created.Kind},
|
||||
ActorType: s.projectActorType(r), ActorName: p.CreatedBy, Metadata: map[string]interface{}{"kind": created.Kind, "level": created.Level, "parent_id": created.ParentID},
|
||||
})
|
||||
writeJSON(w, http.StatusCreated, created)
|
||||
}
|
||||
@@ -152,19 +282,17 @@ func (s *Server) updateTenantProject(w http.ResponseWriter, r *http.Request) {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if in.Name != nil {
|
||||
p.Name = *in.Name
|
||||
}
|
||||
if in.Kind != nil {
|
||||
p.Kind = *in.Kind
|
||||
}
|
||||
if in.Description != nil {
|
||||
p.Description = *in.Description
|
||||
if in.Kind != nil && strings.EqualFold(strings.TrimSpace(*in.Kind), store.ProjectKindTopic) {
|
||||
p.Level, p.ParentID = "", "" // a topic leaves the hierarchy
|
||||
}
|
||||
in.apply(p)
|
||||
if code, msg := normalizeProject(p); code != "" {
|
||||
writeError(w, http.StatusBadRequest, code, msg)
|
||||
return
|
||||
}
|
||||
if !s.placeProject(ctx, w, *p) {
|
||||
return
|
||||
}
|
||||
updated, err := s.Store.UpdateProject(ctx, *p)
|
||||
if err != nil {
|
||||
s.writeProjectError(w, err)
|
||||
@@ -172,7 +300,7 @@ func (s *Server) updateTenantProject(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
s.emitAudit(ctx, r, store.AuditEvent{
|
||||
TenantID: t.ID, Action: "project.updated", TargetID: updated.ID, TargetType: "project", TargetName: updated.Name,
|
||||
ActorType: s.projectActorType(r), ActorName: s.projectActor(r),
|
||||
ActorType: s.projectActorType(r), ActorName: s.projectActor(r), Metadata: map[string]interface{}{"level": updated.Level, "parent_id": updated.ParentID},
|
||||
})
|
||||
writeJSON(w, http.StatusOK, updated)
|
||||
}
|
||||
@@ -202,6 +330,8 @@ func (s *Server) writeProjectError(w http.ResponseWriter, err error) {
|
||||
switch {
|
||||
case errors.Is(err, store.ErrConflict):
|
||||
writeError(w, http.StatusConflict, "name_taken", "a project with this name exists")
|
||||
case errors.Is(err, store.ErrHasChildren):
|
||||
writeError(w, http.StatusConflict, "has_children", "move or delete the products and components below it first")
|
||||
case errors.Is(err, store.ErrInvalidInput):
|
||||
writeError(w, http.StatusBadRequest, "invalid_input", "invalid project")
|
||||
case mapStoreError(w, err):
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
package server_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/store"
|
||||
)
|
||||
|
||||
func TestProjects_hierarchy(t *testing.T) {
|
||||
eachStore(t, func(t *testing.T, h *testHarness) {
|
||||
base := "/v1/tenants/" + h.tenant.ID + "/projects"
|
||||
// Old clients: a product without level is a product at the top.
|
||||
legacy := createProject(t, h, h.tenant.ID, map[string]any{"name": "Pumpe P-1", "kind": "product"})
|
||||
if legacy.Level != "product" || legacy.ParentID != "" {
|
||||
t.Fatalf("legacy: %+v", legacy)
|
||||
}
|
||||
fam := createProject(t, h, h.tenant.ID, map[string]any{"name": "PS-Serie", "kind": "product", "level": "family"})
|
||||
ps := createProject(t, h, h.tenant.ID, map[string]any{"name": "PS-200", "kind": "product", "level": "product", "parent_id": fam.ID})
|
||||
arm := createProject(t, h, h.tenant.ID, map[string]any{"name": "Roboterarm", "kind": "product", "level": "component", "parent_id": ps.ID})
|
||||
grip := createProject(t, h, h.tenant.ID, map[string]any{"name": "Greifer", "kind": "product", "level": "COMPONENT", "parent_id": arm.ID})
|
||||
if grip.Level != "component" || grip.ParentID != arm.ID {
|
||||
t.Fatalf("component: %+v", grip)
|
||||
}
|
||||
topic := createProject(t, h, h.tenant.ID, map[string]any{"name": "CRA", "kind": "topic"})
|
||||
|
||||
// The list stays flat and carries level and parent.
|
||||
_, raw := h.do("GET", base, nil)
|
||||
var list struct{ Items []store.Project }
|
||||
_ = json.Unmarshal(raw, &list)
|
||||
got := map[string]store.Project{}
|
||||
for _, p := range list.Items {
|
||||
got[p.Name] = p
|
||||
}
|
||||
if len(list.Items) != 6 || got["Greifer"].ParentID != arm.ID || got["PS-Serie"].Level != "family" || got["CRA"].Level != "" {
|
||||
t.Fatalf("list: %s", raw)
|
||||
}
|
||||
|
||||
bad := func(body map[string]any, code string) {
|
||||
t.Helper()
|
||||
resp, raw := h.do("POST", base, body)
|
||||
if resp.StatusCode != 400 || !strings.Contains(string(raw), code) {
|
||||
t.Fatalf("%v: %d %s", body, resp.StatusCode, raw)
|
||||
}
|
||||
}
|
||||
bad(map[string]any{"name": "x1", "kind": "product", "level": "machine"}, "invalid_level")
|
||||
bad(map[string]any{"name": "x2", "kind": "topic", "level": "product"}, "invalid_level")
|
||||
bad(map[string]any{"name": "x3", "kind": "topic", "parent_id": fam.ID}, "invalid_level")
|
||||
bad(map[string]any{"name": "x4", "kind": "product", "level": "family", "parent_id": fam.ID}, "invalid_parent")
|
||||
bad(map[string]any{"name": "x5", "kind": "product", "level": "component"}, "invalid_parent")
|
||||
bad(map[string]any{"name": "x6", "kind": "product", "level": "product", "parent_id": ps.ID}, "invalid_parent")
|
||||
bad(map[string]any{"name": "x7", "kind": "product", "level": "component", "parent_id": fam.ID}, "invalid_parent")
|
||||
bad(map[string]any{"name": "x8", "kind": "product", "level": "component", "parent_id": topic.ID}, "invalid_parent")
|
||||
bad(map[string]any{"name": "x9", "kind": "product", "level": "component", "parent_id": "00000000-0000-0000-0000-000000000000"}, "invalid_parent")
|
||||
// family -> product -> arm -> gripper is the deepest allowed.
|
||||
bad(map[string]any{"name": "x10", "kind": "product", "level": "component", "parent_id": grip.ID}, "too_deep")
|
||||
|
||||
// Another workspace's product is not a parent.
|
||||
other, _ := h.store.CreateTenant(context.Background(), store.TenantCreate{Slug: "globex", Name: "Globex"})
|
||||
op := createProject(t, h, other.ID, map[string]any{"name": "Fremd", "kind": "product"})
|
||||
bad(map[string]any{"name": "x11", "kind": "product", "level": "component", "parent_id": op.ID}, "invalid_parent")
|
||||
|
||||
patch := func(id string, body map[string]any) (int, string) {
|
||||
resp, raw := h.do("PATCH", base+"/"+id, body)
|
||||
return resp.StatusCode, string(raw)
|
||||
}
|
||||
// No cycles: the arm cannot move below its own gripper.
|
||||
if code, raw := patch(arm.ID, map[string]any{"parent_id": grip.ID}); code != 400 || !strings.Contains(raw, "invalid_parent") {
|
||||
t.Fatalf("cycle: %d %s", code, raw)
|
||||
}
|
||||
// A level change must keep the children fitting.
|
||||
if code, raw := patch(ps.ID, map[string]any{"level": "family", "parent_id": ""}); code != 400 || !strings.Contains(raw, "invalid_level") {
|
||||
t.Fatalf("product with components below becomes a family: %d %s", code, raw)
|
||||
}
|
||||
// Depth counts what hangs below: PS-200 with arm and gripper cannot go
|
||||
// below a product that is itself in a family.
|
||||
if code, raw := patch(legacy.ID, map[string]any{"parent_id": fam.ID}); code != 200 {
|
||||
t.Fatalf("legacy joins family: %d %s", code, raw)
|
||||
}
|
||||
if code, raw := patch(ps.ID, map[string]any{"level": "component", "parent_id": legacy.ID}); code != 400 || !strings.Contains(raw, "too_deep") {
|
||||
t.Fatalf("too deep with children: %d %s", code, raw)
|
||||
}
|
||||
if code, raw := patch(fam.ID, map[string]any{"level": "product"}); code != 400 || !strings.Contains(raw, "invalid_level") {
|
||||
t.Fatalf("family with products below becomes a product: %d %s", code, raw)
|
||||
}
|
||||
if code, raw := patch(arm.ID, map[string]any{"kind": "topic"}); code != 409 || !strings.Contains(raw, "has_children") {
|
||||
t.Fatalf("arm becomes topic: %d %s", code, raw)
|
||||
}
|
||||
// Moving is fine where it fits: the PS-200 leaves the family.
|
||||
if code, raw := patch(ps.ID, map[string]any{"parent_id": ""}); code != 200 || strings.Contains(raw, `"parent_id"`) {
|
||||
t.Fatalf("detach: %d %s", code, raw)
|
||||
}
|
||||
// Renaming keeps level and parent.
|
||||
if code, raw := patch(legacy.ID, map[string]any{"name": "Pumpe P-1 neu"}); code != 200 || !strings.Contains(raw, fam.ID) || !strings.Contains(raw, `"level":"product"`) {
|
||||
t.Fatalf("rename: %d %s", code, raw)
|
||||
}
|
||||
// A leaf may become a topic; it leaves the tree.
|
||||
if code, raw := patch(grip.ID, map[string]any{"kind": "topic"}); code != 200 || strings.Contains(raw, "parent_id") || strings.Contains(raw, `"level"`) {
|
||||
t.Fatalf("leaf to topic: %d %s", code, raw)
|
||||
}
|
||||
|
||||
// Deleting a project with children is refused; leaves go first.
|
||||
if resp, raw := h.do("DELETE", base+"/"+ps.ID, nil); resp.StatusCode != 409 || !strings.Contains(string(raw), "has_children") {
|
||||
t.Fatalf("delete with children: %d %s", resp.StatusCode, raw)
|
||||
}
|
||||
for _, id := range []string{arm.ID, ps.ID} {
|
||||
if resp, raw := h.do("DELETE", base+"/"+id, nil); resp.StatusCode != 204 {
|
||||
t.Fatalf("delete %s: %d %s", id, resp.StatusCode, raw)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -11,8 +11,29 @@ import (
|
||||
|
||||
func (m *Memory) validProject(p Project) bool {
|
||||
n := len([]rune(p.Name))
|
||||
return n >= 1 && n <= 120 && len([]rune(p.Description)) <= 1000 &&
|
||||
(p.Kind == ProjectKindProduct || p.Kind == ProjectKindTopic)
|
||||
if n < 1 || n > 120 || len([]rune(p.Description)) > 1000 {
|
||||
return false
|
||||
}
|
||||
switch p.Kind {
|
||||
case ProjectKindProduct:
|
||||
if p.Level != ProjectLevelFamily && p.Level != ProjectLevelProduct && p.Level != ProjectLevelComponent {
|
||||
return false
|
||||
}
|
||||
case ProjectKindTopic:
|
||||
if p.Level != "" || p.ParentID != "" {
|
||||
return false
|
||||
}
|
||||
default:
|
||||
return false
|
||||
}
|
||||
if p.ParentID != "" {
|
||||
// Like the database: the parent exists in the same tenant and is not the project itself.
|
||||
parent, ok := m.projects[p.ParentID]
|
||||
if !ok || parent.TenantID != p.TenantID || p.ParentID == p.ID {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// nameTaken reports whether another project of the tenant has the name
|
||||
@@ -92,6 +113,7 @@ func (m *Memory) UpdateProject(_ context.Context, p Project) (*Project, error) {
|
||||
return nil, ErrConflict
|
||||
}
|
||||
cur.Name, cur.Kind, cur.Description, cur.UpdatedAt = p.Name, p.Kind, p.Description, time.Now().UTC()
|
||||
cur.Level, cur.ParentID = p.Level, p.ParentID
|
||||
out := *cur
|
||||
return &out, nil
|
||||
}
|
||||
@@ -102,6 +124,11 @@ func (m *Memory) DeleteProject(_ context.Context, id string) error {
|
||||
if _, ok := m.projects[id]; !ok {
|
||||
return ErrNotFound
|
||||
}
|
||||
for _, x := range m.projects {
|
||||
if x.ParentID == id {
|
||||
return ErrHasChildren
|
||||
}
|
||||
}
|
||||
delete(m.projects, id)
|
||||
for _, d := range m.documents {
|
||||
kept := d.ProjectIDs[:0:0]
|
||||
|
||||
@@ -8,12 +8,12 @@ import (
|
||||
)
|
||||
|
||||
const projectSelect = `
|
||||
SELECT id::text, tenant_id::text, name, kind, description, created_by, created_at, updated_at
|
||||
SELECT id::text, tenant_id::text, name, kind, COALESCE(level, ''), COALESCE(parent_id::text, ''), description, created_by, created_at, updated_at
|
||||
FROM projects `
|
||||
|
||||
func scanProject(row pgx.Row) (*Project, error) {
|
||||
var p Project
|
||||
if err := row.Scan(&p.ID, &p.TenantID, &p.Name, &p.Kind, &p.Description, &p.CreatedBy, &p.CreatedAt, &p.UpdatedAt); err != nil {
|
||||
if err := row.Scan(&p.ID, &p.TenantID, &p.Name, &p.Kind, &p.Level, &p.ParentID, &p.Description, &p.CreatedBy, &p.CreatedAt, &p.UpdatedAt); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
@@ -53,9 +53,9 @@ func (p *Postgres) GetProject(ctx context.Context, id string) (*Project, error)
|
||||
func (p *Postgres) CreateProject(ctx context.Context, pr Project) (*Project, error) {
|
||||
var id string
|
||||
err := p.pool.QueryRow(ctx, `
|
||||
INSERT INTO projects (tenant_id, name, kind, description, created_by)
|
||||
VALUES ($1::uuid, $2, $3, $4, $5) RETURNING id::text`,
|
||||
pr.TenantID, pr.Name, pr.Kind, pr.Description, pr.CreatedBy).Scan(&id)
|
||||
INSERT INTO projects (tenant_id, name, kind, level, parent_id, description, created_by)
|
||||
VALUES ($1::uuid, $2, $3, NULLIF($4, ''), NULLIF($5, '')::uuid, $6, $7) RETURNING id::text`,
|
||||
pr.TenantID, pr.Name, pr.Kind, pr.Level, pr.ParentID, pr.Description, pr.CreatedBy).Scan(&id)
|
||||
switch {
|
||||
case err == nil:
|
||||
return p.GetProject(ctx, id)
|
||||
@@ -72,14 +72,14 @@ func (p *Postgres) CreateProject(ctx context.Context, pr Project) (*Project, err
|
||||
|
||||
func (p *Postgres) UpdateProject(ctx context.Context, pr Project) (*Project, error) {
|
||||
tag, err := p.pool.Exec(ctx, `
|
||||
UPDATE projects SET name = $2, kind = $3, description = $4, updated_at = now()
|
||||
WHERE id = $1::uuid`, pr.ID, pr.Name, pr.Kind, pr.Description)
|
||||
UPDATE projects SET name = $2, kind = $3, description = $4, level = NULLIF($5, ''), parent_id = NULLIF($6, '')::uuid, updated_at = now()
|
||||
WHERE id = $1::uuid`, pr.ID, pr.Name, pr.Kind, pr.Description, pr.Level, pr.ParentID)
|
||||
switch {
|
||||
case isInvalidUUID(err):
|
||||
return nil, ErrNotFound
|
||||
case isUniqueViolation(err):
|
||||
return nil, ErrConflict
|
||||
case isCheckViolation(err):
|
||||
case isCheckViolation(err), isFKViolation(err):
|
||||
return nil, ErrInvalidInput
|
||||
case err != nil:
|
||||
return nil, err
|
||||
@@ -94,6 +94,9 @@ func (p *Postgres) DeleteProject(ctx context.Context, id string) error {
|
||||
if isInvalidUUID(err) {
|
||||
return ErrNotFound
|
||||
}
|
||||
if isFKViolation(err) {
|
||||
return ErrHasChildren
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -15,6 +15,8 @@ var (
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrConflict = errors.New("conflict")
|
||||
ErrInvalidInput = errors.New("invalid input")
|
||||
// ErrHasChildren: a project with sub-projects cannot be deleted (0020).
|
||||
ErrHasChildren = errors.New("has children")
|
||||
)
|
||||
|
||||
// TenantCreate is the input shape for Store.CreateTenant.
|
||||
|
||||
+12
-4
@@ -301,10 +301,14 @@ const (
|
||||
// Project — a tenant's grouping of documents and product objects (0010):
|
||||
// one of the customer's products or machines, or a topic such as the CRA.
|
||||
type Project struct {
|
||||
ID string `json:"id"`
|
||||
TenantID string `json:"tenant_id"`
|
||||
Name string `json:"name"`
|
||||
Kind string `json:"kind"` // product | topic
|
||||
ID string `json:"id"`
|
||||
TenantID string `json:"tenant_id"`
|
||||
Name string `json:"name"`
|
||||
Kind string `json:"kind"` // product | topic
|
||||
// Level and ParentID (0020) place a product project in the hierarchy:
|
||||
// family -> product -> component (components nest). Empty for topics.
|
||||
Level string `json:"level,omitempty"`
|
||||
ParentID string `json:"parent_id,omitempty"`
|
||||
Description string `json:"description"`
|
||||
CreatedBy string `json:"created_by,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
@@ -314,6 +318,10 @@ type Project struct {
|
||||
const (
|
||||
ProjectKindProduct = "product"
|
||||
ProjectKindTopic = "topic"
|
||||
|
||||
ProjectLevelFamily = "family"
|
||||
ProjectLevelProduct = "product"
|
||||
ProjectLevelComponent = "component"
|
||||
)
|
||||
|
||||
// ManagedService — infrastructure BreakPilot runs for a tenant (0012,
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
DROP INDEX IF EXISTS projects_parent_idx;
|
||||
ALTER TABLE projects
|
||||
DROP CONSTRAINT IF EXISTS projects_parent,
|
||||
DROP CONSTRAINT IF EXISTS projects_tenant_id_key,
|
||||
DROP CONSTRAINT IF EXISTS projects_not_own_parent,
|
||||
DROP CONSTRAINT IF EXISTS projects_level,
|
||||
DROP COLUMN IF EXISTS parent_id,
|
||||
DROP COLUMN IF EXISTS level;
|
||||
@@ -0,0 +1,22 @@
|
||||
-- Product hierarchy: a product project is a family, a product placed on the
|
||||
-- market, or a component of one (a machine's robot arm, PLC, edge server or
|
||||
-- Windows application). Components nest (robot arm -> gripper). Topics stay
|
||||
-- flat. A document's role follows the level of the project it is linked to.
|
||||
-- The rules that need the whole tree (allowed parents, depth, no cycles) are
|
||||
-- checked by the API; the database keeps the parent within the tenant and
|
||||
-- refuses to delete a project that still has children.
|
||||
ALTER TABLE projects
|
||||
ADD COLUMN level TEXT,
|
||||
ADD COLUMN parent_id UUID;
|
||||
|
||||
UPDATE projects SET level = 'product' WHERE kind = 'product';
|
||||
|
||||
ALTER TABLE projects
|
||||
ADD CONSTRAINT projects_level CHECK (
|
||||
(kind = 'product' AND level IN ('family', 'product', 'component'))
|
||||
OR (kind = 'topic' AND level IS NULL AND parent_id IS NULL)),
|
||||
ADD CONSTRAINT projects_not_own_parent CHECK (parent_id IS NULL OR parent_id <> id),
|
||||
ADD CONSTRAINT projects_tenant_id_key UNIQUE (tenant_id, id),
|
||||
ADD CONSTRAINT projects_parent FOREIGN KEY (tenant_id, parent_id) REFERENCES projects (tenant_id, id) ON DELETE RESTRICT;
|
||||
|
||||
CREATE INDEX projects_parent_idx ON projects (parent_id) WHERE parent_id IS NOT NULL;
|
||||
+8
-3
@@ -268,7 +268,7 @@ paths:
|
||||
description: Created.
|
||||
content:
|
||||
application/json: { schema: { $ref: "#/components/schemas/Project" } }
|
||||
"400": { $ref: "#/components/responses/BadRequest" }
|
||||
"400": { description: "invalid_name, invalid_kind, invalid_level, invalid_parent or too_deep." }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
"409": { description: A project with this name exists (name_taken). }
|
||||
|
||||
@@ -287,9 +287,9 @@ paths:
|
||||
description: The project.
|
||||
content:
|
||||
application/json: { schema: { $ref: "#/components/schemas/Project" } }
|
||||
"400": { $ref: "#/components/responses/BadRequest" }
|
||||
"400": { description: "invalid_name, invalid_kind, invalid_level (also when its children would no longer fit), invalid_parent (incl. cycles) or too_deep." }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
"409": { description: A project with this name exists (name_taken). }
|
||||
"409": { description: "name_taken, or has_children when a project with children would become a topic." }
|
||||
delete:
|
||||
summary: Delete a project. Its documents stay; they lose the assignment.
|
||||
parameters:
|
||||
@@ -298,6 +298,7 @@ paths:
|
||||
responses:
|
||||
"204": { description: Deleted. }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
"409": { description: "has_children: move or delete the products and components below it first." }
|
||||
|
||||
/v1/tenants/{id}/projects/{pid}/targets:
|
||||
get:
|
||||
@@ -1801,6 +1802,8 @@ components:
|
||||
tenant_id: { type: string, format: uuid }
|
||||
name: { type: string }
|
||||
kind: { type: string, enum: [product, topic] }
|
||||
level: { type: string, enum: [family, product, component], description: "Products only (0020): where it sits in family -> product -> component. Absent for topics." }
|
||||
parent_id: { type: string, format: uuid, description: "The project above it (family for a product; product or component for a component). Absent at the top." }
|
||||
description: { type: string }
|
||||
created_by: { type: string }
|
||||
created_at: { type: string, format: date-time }
|
||||
@@ -1811,6 +1814,8 @@ components:
|
||||
name: { type: string, minLength: 1, maxLength: 120 }
|
||||
kind: { type: string, enum: [product, topic], description: "product: one of the customer's products or machines; topic: e.g. CRA, Data Act" }
|
||||
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." }
|
||||
ManagedService:
|
||||
type: object
|
||||
required: [id, tenant_id, kind, name, url, sku, status, created_at, updated_at]
|
||||
|
||||
Reference in new issue
Block a user