Files
Docwell/Server/internal/directory/spaces.go
T
tajniak81andClaude Opus 5.5 ec11abd8b8 Add page properties, tags, All docs, collections and journals
Phase B (items 1-6) of docs/AFFINE.md.

Properties: workspaces define custom page properties (text, number,
checkbox, date, select, multi-select, person, link) in the new
workspace_properties collection; pages keep their values in
pages.properties, checked against each property's type. The Info panel
under the title shows tags, custom and built-in properties, following
each property's visibility; the Info side panel shows them all, with the
page's collections and the journal. Settings gains Page properties and
Tags sections.

Tags: coloured, per workspace (tags collection, pages.tags); create from
the picker, rename, recolour, merge and delete. Search filters by tag.

All docs: GET /workspaces/{id}/docs lists the pages the caller can open
with their properties, narrowed by space, tag, collection or filter
rules evaluated on the server. The view shows a list, grid or cards,
groups and orders by any property, picks the properties shown, and acts
on several pages at once (tag, move, trash, collect).

Collections (page_collections): saved rules plus pages added or taken
out by hand, private to their creator until shared with the workspace,
listed in the sidebar.

Journals: one page per person and day in a private journal space
(spaces.journal_owner) that workspace admins do not see into, made on
first use. A week strip marks days with pages, new days can start from
a template, and dates in read mode open that day's journal.

The migration and schema snapshot, OpenAPI spec and generated Go, TS and
Dart types are updated (the Dart generator learns untyped values), the
mobile editor bundle is rebuilt, the new strings are translated into all
five languages, and the user guide covers the new features.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 16:35:42 +01:00

453 lines
14 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
package directory
import (
"context"
"errors"
"fmt"
"slices"
"sort"
"strings"
"docwell/server/internal/access"
"docwell/server/internal/apperr"
"docwell/server/internal/store/pocketbase"
)
// ---- Spaces ----------------------------------------------------------------
type Space struct {
ID string `json:"id"`
Workspace string `json:"workspace"`
Name string `json:"name"`
Slug string `json:"slug"`
Icon string `json:"icon"`
Description string `json:"description"`
Visibility string `json:"visibility"`
DefaultRole string `json:"defaultRole"`
// Role is the caller's effective space role after the cascade.
Role string `json:"role"`
// Limited is true when the caller cannot open the space itself and sees
// only the pages shared with them (Role is then "").
Limited bool `json:"limited"`
// Journal is set on a journal space: one person's daily pages, kept
// out of everyone else's lists (see access.JournalSpaceRole).
Journal bool `json:"journal"`
Created string `json:"created"`
}
type spaceRecord struct {
ID string `json:"id"`
Workspace string `json:"workspace"`
Name string `json:"name"`
Slug string `json:"slug"`
Icon string `json:"icon"`
Description string `json:"description"`
Visibility string `json:"visibility"`
DefaultRole string `json:"default_role"`
Created string `json:"created"`
// JournalOwner is the person whose journal this space is ("" for others).
JournalOwner string `json:"journal_owner"`
JournalTemplate string `json:"journal_template"`
}
func (r spaceRecord) view(role string) Space {
def := r.DefaultRole
if !access.ValidDefaultRole(def) {
def = access.SpaceEditor
}
return Space{
ID: r.ID, Workspace: r.Workspace, Name: r.Name, Slug: r.Slug, Icon: r.Icon, Description: r.Description,
Visibility: r.Visibility, DefaultRole: def, Role: role, Limited: role == "", Journal: r.JournalOwner != "",
Created: r.Created,
}
}
// role is the caller's role in the space after the cascade; explicit is
// their own (or their groups') role in it.
func (r spaceRecord) role(callerID, wsRole, explicit string) string {
if r.JournalOwner != "" {
return access.JournalSpaceRole(wsRole, r.JournalOwner, callerID, explicit)
}
return access.SpaceRole(wsRole, r.Visibility, r.DefaultRole, explicit)
}
type spaceMemberRecord struct {
ID string `json:"id"`
Space string `json:"space"`
PrincipalID string `json:"principal_id"`
Role string `json:"role"`
}
// listAll pages through a whole collection query (PocketBase caps a page at 1000 records).
func listAll[T any](ctx context.Context, s *Service, collection string, opts pocketbase.ListOptions) ([]T, error) {
opts.PerPage = 1000
var out []T
for page := 1; ; page++ {
opts.Page = page
res, err := pocketbase.List[T](ctx, s.pb, collection, opts)
if err != nil {
return nil, err
}
out = append(out, res.Items...)
if page >= res.TotalPages || len(res.Items) == 0 {
return out, nil
}
}
}
// userSpaceMemberships lists a user's space memberships, in one workspace or ("" ) all.
func (s *Service) userSpaceMemberships(ctx context.Context, userID, wsID string) ([]spaceMemberRecord, error) {
filter := fmt.Sprintf("principal_type = 'user' && principal_id = '%s'", userID)
if wsID != "" {
filter += fmt.Sprintf(" && space.workspace = '%s'", wsID)
}
return listAll[spaceMemberRecord](ctx, s, "space_members", pocketbase.ListOptions{Filter: filter})
}
func (s *Service) spaceMembership(ctx context.Context, spaceID, userID string) (spaceMemberRecord, error) {
res, err := pocketbase.List[spaceMemberRecord](ctx, s.pb, "space_members", pocketbase.ListOptions{
PerPage: 1, Filter: fmt.Sprintf("space = '%s' && principal_type = 'user' && principal_id = '%s'", spaceID, userID),
})
if err != nil || len(res.Items) == 0 {
return spaceMemberRecord{}, err
}
return res.Items[0], nil
}
// spaceAccess is a space with the caller's workspace and space roles. From
// pageFor, role is the caller's role on that page (see pageRules) and
// spaceRole stays the role in the space itself.
type spaceAccess struct {
space spaceRecord
ws workspaceRecord
wsRole string
spaceRole string
role string
}
// loadSpace loads a space with c's roles, without checking that c may open it.
func (s *Service) loadSpace(ctx context.Context, c access.Caller, id string) (spaceAccess, error) {
if !validID(id) {
return spaceAccess{}, apperr.NotFound("space not found")
}
sp, err := pocketbase.Get[spaceRecord](ctx, s.pb, "spaces", id)
if err != nil {
return spaceAccess{}, mapPB(err, "space not found")
}
ws, err := s.getWorkspace(ctx, sp.Workspace)
if err != nil {
return spaceAccess{}, err
}
wsRole, err := s.effective(ctx, c, ws)
if err != nil {
return spaceAccess{}, err
}
var explicit string
if wsRole != "" && (!access.AtLeast(wsRole, access.WorkspaceAdmin) || sp.JournalOwner != "") {
if explicit, err = s.explicitSpaceRole(ctx, sp, c.ID); err != nil {
return spaceAccess{}, err
}
}
role := sp.role(c.ID, wsRole, explicit)
return spaceAccess{space: sp, ws: ws, wsRole: wsRole, spaceRole: role, role: role}, nil
}
// spaceFor loads a space with c's roles. A space c cannot open is reported as
// not found, like a workspace.
func (s *Service) spaceFor(ctx context.Context, c access.Caller, id string) (spaceAccess, error) {
a, err := s.loadSpace(ctx, c, id)
if err != nil {
return spaceAccess{}, err
}
if err := access.ViewSpace(a.role); err != nil {
return spaceAccess{}, err
}
return a, nil
}
// spaceReach is spaceFor that also lets in a workspace member who cannot
// open the space but holds page grants in it (a guest a page was shared
// with). Their role stays "": only pageRules gives them anything.
func (s *Service) spaceReach(ctx context.Context, c access.Caller, id string) (spaceAccess, error) {
a, err := s.loadSpace(ctx, c, id)
if err != nil || a.role != "" {
return a, err
}
if a.wsRole != "" {
has, err := s.hasPageGrants(ctx, c, a.space)
if err != nil {
return spaceAccess{}, err
}
if has {
return a, nil
}
}
return spaceAccess{}, apperr.NotFound("space not found")
}
// ListSpaces lists the spaces of a workspace that c can open.
func (s *Service) ListSpaces(ctx context.Context, c access.Caller, wsID string) ([]Space, error) {
ws, wsRole, err := s.workspaceFor(ctx, c, wsID)
if err != nil {
return nil, err
}
spaces, err := listAll[spaceRecord](ctx, s, "spaces", pocketbase.ListOptions{
Filter: fmt.Sprintf("workspace = '%s'", ws.ID), Sort: "name",
})
if err != nil {
return nil, err
}
explicit := map[string]string{}
journals := slices.ContainsFunc(spaces, func(sp spaceRecord) bool { return sp.JournalOwner != "" })
if !access.AtLeast(wsRole, access.WorkspaceAdmin) || journals {
mine, err := s.userSpaceMemberships(ctx, c.ID, ws.ID)
if err != nil {
return nil, err
}
for _, m := range mine {
explicit[m.Space] = m.Role
}
groups, err := s.userGroups(ctx, c.ID, ws.ID)
if err != nil {
return nil, err
}
grants, err := s.groupGrants(ctx, groups, "")
if err != nil {
return nil, err
}
for _, g := range grants {
explicit[g.Space] = access.HigherSpaceRole(explicit[g.Space], g.Role)
}
}
var shared map[string]bool
if !access.AtLeast(wsRole, access.WorkspaceAdmin) || journals {
if shared, err = s.grantedSpaces(ctx, c, ws.ID); err != nil {
return nil, err
}
}
out := []Space{}
for _, sp := range spaces {
if role := sp.role(c.ID, wsRole, explicit[sp.ID]); role != "" || shared[sp.ID] {
out = append(out, sp.view(role))
}
}
sort.SliceStable(out, func(i, j int) bool { return strings.ToLower(out[i].Name) < strings.ToLower(out[j].Name) })
return out, nil
}
// GetSpace returns one space with c's role (Limited for someone who sees
// only pages shared with them).
func (s *Service) GetSpace(ctx context.Context, c access.Caller, id string) (Space, error) {
a, err := s.spaceReach(ctx, c, id)
if err != nil {
return Space{}, err
}
return a.space.view(a.role), nil
}
type CreateSpaceInput struct {
Name string `json:"name"`
Description string `json:"description"`
Icon string `json:"icon"`
Visibility string `json:"visibility"`
}
// CreateSpace creates a space in a workspace (workspace admin or above).
func (s *Service) CreateSpace(ctx context.Context, c access.Caller, wsID string, in CreateSpaceInput) (Space, error) {
name, err := cleanName(in.Name, "Space")
if err != nil {
return Space{}, err
}
visibility := in.Visibility
if visibility == "" {
visibility = access.SpaceOpen
}
if visibility != access.SpaceOpen && visibility != access.SpacePrivate {
return Space{}, apperr.InvalidFields(map[string]string{"visibility": "Visibility must be open or private."})
}
ws, wsRole, err := s.workspaceFor(ctx, c, wsID)
if err != nil {
return Space{}, err
}
if err := access.CreateSpace(wsRole); err != nil {
return Space{}, err
}
base := slugify(name, "space")
for i := 1; i <= 50; i++ {
slug := base
if i > 1 {
slug = fmt.Sprintf("%s-%d", base, i)
}
rec, err := pocketbase.Create[spaceRecord](ctx, s.pb, "spaces", map[string]any{
"workspace": ws.ID, "name": name, "slug": slug, "icon": strings.TrimSpace(in.Icon),
"description": strings.TrimSpace(in.Description), "visibility": visibility, "default_role": access.SpaceEditor,
})
var pbErr *pocketbase.Error
if errors.As(err, &pbErr) && pbErr.Data["slug"].Code == "validation_not_unique" {
continue
}
if err != nil {
return Space{}, mapPB(err, "space not found")
}
s.emitSpace(ctx, "space.created", rec, c.ID)
return rec.view(access.SpaceAdmin), nil
}
return Space{}, apperr.Conflict("could not find a free space address; try another name")
}
// UpdateSpaceInput changes only the fields that are set.
type UpdateSpaceInput struct {
Name *string `json:"name"`
Description *string `json:"description"`
Icon *string `json:"icon"`
Visibility *string `json:"visibility"`
DefaultRole *string `json:"defaultRole"`
}
// UpdateSpace changes a space's settings (space admin).
func (s *Service) UpdateSpace(ctx context.Context, c access.Caller, id string, in UpdateSpaceInput) (Space, error) {
a, err := s.spaceFor(ctx, c, id)
if err != nil {
return Space{}, err
}
if err := access.ManageSpace(a.role); err != nil {
return Space{}, err
}
patch := map[string]any{}
if in.Name != nil {
name, err := cleanName(*in.Name, "Space")
if err != nil {
return Space{}, err
}
patch["name"] = name
}
if in.Description != nil {
patch["description"] = strings.TrimSpace(*in.Description)
}
if in.Icon != nil {
patch["icon"] = strings.TrimSpace(*in.Icon)
}
if in.Visibility != nil {
if *in.Visibility != access.SpaceOpen && *in.Visibility != access.SpacePrivate {
return Space{}, apperr.InvalidFields(map[string]string{"visibility": "Visibility must be open or private."})
}
patch["visibility"] = *in.Visibility
}
if in.DefaultRole != nil {
if !access.ValidDefaultRole(*in.DefaultRole) {
return Space{}, apperr.InvalidFields(map[string]string{"defaultRole": "Default role must be editor, commenter or viewer."})
}
patch["default_role"] = *in.DefaultRole
}
if len(patch) == 0 {
return a.space.view(a.role), nil
}
rec, err := pocketbase.Update[spaceRecord](ctx, s.pb, "spaces", a.space.ID, patch)
if err != nil {
return Space{}, mapPB(err, "space not found")
}
return rec.view(a.role), nil
}
// DeleteSpace deletes a space with all of its pages (workspace admin).
func (s *Service) DeleteSpace(ctx context.Context, c access.Caller, id string) error {
a, err := s.spaceFor(ctx, c, id)
if err != nil {
return err
}
if err := access.DeleteSpace(a.wsRole); err != nil {
return err
}
if err := s.pb.Delete(ctx, "spaces", a.space.ID); err != nil {
return mapPB(err, "space not found")
}
s.emitSpace(ctx, "space.deleted", a.space, c.ID)
return nil
}
// ListSpaceMembers lists a space's explicit members (any space role may look).
// Workspace admins manage every space without being listed.
func (s *Service) ListSpaceMembers(ctx context.Context, c access.Caller, id string) ([]Member, error) {
a, err := s.spaceFor(ctx, c, id)
if err != nil {
return nil, err
}
members, err := listAll[spaceMemberRecord](ctx, s, "space_members", pocketbase.ListOptions{
Filter: fmt.Sprintf("space = '%s' && principal_type = 'user'", a.space.ID),
})
if err != nil {
return nil, err
}
out := make([]Member, 0, len(members))
for _, m := range members {
u, err := s.getUser(ctx, m.PrincipalID)
if err != nil {
continue // a deleted user's leftover row
}
out = append(out, Member{User: MemberUser{ID: u.ID, Email: u.Email, Name: u.Name}, Role: m.Role})
}
sort.Slice(out, func(i, j int) bool { return out[i].User.Email < out[j].User.Email })
return out, nil
}
// SetSpaceMember adds a workspace member (by email) to a space or changes their role (space admin).
func (s *Service) SetSpaceMember(ctx context.Context, c access.Caller, id, email, role string) (Member, error) {
a, err := s.spaceFor(ctx, c, id)
if err != nil {
return Member{}, err
}
if err := access.ManageSpace(a.role); err != nil {
return Member{}, err
}
u, err := s.findUserByEmail(ctx, email)
if err != nil {
return Member{}, err
}
targetWsRole, err := s.effective(ctx, u.Caller(), a.ws)
if err != nil {
return Member{}, err
}
if err := access.SetSpaceMember(a.role, targetWsRole, role); err != nil {
return Member{}, err
}
current, err := s.spaceMembership(ctx, a.space.ID, u.ID)
if err != nil {
return Member{}, err
}
if current.ID != "" {
_, err = pocketbase.Update[spaceMemberRecord](ctx, s.pb, "space_members", current.ID, map[string]any{"role": role})
} else {
_, err = pocketbase.Create[spaceMemberRecord](ctx, s.pb, "space_members", map[string]any{
"space": a.space.ID, "principal_type": "user", "principal_id": u.ID, "role": role,
})
}
if err != nil {
return Member{}, mapPB(err, "space not found")
}
return Member{User: MemberUser{ID: u.ID, Email: u.Email, Name: u.Name}, Role: role}, nil
}
// RemoveSpaceMember removes a space membership (idempotent). Anyone may leave;
// removing others needs space admin.
func (s *Service) RemoveSpaceMember(ctx context.Context, c access.Caller, id, userID string) error {
a, err := s.spaceFor(ctx, c, id)
if err != nil {
return err
}
if userID != c.ID {
if err := access.ManageSpace(a.role); err != nil {
return err
}
}
if !validID(userID) {
return apperr.NotFound("member not found")
}
current, err := s.spaceMembership(ctx, a.space.ID, userID)
if err != nil || current.ID == "" {
return err
}
return mapPB(s.pb.Delete(ctx, "space_members", current.ID), "member not found")
}