org

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 5, 2026 License: Apache-2.0 Imports: 22 Imported by: 0

Documentation

Overview

The production AdminAuthorizer. org has no engine-relation question to ask here — "may this caller administer org" is exactly the same platform-superadmin global-scope question registry's own EffectiveAccessAuthorizer (internal/registry/adminauthz.go) already answers, so this is a thin adapter over the shared internal/authz/client implementation rather than a second copy of the HTTP logic.

org's own half of the default module-access grant writer. On the PRODUCTION company-creation path (POST /internal/org/units, org.Store.CreateOrgUnit, when the created unit's type is org.org_unit_type.is_company = true), every currently installed+enabled module gets `company_module:<newCompanyId>/<moduleKey>#system @ system:platform` defaulted, default-ONCE, through authz's own audited authz/store.EnsureDefaultGrant — in the SAME transaction as the org_unit insert and its audit record, so a brand new company is never left with zero admins even transiently. Runs on org's OWN pool/role (kiban_org), which migrations/registry/0007 and migrations/authz/0005 grant exactly the cross-schema read (platform.module_installation) and write (authz.tuple/grant_ledger/default_grant) access this needs.

org.group / org.group_member — the third org fact type (member · position · group), source-aware. A group is a company-scoped named set of members with exactly one authoritative source: `source='kiban'` groups are writable through this file's own membership methods (the human/API path); any other source is a group an external sync writer owns — its membership is READ-ONLY through every path this file exposes, enforced HERE in the store (never only at the HTTP layer), never by a second writer racing the first. Kept in its own file (store.go is already large) — same package, same Store receiver.

Package org implements the org service: the triangle. It owns org-unit tree facts (typed taxonomy = configuration, company = the sole tenancy/authz anchor), members (company-scoped persons, optional user link), and position slots (C-lite: position + assignment with validity windows). Facts only — anything ACTING on these facts is a module.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrGroupNotFound is returned when a group id doesn't resolve to any row.
	ErrGroupNotFound = errors.New("org: group not found")
	// ErrGroupMemberNotFound is the 404 for removing a member who is not in the group — no
	// audit row, no revoke (nothing changed).
	ErrGroupMemberNotFound = errors.New("org: member is not in this group")
	// ErrGroupExternallyManaged is the single-writer invariant's own sentinel (409
	// GROUP_EXTERNALLY_MANAGED): a membership write was attempted against a group whose source is
	// not "kiban". With no sync-writer entrypoint, NO write path can ever succeed against such a
	// group — this is not a restriction the HTTP layer works around, it is enforced in the store,
	// unconditionally, for every caller.
	ErrGroupExternallyManaged = errors.New("org: group is externally managed — membership is read-only here")
)
View Source
var (
	ErrOrgUnitNotFound    = errors.New("org: org unit not found")
	ErrOrgUnitHasChildren = errors.New("org: org unit has children")
	ErrOrgUnitHasMembers  = errors.New("org: org unit has members")
	ErrMemberNotFound     = errors.New("org: member not found")
	ErrPositionNotFound   = errors.New("org: position not found")
	ErrAssignmentNotFound = errors.New("org: assignment not found")
	// ErrAssignmentAlreadyEnded is the 409 ASSIGNMENT_ALREADY_ENDED: EndAssignment on a window
	// whose valid_to is already set writes nothing (re-ending would rewrite history and revoke
	// the holder tuple a newer open assignment for the same pair depends on).
	ErrAssignmentAlreadyEnded = errors.New("org: assignment already ended")
)
View Source
var ErrAuthorizationUnavailable = &authUnavailableError{}

ErrAuthorizationUnavailable is the fail-closed sentinel the HTTP layer maps to 503 AUTHORIZATION_UNAVAILABLE.

View Source
var ErrConflict = errors.New("org: conflict")

ErrConflict is a 409 CONFLICT condition: a unique or exclusion constraint violation (duplicate code, duplicate user link within a company, overlapping assignment).

View Source
var ErrCrossCompanyAssignment = &ValidationError{Field: "memberId", Message: "member must belong to the position's company"}

ErrCrossCompanyAssignment is the store-level VALIDATION_FAILED for an assignment whose member does not belong to the position's company.

View Source
var ErrMemberInactive = &ValidationError{Field: "memberId", Message: "member must be active"}

ErrMemberInactive is the 422 VALIDATION_ERROR for assign-NOW against an inactive member — assign-NOW never silently assigns an inactive member.

View Source
var ErrUserNotConfirmed = &ValidationError{Field: "kcSub", Message: "identity could not confirm this user exists"}

ErrUserNotConfirmed is returned by LinkUser when identity's live state check could not confirm the kcSub resolves to a real account (either identity said not-found, or identity was unreachable — this call never trusts the input).

Functions

func CheckMigrationsApplied

func CheckMigrationsApplied(ctx context.Context, pool *pgxpool.Pool) error

CheckMigrationsApplied verifies migrations have been run — it never runs them itself (no runtime DDL, ever; migrations are applied out-of-band by `make migrate-org`, as the kiban owner role).

Types

type AddGroupMemberParams

type AddGroupMemberParams struct {
	GroupID  pgtype.UUID `json:"group_id"`
	MemberID pgtype.UUID `json:"member_id"`
	AddedBy  string      `json:"added_by"`
}

type AdminAuthorizer

type AdminAuthorizer interface {
	// Can reports whether authCtx may perform action. A *DeniedError is a definite denial
	// (authz answered "not the superadmin", with its reason); any other non-nil error means the
	// authorizer could not reach a definite answer — callers must treat both as deny, never as
	// allow, and only the first as a 403.
	Can(ctx context.Context, authCtx AuthContext, action string) (bool, error)
	// CanInCompany reports whether authCtx may perform action in companyID: the superadmin, or
	// an active member holding the company's admin relation. Same error contract as Can.
	CanInCompany(ctx context.Context, authCtx AuthContext, action, companyID string) (bool, error)
}

AdminAuthorizer guards org's mutation endpoints — same fail-closed seam as registry.AdminAuthorizer and identity.AdminAuthorizer.

func NewDenyAllAuthorizer

func NewDenyAllAuthorizer() AdminAuthorizer

NewDenyAllAuthorizer returns the v1 fail-closed AdminAuthorizer.

func NewEngineAdminAuthorizer

func NewEngineAdminAuthorizer(baseURL string, httpClient *http.Client) AdminAuthorizer

NewEngineAdminAuthorizer returns the real, authz-service-backed AdminAuthorizer: fails closed (ErrAuthorizationUnavailable) on anything but an explicit ALLOWED response from authz — same seam denyAllAuthorizer defined, now backed by a live decision instead of an unconditional 503.

type Assignment

type Assignment struct {
	ID         uuid.UUID
	PositionID uuid.UUID
	MemberID   uuid.UUID
	ValidFrom  time.Time
	ValidTo    *time.Time
}

Assignment is the API-facing shape of an org.position_assignment row.

type AuditIdentityEvent

type AuditIdentityEvent struct {
	ID            int64              `json:"id"`
	OccurredAt    pgtype.Timestamptz `json:"occurred_at"`
	Actor         string             `json:"actor"`
	Action        string             `json:"action"`
	Subject       string             `json:"subject"`
	Payload       []byte             `json:"payload"`
	CorrelationID *string            `json:"correlation_id"`
}

type AuditOrgEvent

type AuditOrgEvent struct {
	ID            int64              `json:"id"`
	OccurredAt    pgtype.Timestamptz `json:"occurred_at"`
	Actor         string             `json:"actor"`
	Action        string             `json:"action"`
	Subject       string             `json:"subject"`
	Payload       []byte             `json:"payload"`
	CorrelationID *string            `json:"correlation_id"`
}

type AuthContext

type AuthContext struct {
	Subject string // empty means "no authenticated actor" — never treated as authority

	// RawBearer is the inbound request's untouched "Authorization: Bearer ..." header value,
	// populated by http.go's mutation handlers straight from the request — never derived, never
	// from a request body. It exists so the real AdminAuthorizer
	// (internal/authz/client) can forward the SAME bearer to authz's effective-access endpoint
	// for a live platform-role check — same shape as internal/registry/adminauthz.go's
	// EffectiveAccessAuthorizer, which this package's AdminAuthorizer now reuses via a thin
	// adapter (see NewEngineAdminAuthorizer).
	RawBearer string
}

AuthContext is the server-derived actor identity threaded into authorization and audit calls — derived server-side from the request, never from a request body.

type CompanySummary

type CompanySummary struct {
	ID       uuid.UUID
	Code     string
	Name     string
	IsActive bool
}

CompanySummary is one company row in ListActiveCompaniesForKcSub's result — the fields the company-switcher needs, nothing more.

type CountMemberDirectoryParams

type CountMemberDirectoryParams struct {
	CompanyID pgtype.UUID `json:"company_id"`
	Q         *string     `json:"q"`
}

type CountOtherOpenAssignmentsParams

type CountOtherOpenAssignmentsParams struct {
	ID         pgtype.UUID `json:"id"`
	PositionID pgtype.UUID `json:"position_id"`
	MemberID   pgtype.UUID `json:"member_id"`
}

type CreateAssignmentParams

type CreateAssignmentParams struct {
	PositionID pgtype.UUID `json:"position_id"`
	MemberID   pgtype.UUID `json:"member_id"`
	ValidFrom  pgtype.Date `json:"valid_from"`
	ValidTo    pgtype.Date `json:"valid_to"`
}

type CreateGroupParams

type CreateGroupParams struct {
	CompanyID   pgtype.UUID `json:"company_id"`
	Code        string      `json:"code"`
	Name        string      `json:"name"`
	Source      string      `json:"source"`
	ExternalRef *string     `json:"external_ref"`
}

type CreateMemberParams

type CreateMemberParams struct {
	CompanyID   pgtype.UUID `json:"company_id"`
	Code        string      `json:"code"`
	DisplayName string      `json:"display_name"`
	Email       *string     `json:"email"`
	IsActive    bool        `json:"is_active"`
	IsGuest     bool        `json:"is_guest"`
}

type CreateOrgUnitParams

type CreateOrgUnitParams struct {
	TypeKey  string      `json:"type_key"`
	ParentID pgtype.UUID `json:"parent_id"`
	Code     string      `json:"code"`
	Name     string      `json:"name"`
	IsActive bool        `json:"is_active"`
}

type CreatePositionParams

type CreatePositionParams struct {
	CompanyID pgtype.UUID `json:"company_id"`
	Code      string      `json:"code"`
	Title     string      `json:"title"`
	OrgUnitID pgtype.UUID `json:"org_unit_id"`
}

type DBTX

type DBTX interface {
	Exec(context.Context, string, ...interface{}) (pgconn.CommandTag, error)
	Query(context.Context, string, ...interface{}) (pgx.Rows, error)
	QueryRow(context.Context, string, ...interface{}) pgx.Row
}

type DeniedError

type DeniedError struct {
	Reason string
}

DeniedError is Can's confirmed denial: authz's own decision reason (e.g. PLATFORM_ROLE_REQUIRED), which the HTTP layer maps to 403 AUTHORIZATION_DENIED and audits.

func (*DeniedError) Error

func (e *DeniedError) Error() string

type EndAssignmentParams

type EndAssignmentParams struct {
	ID      pgtype.UUID `json:"id"`
	ValidTo pgtype.Date `json:"valid_to"`
}

type GetAssignmentOnDateParams

type GetAssignmentOnDateParams struct {
	PositionID pgtype.UUID `json:"position_id"`
	ValidFrom  pgtype.Date `json:"valid_from"`
}

type GetCompanyStateRow

type GetCompanyStateRow struct {
	ID       pgtype.UUID `json:"id"`
	IsActive bool        `json:"is_active"`
}

type GetGroupMemberParams

type GetGroupMemberParams struct {
	GroupID  pgtype.UUID `json:"group_id"`
	MemberID pgtype.UUID `json:"member_id"`
}

type GetMemberByCompanyAndKcSubParams

type GetMemberByCompanyAndKcSubParams struct {
	CompanyID pgtype.UUID `json:"company_id"`
	KcSub     string      `json:"kc_sub"`
}

type GetMemberByCompanyAndKcSubRow

type GetMemberByCompanyAndKcSubRow struct {
	ID       pgtype.UUID `json:"id"`
	IsActive bool        `json:"is_active"`
	IsGuest  bool        `json:"is_guest"`
}

type GetMemberWithUserRow

type GetMemberWithUserRow struct {
	ID                    pgtype.UUID `json:"id"`
	CompanyID             pgtype.UUID `json:"company_id"`
	Code                  string      `json:"code"`
	DisplayName           string      `json:"display_name"`
	Email                 *string     `json:"email"`
	UserID                pgtype.UUID `json:"user_id"`
	IsActive              bool        `json:"is_active"`
	IsGuest               bool        `json:"is_guest"`
	UserKcSub             *string     `json:"user_kc_sub"`
	UserEmail             *string     `json:"user_email"`
	UserPreferredUsername *string     `json:"user_preferred_username"`
	UserLifecycle         *string     `json:"user_lifecycle"`
	UserKind              *string     `json:"user_kind"`
}

type Group

type Group struct {
	ID          uuid.UUID
	CompanyID   uuid.UUID
	Code        string
	Name        string
	Source      string
	ExternalRef *string
	IsActive    bool
	CreatedAt   time.Time
	UpdatedAt   time.Time
}

Group is the API-facing shape of an org.group row.

func (Group) IsKibanManaged

func (g Group) IsKibanManaged() bool

IsKibanManaged reports whether this group's membership is writable through the ordinary human/API surface — true only for source == "kiban" (the DEFAULT, and currently the ONLY source any group can actually have, since no sync writer exists yet).

type GroupMember

type GroupMember struct {
	GroupID           uuid.UUID
	MemberID          uuid.UUID
	AddedBy           string
	AddedAt           time.Time
	MemberDisplayName string
	MemberEmail       *string
}

GroupMember is the API-facing shape of one org.group_member row, joined with the member's own display fields (the shape the admin surface and helpdesk's assignable-groups read both need).

type GroupWithMemberCount

type GroupWithMemberCount struct {
	Group
	MemberCount int
}

GroupWithMemberCount is the admin-list shape: a group plus how many members it currently has, so the UI never needs a second round trip per row.

type IdentityClient

type IdentityClient struct {
	// contains filtered or unexported fields
}

IdentityClient calls identity's HTTP API to confirm a kcSub resolves to a real account before org links a member to it — validated over HTTP, never by trusting input. It implements Store.IdentityStateChecker.

func NewIdentityClient

func NewIdentityClient(httpClient *http.Client, baseURL string) *IdentityClient

NewIdentityClient builds an IdentityClient. httpClient's Timeout governs the call — a slow/unreachable identity service must fail fast into "not confirmed" rather than hang the caller (same fail-closed shape as identity's own AdminClient.UserEnabled).

func (*IdentityClient) UserExists

func (c *IdentityClient) UserExists(ctx context.Context, kcSub string) (bool, error)

UserExists calls GET /internal/identity/users/{kcSub}/state and reports whether identity confirmed the account exists. A 404 returns (false, nil): identity answered that the account does not exist. Any other non-200 status or a transport/decode error returns (false, non-nil). Neither outcome is ever reported as "exists".

type IdentityMfaPolicy

type IdentityMfaPolicy struct {
	ID        pgtype.UUID        `json:"id"`
	Scope     string             `json:"scope"`
	SubjectID pgtype.UUID        `json:"subject_id"`
	Required  bool               `json:"required"`
	Method    *string            `json:"method"`
	UpdatedAt pgtype.Timestamptz `json:"updated_at"`
}

type IdentityStateChecker

type IdentityStateChecker interface {
	// UserExists reports whether kcSub resolves to a live identity.user_account (any lifecycle
	// state counts as "exists" — LinkUser only needs to know the account is real, not that it's
	// active). A non-nil error means the check could not be completed (identity unreachable);
	// callers must treat that as "not confirmed", never as "exists".
	UserExists(ctx context.Context, kcSub string) (bool, error)
}

IdentityStateChecker is the seam LinkUser calls to validate a user exists over identity's state endpoint, not by trusting input — satisfied by identityclient.Client in production, faked with httptest in tests.

type IdentityUserAccount

type IdentityUserAccount struct {
	ID                pgtype.UUID        `json:"id"`
	KcSub             string             `json:"kc_sub"`
	Email             *string            `json:"email"`
	PreferredUsername *string            `json:"preferred_username"`
	Lifecycle         string             `json:"lifecycle"`
	CreatedAt         pgtype.Timestamptz `json:"created_at"`
	UpdatedAt         pgtype.Timestamptz `json:"updated_at"`
	Kind              string             `json:"kind"`
}

type IdentityUserLoginObservation

type IdentityUserLoginObservation struct {
	UserID      pgtype.UUID        `json:"user_id"`
	LastLoginAt pgtype.Timestamptz `json:"last_login_at"`
	LastLoginIp *string            `json:"last_login_ip"`
}

type IdentityUserReadV

type IdentityUserReadV struct {
	ID                pgtype.UUID `json:"id"`
	KcSub             string      `json:"kc_sub"`
	Email             *string     `json:"email"`
	PreferredUsername *string     `json:"preferred_username"`
	Lifecycle         string      `json:"lifecycle"`
	Kind              string      `json:"kind"`
}

type LinkMemberUserParams

type LinkMemberUserParams struct {
	ID     pgtype.UUID `json:"id"`
	UserID pgtype.UUID `json:"user_id"`
}

type ListActiveCompaniesForKcSubRow

type ListActiveCompaniesForKcSubRow struct {
	ID       pgtype.UUID `json:"id"`
	Code     string      `json:"code"`
	Name     string      `json:"name"`
	IsActive bool        `json:"is_active"`
}

type ListGroupMembersRow

type ListGroupMembersRow struct {
	GroupID           pgtype.UUID        `json:"group_id"`
	MemberID          pgtype.UUID        `json:"member_id"`
	AddedBy           string             `json:"added_by"`
	AddedAt           pgtype.Timestamptz `json:"added_at"`
	MemberDisplayName string             `json:"member_display_name"`
	MemberEmail       *string            `json:"member_email"`
}

type ListGroupsWithMemberCountParams

type ListGroupsWithMemberCountParams struct {
	CompanyID pgtype.UUID `json:"company_id"`
	Limit     int32       `json:"limit"`
	Offset    int32       `json:"offset"`
}

type ListGroupsWithMemberCountRow

type ListGroupsWithMemberCountRow struct {
	ID          pgtype.UUID        `json:"id"`
	CompanyID   pgtype.UUID        `json:"company_id"`
	Code        string             `json:"code"`
	Name        string             `json:"name"`
	Source      string             `json:"source"`
	ExternalRef *string            `json:"external_ref"`
	IsActive    bool               `json:"is_active"`
	CreatedAt   pgtype.Timestamptz `json:"created_at"`
	UpdatedAt   pgtype.Timestamptz `json:"updated_at"`
	MemberCount int64              `json:"member_count"`
}

type ListMemberDirectoryParams

type ListMemberDirectoryParams struct {
	CompanyID pgtype.UUID `json:"company_id"`
	Limit     int32       `json:"limit"`
	Offset    int32       `json:"offset"`
	Q         *string     `json:"q"`
}

type ListMemberDirectoryRow

type ListMemberDirectoryRow struct {
	ID            pgtype.UUID `json:"id"`
	DisplayName   string      `json:"display_name"`
	Email         *string     `json:"email"`
	HasLinkedUser bool        `json:"has_linked_user"`
	Kind          string      `json:"kind"`
}

type ListMembersParams

type ListMembersParams struct {
	CompanyID pgtype.UUID `json:"company_id"`
	Limit     int32       `json:"limit"`
	Offset    int32       `json:"offset"`
}

type ListMembersRow

type ListMembersRow struct {
	ID                    pgtype.UUID `json:"id"`
	CompanyID             pgtype.UUID `json:"company_id"`
	Code                  string      `json:"code"`
	DisplayName           string      `json:"display_name"`
	Email                 *string     `json:"email"`
	UserID                pgtype.UUID `json:"user_id"`
	IsActive              bool        `json:"is_active"`
	IsGuest               bool        `json:"is_guest"`
	UserKcSub             *string     `json:"user_kc_sub"`
	UserEmail             *string     `json:"user_email"`
	UserPreferredUsername *string     `json:"user_preferred_username"`
	UserLifecycle         *string     `json:"user_lifecycle"`
	UserKind              *string     `json:"user_kind"`
}

type ListPositionsParams

type ListPositionsParams struct {
	CompanyID pgtype.UUID `json:"company_id"`
	Limit     int32       `json:"limit"`
	Offset    int32       `json:"offset"`
}

type ListPositionsWithHolderParams

type ListPositionsWithHolderParams struct {
	CompanyID pgtype.UUID `json:"company_id"`
	Limit     int32       `json:"limit"`
	Offset    int32       `json:"offset"`
	Today     pgtype.Date `json:"today"`
}

type ListPositionsWithHolderRow

type ListPositionsWithHolderRow struct {
	ID                 pgtype.UUID `json:"id"`
	CompanyID          pgtype.UUID `json:"company_id"`
	Code               string      `json:"code"`
	Title              string      `json:"title"`
	OrgUnitID          pgtype.UUID `json:"org_unit_id"`
	AssignmentID       pgtype.UUID `json:"assignment_id"`
	AssignmentMemberID pgtype.UUID `json:"assignment_member_id"`
	HolderDisplayName  *string     `json:"holder_display_name"`
}

type Member

type Member struct {
	ID          uuid.UUID
	CompanyID   uuid.UUID
	Code        string
	DisplayName string
	Email       string
	UserID      *uuid.UUID
	IsActive    bool
	// IsGuest: an external person the company shares with, refused the member-level directory
	// reads (members, positions, groups, a group's members). Decisions treat a guest like any
	// other active member.
	IsGuest bool

	// Linked-user display fields (empty when UserID is nil) — never fetched per-row.
	UserKcSub             string
	UserEmail             string
	UserPreferredUsername string
	UserLifecycle         string
	UserKind              string // "person" or "service"; "" when unlinked
}

Member is the API-facing shape of an org.member row, joined with identity.user_read_v when a user is linked (member directory read).

type MemberDirectoryEntry

type MemberDirectoryEntry struct {
	ID            uuid.UUID
	DisplayName   string
	Email         string
	HasLinkedUser bool
	Kind          string // "person", or "service" when the linked user is a client's service account
}

MemberDirectoryEntry is the REDUCED member-directory view (least disclosure — no kcSub, no code, no lifecycle; modules resolve kcSubs server-side via the existing internal member-by-id read when they actually need one).

type MemberFact added in v0.2.0

type MemberFact struct {
	IsMember, IsActive, IsGuest bool
	MemberID                    uuid.UUID
}

MemberFact is what org knows about kcSub inside one company.

type OrgGroup

type OrgGroup struct {
	ID          pgtype.UUID        `json:"id"`
	CompanyID   pgtype.UUID        `json:"company_id"`
	Code        string             `json:"code"`
	Name        string             `json:"name"`
	Source      string             `json:"source"`
	ExternalRef *string            `json:"external_ref"`
	IsActive    bool               `json:"is_active"`
	CreatedAt   pgtype.Timestamptz `json:"created_at"`
	UpdatedAt   pgtype.Timestamptz `json:"updated_at"`
}

type OrgGroupMember

type OrgGroupMember struct {
	GroupID  pgtype.UUID        `json:"group_id"`
	MemberID pgtype.UUID        `json:"member_id"`
	AddedBy  string             `json:"added_by"`
	AddedAt  pgtype.Timestamptz `json:"added_at"`
}

type OrgMember

type OrgMember struct {
	ID          pgtype.UUID `json:"id"`
	CompanyID   pgtype.UUID `json:"company_id"`
	Code        string      `json:"code"`
	DisplayName string      `json:"display_name"`
	Email       *string     `json:"email"`
	UserID      pgtype.UUID `json:"user_id"`
	IsActive    bool        `json:"is_active"`
	IsGuest     bool        `json:"is_guest"`
}

type OrgOrgUnit

type OrgOrgUnit struct {
	ID       pgtype.UUID `json:"id"`
	TypeKey  string      `json:"type_key"`
	ParentID pgtype.UUID `json:"parent_id"`
	Code     string      `json:"code"`
	Name     string      `json:"name"`
	IsActive bool        `json:"is_active"`
}

type OrgOrgUnitType

type OrgOrgUnitType struct {
	Key       string `json:"key"`
	Label     string `json:"label"`
	IsCompany bool   `json:"is_company"`
}

type OrgPosition

type OrgPosition struct {
	ID        pgtype.UUID `json:"id"`
	CompanyID pgtype.UUID `json:"company_id"`
	Code      string      `json:"code"`
	Title     string      `json:"title"`
	OrgUnitID pgtype.UUID `json:"org_unit_id"`
}

type OrgPositionAssignment

type OrgPositionAssignment struct {
	ID         pgtype.UUID `json:"id"`
	PositionID pgtype.UUID `json:"position_id"`
	MemberID   pgtype.UUID `json:"member_id"`
	ValidFrom  pgtype.Date `json:"valid_from"`
	ValidTo    pgtype.Date `json:"valid_to"`
}

type OrgUnit

type OrgUnit struct {
	ID       uuid.UUID
	TypeKey  string
	ParentID *uuid.UUID
	Code     string
	Name     string
	IsActive bool
	Depth    int
}

OrgUnit is the API-facing shape of an org.org_unit row.

type Position

type Position struct {
	ID        uuid.UUID
	CompanyID uuid.UUID
	Code      string
	Title     string
	OrgUnitID uuid.UUID
}

Position is the API-facing shape of an org.position row.

type PositionBoundError

type PositionBoundError struct {
	Count int
}

PositionBoundError is the 409 CONFLICT for deleting a position while any tuple still names `position:<id>#holder` as SUBJECT — i.e. at least one module binding (e.g. helpdesk's agent tier) still points at this position. Count is the number of such tuples, surfaced to the caller so the 409 is actionable. Position DELETE never cascade-revokes another module's grants to unblock itself.

func (*PositionBoundError) Error

func (e *PositionBoundError) Error() string

type PositionHeldError added in v0.1.3

type PositionHeldError struct {
	AssignmentID uuid.UUID
	MemberID     uuid.UUID
}

PositionHeldError is the 409 POSITION_HELD for assigning a member to a position that has a holder today. It names the current assignment so the caller can end it first; the exclusion constraint on position_assignment stays as the second layer for a concurrent write.

func (*PositionHeldError) Error added in v0.1.3

func (e *PositionHeldError) Error() string

func (*PositionHeldError) Unwrap added in v0.1.3

func (e *PositionHeldError) Unwrap() error

Unwrap keeps errors.Is(err, ErrConflict) true: a held position is still a conflict.

type PositionWithHolder

type PositionWithHolder struct {
	Position
	AssignmentID       *uuid.UUID
	AssignmentMemberID *uuid.UUID
	HolderDisplayName  *string
}

PositionWithHolder is the admin-list shape: a position plus its CURRENT assignment (nil when the position has no holder today) — the fields the UI needs to END a tenure.

type Queries

type Queries struct {
	// contains filtered or unexported fields
}

func New

func New(db DBTX) *Queries

func (*Queries) AddGroupMember

func (q *Queries) AddGroupMember(ctx context.Context, arg AddGroupMemberParams) (int64, error)

0 rows affected = already a member (idempotent add); the store then reads the STORED row back with GetGroupMember so the response carries the original added_by/added_at.

func (*Queries) CountGroups

func (q *Queries) CountGroups(ctx context.Context, companyID pgtype.UUID) (int64, error)

func (*Queries) CountMemberDirectory

func (q *Queries) CountMemberDirectory(ctx context.Context, arg CountMemberDirectoryParams) (int64, error)

func (*Queries) CountMembers

func (q *Queries) CountMembers(ctx context.Context, companyID pgtype.UUID) (int64, error)

func (*Queries) CountMembersForCompany

func (q *Queries) CountMembersForCompany(ctx context.Context, companyID pgtype.UUID) (int64, error)

func (*Queries) CountOrgUnitChildren

func (q *Queries) CountOrgUnitChildren(ctx context.Context, parentID pgtype.UUID) (int64, error)

func (*Queries) CountOtherOpenAssignments

func (q *Queries) CountOtherOpenAssignments(ctx context.Context, arg CountOtherOpenAssignmentsParams) (int64, error)

Open (valid_to IS NULL) assignments for the same (position, member) pair other than $1 — the holder tuple is revoked only when this count is zero (ending one of several open windows must not revoke the access another still-open window confers).

func (*Queries) CountPositions

func (q *Queries) CountPositions(ctx context.Context, companyID pgtype.UUID) (int64, error)

func (*Queries) CreateAssignment

func (q *Queries) CreateAssignment(ctx context.Context, arg CreateAssignmentParams) (OrgPositionAssignment, error)

func (*Queries) CreateGroup

func (q *Queries) CreateGroup(ctx context.Context, arg CreateGroupParams) (OrgGroup, error)

source defaults to 'kiban' at the DB level; only an external sync writer would pass another source value explicitly, the org admin API never does.

func (*Queries) CreateMember

func (q *Queries) CreateMember(ctx context.Context, arg CreateMemberParams) (OrgMember, error)

func (*Queries) CreateOrgUnit

func (q *Queries) CreateOrgUnit(ctx context.Context, arg CreateOrgUnitParams) (OrgOrgUnit, error)

func (*Queries) CreatePosition

func (q *Queries) CreatePosition(ctx context.Context, arg CreatePositionParams) (OrgPosition, error)

func (*Queries) DeleteOrgUnit

func (q *Queries) DeleteOrgUnit(ctx context.Context, id pgtype.UUID) (int64, error)

func (*Queries) DeletePosition

func (q *Queries) DeletePosition(ctx context.Context, id pgtype.UUID) (int64, error)

func (*Queries) EndAssignment

func (q *Queries) EndAssignment(ctx context.Context, arg EndAssignmentParams) (OrgPositionAssignment, error)

func (*Queries) GetAssignment

func (q *Queries) GetAssignment(ctx context.Context, id pgtype.UUID) (OrgPositionAssignment, error)

func (*Queries) GetAssignmentOnDate

func (q *Queries) GetAssignmentOnDate(ctx context.Context, arg GetAssignmentOnDateParams) (OrgPositionAssignment, error)

"who holds position P on date D". valid_to is HALF-OPEN/EXCLUSIVE (migrations/org/0009) — D is held when valid_from <= D < valid_to (or valid_to IS NULL), never valid_to >= D (which would have D's holder-of-record still be the PREVIOUS occupant on the exact day a same-day handover's successor starts).

func (*Queries) GetCompanyState

func (q *Queries) GetCompanyState(ctx context.Context, id pgtype.UUID) (GetCompanyStateRow, error)

Company-state fact for authz's decision.CompanySource. A row is only returned when id resolves to a COMPANY-typed org_unit (org_unit_type.is_company = true) — a non-company unit or an unknown id both come back as no-rows, which the store maps to exists=false (never a fabricated company for an org_unit of the wrong type).

func (*Queries) GetGroup

func (q *Queries) GetGroup(ctx context.Context, id pgtype.UUID) (OrgGroup, error)

func (*Queries) GetGroupMember

func (q *Queries) GetGroupMember(ctx context.Context, arg GetGroupMemberParams) (OrgGroupMember, error)

func (*Queries) GetIdentityUserByKcSub

func (q *Queries) GetIdentityUserByKcSub(ctx context.Context, kcSub string) (IdentityUserReadV, error)

The published read contract — the ONLY way org reads identity data. Resolves the internal user_id to store in member.user_id after the HTTP-level liveness check (internal/org/identityclient.go) has confirmed the account exists.

func (*Queries) GetMember

func (q *Queries) GetMember(ctx context.Context, id pgtype.UUID) (OrgMember, error)

func (*Queries) GetMemberByCompanyAndKcSub

Membership fact for authz's decision.MembershipSource. Resolves the member linked to kcSub within companyId via the published identity.user_read_v join (same read path ListMembers/GetMemberWithUser already use) — never a per-row identity call.

func (*Queries) GetMemberWithUser

func (q *Queries) GetMemberWithUser(ctx context.Context, id pgtype.UUID) (GetMemberWithUserRow, error)

func (*Queries) GetOrgUnit

func (q *Queries) GetOrgUnit(ctx context.Context, id pgtype.UUID) (OrgOrgUnit, error)

func (*Queries) GetOrgUnitType

func (q *Queries) GetOrgUnitType(ctx context.Context, key string) (OrgOrgUnitType, error)

SPDX-License-Identifier: Apache-2.0

func (*Queries) GetPosition

func (q *Queries) GetPosition(ctx context.Context, id pgtype.UUID) (OrgPosition, error)

func (*Queries) LinkMemberUser

func (q *Queries) LinkMemberUser(ctx context.Context, arg LinkMemberUserParams) (OrgMember, error)

func (*Queries) ListActiveCompaniesForKcSub

func (q *Queries) ListActiveCompaniesForKcSub(ctx context.Context, kcSub string) ([]ListActiveCompaniesForKcSubRow, error)

The company-switcher source — companies where kcSub has an ACTIVE membership in an ACTIVE company. One SQL query (member JOIN identity.user_read_v JOIN org_unit), filtered/sorted in SQL — never in-memory. Self-scoped by construction: kcSub is the caller's own identity, a param at the internal layer; the gateway injects the bearer's own kcSub, never trusting a client-supplied value. Both m.is_active (the membership) and ou.is_active (the company itself) are required — an inactive company is never offered as a switch target even if the membership row is still active.

func (*Queries) ListGroupMembers

func (q *Queries) ListGroupMembers(ctx context.Context, groupID pgtype.UUID) ([]ListGroupMembersRow, error)

Group membership read: member rows for a group, joined for display fields — the shape the admin surface and the assignable-groups module read both need.

func (*Queries) ListGroupsWithMemberCount

func (q *Queries) ListGroupsWithMemberCount(ctx context.Context, arg ListGroupsWithMemberCountParams) ([]ListGroupsWithMemberCountRow, error)

The admin list surface: each row carries its member count so the UI can render "N members" without a second round trip per row.

func (*Queries) ListMemberDirectory

func (q *Queries) ListMemberDirectory(ctx context.Context, arg ListMemberDirectoryParams) ([]ListMemberDirectoryRow, error)

The browser-reachable member directory (share-with/assign-to picker). REDUCED view (id/displayName/email/hasLinkedUser only — least disclosure) over ACTIVE members of one company, optional case-insensitive LITERAL substring filter on displayName/email (sqlc.narg — NULL means "no filter"; the store escapes `\`, `%`, `_` in q, hence ESCAPE '\'), filtered/sorted/paginated entirely in SQL.

func (*Queries) ListMembers

func (q *Queries) ListMembers(ctx context.Context, arg ListMembersParams) ([]ListMembersRow, error)

Member directory read: one SQL query, JOIN identity.user_read_v for linked-user display fields, paginated/authorized in SQL — never per-row API calls.

func (*Queries) ListPositions

func (q *Queries) ListPositions(ctx context.Context, arg ListPositionsParams) ([]OrgPosition, error)

func (*Queries) ListPositionsWithHolder

func (q *Queries) ListPositionsWithHolder(ctx context.Context, arg ListPositionsWithHolderParams) ([]ListPositionsWithHolderRow, error)

The admin list surface — each row carries the CURRENT assignment (assignmentId/memberId/ holder displayName), the fields the UI needs to END a tenure. "current" = today's half-open window (migrations/org/0009): valid_from <= today AND (valid_to IS NULL OR valid_to > today). today is the store's tenant-timezone date (the same clock assign-NOW/end-NOW stamp), never CURRENT_DATE (the DB session's zone — a second clock). LEFT JOINs so an unassigned position still returns a row with NULL assignment fields, never omitted.

func (*Queries) RemoveGroupMember

func (q *Queries) RemoveGroupMember(ctx context.Context, arg RemoveGroupMemberParams) (int64, error)

func (*Queries) SubtreeOrgUnits

func (q *Queries) SubtreeOrgUnits(ctx context.Context, id pgtype.UUID) ([]SubtreeOrgUnitsRow, error)

Recursive CTE, depth-bounded 32. Powers GET /internal/org/units/{id}/subtree and the cycle-proof parent-change validation (a candidate new parent must not already be in the moved unit's own subtree).

func (*Queries) UnlinkMemberUser

func (q *Queries) UnlinkMemberUser(ctx context.Context, id pgtype.UUID) (OrgMember, error)

func (*Queries) UpdateMember

func (q *Queries) UpdateMember(ctx context.Context, arg UpdateMemberParams) (OrgMember, error)

is_guest is optional: NULL keeps the current value.

func (*Queries) UpdateOrgUnit

func (q *Queries) UpdateOrgUnit(ctx context.Context, arg UpdateOrgUnitParams) (OrgOrgUnit, error)

type_key is deliberately absent: org-unit type is immutable after creation.

func (*Queries) UpdatePosition

func (q *Queries) UpdatePosition(ctx context.Context, arg UpdatePositionParams) (OrgPosition, error)

func (*Queries) WithTx

func (q *Queries) WithTx(tx pgx.Tx) *Queries

type ReferencedError

type ReferencedError struct {
	Table string
}

ReferencedError is the 409 CONFLICT for a DELETE refused by a foreign key: the row is still referenced from Table (the referencing table's name, e.g. "position_assignment") — the opposite of the INSERT/UPDATE-side "referenced row does not exist" 422.

func (*ReferencedError) Error

func (e *ReferencedError) Error() string

type RemoveGroupMemberParams

type RemoveGroupMemberParams struct {
	GroupID  pgtype.UUID `json:"group_id"`
	MemberID pgtype.UUID `json:"member_id"`
}

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service wires the store, the identity live-check client, the admin authorization guard, and the audit writer together for the HTTP handlers in http.go.

func NewService

func NewService(store *Store, identity IdentityStateChecker, authz AdminAuthorizer, auditWriter *audit.Writer) *Service

NewService builds a Service. auditWriter must be constructed against "audit.org__events" (see cmd/org/main.go).

func (*Service) Routes

func (svc *Service) Routes() http.Handler

Routes builds the org service's HTTP handler (stdlib net/http, Go 1.22+ pattern routing — same layout as registry and identity). Reads are open; mutations are guarded by AdminAuthorizer (fail-closed) and audited in-transaction.

type Store

type Store struct {
	// contains filtered or unexported fields
}

Store is the org service's data access layer: a pgx pool plus the sqlc-generated Queries built from it.

func NewStore

func NewStore(pool *pgxpool.Pool, auditWriter *audit.Writer) *Store

NewStore wraps an already-connected pool (the caller owns its lifecycle: connect with the service's own kiban_org credentials) plus the audit writer for "audit.org__events" (member mutations audit their full changed-field set).

func (*Store) AddGroupMember

func (s *Store) AddGroupMember(ctx context.Context, actor string, groupID, memberID uuid.UUID) (GroupMember, error)

AddGroupMember is the SOLE write path for Kiban-native group membership (the single-writer invariant). It:

  1. resolves the group and REFUSES (ErrGroupExternallyManaged, 409) unless group.IsKibanManaged() — enforced here, in the store, before any row is touched, so every human/API caller hits the SAME wall no matter which handler reaches this method;
  2. inserts the org.group_member row (the same-company trigger, migrations/org/0010, is the DB-level backstop for the store-level check below);
  3. grants `group:<id>#member @ member:<memberId>#mapped_user` in the SAME transaction;
  4. audits `org.group.member_add`.

memberID must resolve to an ACTIVE member of the group's own company (same posture as AssignNow's memberID check).

func (*Store) AssignNow

func (s *Store) AssignNow(ctx context.Context, actor string, positionID, memberID uuid.UUID) (Assignment, error)

AssignNow is the assign-NOW surface (`POST /internal/org/positions/{id}/assignments`): server sets valid_from = today (NO caller-supplied dates), grants `position:<id>#holder @ member:<memberId>#mapped_user` in the SAME transaction as the assignment row insert, and audits `org.assignment.create`. memberID must resolve to an ACTIVE member of positionID's own company.

func (*Store) AssignmentOnDate

func (s *Store) AssignmentOnDate(ctx context.Context, positionID uuid.UUID, date time.Time) (Assignment, error)

AssignmentOnDate answers "who holds position P on date D".

func (*Store) CompanyState

func (s *Store) CompanyState(ctx context.Context, id uuid.UUID) (exists bool, isActive bool, err error)

CompanyState reports whether id resolves to a COMPANY-typed org_unit and, if so, its is_active flag (`GET /internal/org/companies/{id}/state`, authz's decision.CompanySource step 5). A non-company-typed org_unit or an unknown id both report exists=false — never a fabricated company for the wrong type of unit.

func (*Store) CreateAndAssign

func (s *Store) CreateAndAssign(
	ctx context.Context, actor string,
	companyID uuid.UUID, code, title string, orgUnitID uuid.UUID,
	memberID uuid.UUID, validFrom time.Time, validTo *time.Time,
) (Position, Assignment, error)

CreateAndAssign is the combined create+assign operation (POST /internal/org/positions:create-and-assign, one transaction — a usability shortcut for small orgs): creates the position and its first assignment atomically — a failure at the assign step (e.g. the member doesn't exist, or an overlap somehow) rolls back the position creation too, so no orphan position is left behind.

func (*Store) CreateGroup

func (s *Store) CreateGroup(ctx context.Context, actor string, companyID uuid.UUID, code, name string) (Group, error)

CreateGroup creates a Kiban-native group (source is ALWAYS "kiban", external_ref is ALWAYS nil on this path — the only path the human/API surface ever calls). A sync-writer entrypoint that creates externally-sourced groups would be a DIFFERENT method; none exists.

func (*Store) CreateMember

func (s *Store) CreateMember(ctx context.Context, actor string, companyID uuid.UUID, code, displayName, email string, isActive, isGuest bool) (Member, error)

CreateMember creates a member, auditing the full field set in the same transaction.

func (*Store) CreateOrgUnit

func (s *Store) CreateOrgUnit(ctx context.Context, actor, typeKey string, parentID *uuid.UUID, code, name string, isActive bool) (OrgUnit, error)

CreateOrgUnit creates a new org unit, auditing in the SAME transaction as the state change — an audit failure rolls back the insert (fail closed). code/name are normalized/validated here (application layer) before insert; the DB CHECK constraints are the storage-level backstop.

func (*Store) CreatePosition

func (s *Store) CreatePosition(ctx context.Context, actor string, companyID uuid.UUID, code, title string, orgUnitID uuid.UUID) (Position, error)

CreatePosition creates a position slot, auditing in the same transaction.

func (*Store) DeleteOrgUnit

func (s *Store) DeleteOrgUnit(ctx context.Context, actor string, id uuid.UUID) error

DeleteOrgUnit deletes an org unit — guarded: cannot delete a unit with children or members. The guards run inside the delete transaction, after locking the unit row FOR UPDATE: a concurrent child/member insert takes FOR KEY SHARE on this row through its FK, so it either commits before the lock (the guard sees it → 422) or waits and then fails its FK (the unit is gone). Anything else still referencing the unit (positions, groups) surfaces as the FK's ReferencedError (409). Audited in the same transaction as the delete.

func (*Store) DeletePosition

func (s *Store) DeletePosition(ctx context.Context, actor string, id uuid.UUID) error

DeletePosition deletes a position. The FK from position_assignment (no ON DELETE CASCADE) is the storage-level guard against deleting a position with assignment history — it surfaces as a foreign_key_violation, classified to a 409 ReferencedError. A second guard runs inside the same transaction, after locking the position row FOR UPDATE (so a concurrent assignment insert, which takes FOR KEY SHARE on the row through its FK, serialises against the delete): refuse (PositionBoundError, 409) while any tuple still names `position:<id>#holder` as SUBJECT — i.e. some module (e.g. helpdesk) still binds an access tier to this position. Never cascade-revokes the other module's grant to unblock itself. Known ceiling: a module bind racing the delete (authz.tuple insert, no FK to org.position) can still land after the count; org's tree lock does not cover authz writes — a cross-service lock would be the upgrade if that race is ever observed.

func (*Store) EndAssignment

func (s *Store) EndAssignment(ctx context.Context, actor string, id uuid.UUID) (Assignment, error)

EndAssignment closes an assignment's validity window as of TODAY (the end-NOW surface — NO caller-supplied validTo) — a fact update, not a workflow (no approval/state-machine semantics here). Revokes `position:<id>#holder @ member:<memberId>#mapped_user` and audits `org.assignment.end`, both in the SAME transaction as the state change.

func (*Store) GetAssignment added in v0.1.1

func (s *Store) GetAssignment(ctx context.Context, id uuid.UUID) (Assignment, error)

GetAssignment reads one assignment; ErrAssignmentNotFound when absent.

func (*Store) GetGroup

func (s *Store) GetGroup(ctx context.Context, id uuid.UUID) (Group, error)

GetGroup looks up a group by id.

func (*Store) GetMember

func (s *Store) GetMember(ctx context.Context, id uuid.UUID) (Member, error)

GetMember looks up a member by id, joined with identity.user_read_v for linked-user display fields — a single SQL query, never a per-row identity call.

func (*Store) GetOrgUnit

func (s *Store) GetOrgUnit(ctx context.Context, id uuid.UUID) (OrgUnit, error)

GetOrgUnit looks up an org unit by id.

func (*Store) GetPosition

func (s *Store) GetPosition(ctx context.Context, id uuid.UUID) (Position, error)

GetPosition looks up a position by id.

func (*Store) Handover added in v0.2.0

func (s *Store) Handover(ctx context.Context, actor string, positionID, memberID uuid.UUID, expected *uuid.UUID) (ended *Assignment, created Assignment, err error)

Handover ends the position's current assignment and assigns memberID in one transaction, so no check between the two ever finds the position empty. It refuses an empty position (a ValidationError: use AssignNow), an inactive member and a member of another company; it is idempotent when memberID already holds the position (ended is nil, the current assignment is returned); and when expected names an assignment that is no longer the current one it answers PositionHeldError with the current holder, so two administrators cannot both think they handed the position over. Both audit events carry the same handoverId.

func (*Store) LinkUser

func (s *Store) LinkUser(ctx context.Context, actor string, checker IdentityStateChecker, memberID uuid.UUID, kcSub string) (Member, error)

LinkUser links memberID to the identity user identified by kcSub. It NEVER trusts kcSub as given: it first confirms the account exists via an HTTP call to identity (checker), then resolves the internal user_id via the published identity.user_read_v view — the only way org reads identity data — before writing the FK. UNIQUE(company_id, user_id) rejects a second member linking the same user in the same company.

func (*Store) ListActiveCompaniesForKcSub

func (s *Store) ListActiveCompaniesForKcSub(ctx context.Context, kcSub string) ([]CompanySummary, error)

ListActiveCompaniesForKcSub returns the companies where kcSub has an active membership in an active company (`GET /internal/org/me/companies`, the company-switcher source) — one SQL query, filtered/sorted in SQL. An unknown kcSub (no linked user, or a user with no active memberships) returns an empty slice, never an error.

func (*Store) ListActiveGroups added in v0.2.0

func (s *Store) ListActiveGroups(ctx context.Context, companyID uuid.UUID, page, pageSize int) ([]Group, int, error)

ListGroupsWithMemberCount returns companyID's groups, paginated, each with its current member count. ListActiveGroups is the directory read: the company's active groups, by code.

func (*Store) ListGroupMembers

func (s *Store) ListGroupMembers(ctx context.Context, groupID uuid.UUID) ([]GroupMember, error)

ListGroupMembers returns groupID's current members, joined with display fields.

func (*Store) ListGroupsWithMemberCount

func (s *Store) ListGroupsWithMemberCount(ctx context.Context, companyID uuid.UUID, page, pageSize int) ([]GroupWithMemberCount, int, error)

func (*Store) ListMembers

func (s *Store) ListMembers(ctx context.Context, companyID uuid.UUID, page, pageSize int) ([]Member, int, error)

ListMembers returns companyID's member directory, page/pageSize (default 1/25, clamp 1..100), joined with identity.user_read_v — filtered/paginated in SQL, never in-memory.

func (*Store) ListPositions

func (s *Store) ListPositions(ctx context.Context, companyID uuid.UUID, page, pageSize int) ([]Position, int, error)

ListPositions returns companyID's positions, paginated.

func (*Store) ListPositionsWithHolder

func (s *Store) ListPositionsWithHolder(ctx context.Context, companyID uuid.UUID, page, pageSize int) ([]PositionWithHolder, int, error)

ListPositionsWithHolder is ListPositions plus each row's current assignment — the admin surface. Paginated identically to ListPositions.

func (*Store) MemberByCompanyAndKcSub

func (s *Store) MemberByCompanyAndKcSub(ctx context.Context, companyID uuid.UUID, kcSub string) (isMember bool, memberID uuid.UUID, isActive bool, err error)

MemberByCompanyAndKcSub resolves the member (if any) linking kcSub within companyID (`GET /internal/org/companies/{id}/members/by-kcsub/{kcSub}`, authz's decision.MembershipSource step 5) — joined via the published identity.user_read_v view, same read path ListMembers/GetMemberWithUser already use. No row (unknown kcSub, or a member in a different company) reports isMember=false — never a fabricated membership.

func (*Store) MemberDirectory

func (s *Store) MemberDirectory(ctx context.Context, companyID uuid.UUID, q string, page, pageSize int) ([]MemberDirectoryEntry, int, error)

MemberDirectory returns companyID's ACTIVE member directory (the share-with/assign-to picker modules such as docs and helpdesk need), optionally filtered by a substring q (case-insensitive LITERAL substring, matched against displayName OR email, parameterized ILIKE with its wildcards escaped — never string-concatenated into SQL). page/pageSize follow the same 1/25, clamp 1..100 convention as ListMembers.

func (*Store) MemberFactByKcSub added in v0.2.0

func (s *Store) MemberFactByKcSub(ctx context.Context, companyID uuid.UUID, kcSub string) (MemberFact, error)

MemberFactByKcSub is MemberByCompanyAndKcSub with the guest flag.

func (*Store) Pool

func (s *Store) Pool() *pgxpool.Pool

Pool returns the underlying pool (used by http.go for the /ready liveness check).

func (*Store) RemoveGroupMember

func (s *Store) RemoveGroupMember(ctx context.Context, actor string, groupID, memberID uuid.UUID) error

RemoveGroupMember is the SOLE revocation path for Kiban-native group membership — the mirror of AddGroupMember. Same single-writer refusal, ahead of any row touch; revokes the group:*#member tuple via the SECURITY DEFINER function (migrations/authz/0007 widened its allow-list for exactly this shape) — never a raw DELETE from application code.

func (*Store) Subtree

func (s *Store) Subtree(ctx context.Context, id uuid.UUID) ([]OrgUnit, error)

Subtree returns id's subtree (itself plus every descendant), depth-bounded 32, via the recursive CTE — powers GET /internal/org/units/{id}/subtree.

func (*Store) UnlinkUser

func (s *Store) UnlinkUser(ctx context.Context, actor string, memberID uuid.UUID) (Member, error)

UnlinkUser clears memberID's user link.

func (*Store) UpdateMember

func (s *Store) UpdateMember(ctx context.Context, actor string, id uuid.UUID, displayName, email string, isActive bool, isGuest *bool) (Member, error)

UpdateMember updates display_name/email/is_active, auditing the full before/after field set in the same transaction. email is the only PII field (field-policy-eligible). UpdateMember changes the display fields and the active flag; isGuest nil keeps the current value.

func (*Store) UpdateOrgUnit

func (s *Store) UpdateOrgUnit(ctx context.Context, actor string, id uuid.UUID, parentID *uuid.UUID, code, name string, isActive bool) (OrgUnit, error)

UpdateOrgUnit updates parent/code/name/is_active. type_key is immutable (the query has no type_key column at all). Moving a unit under a new parent is validated as cycle-proof: the candidate parent must not already be in this unit's own subtree (which would make it its own descendant's descendant).

func (*Store) UpdatePosition

func (s *Store) UpdatePosition(ctx context.Context, actor string, id uuid.UUID, title string, orgUnitID uuid.UUID) (Position, error)

UpdatePosition updates title/org_unit_id. company_id/code are immutable after creation (UNIQUE(company_id, code) is the identity of the slot).

type SubtreeOrgUnitsRow

type SubtreeOrgUnitsRow struct {
	ID       pgtype.UUID `json:"id"`
	TypeKey  string      `json:"type_key"`
	ParentID pgtype.UUID `json:"parent_id"`
	Code     string      `json:"code"`
	Name     string      `json:"name"`
	IsActive bool        `json:"is_active"`
	Depth    int32       `json:"depth"`
}

type UpdateMemberParams

type UpdateMemberParams struct {
	ID          pgtype.UUID `json:"id"`
	DisplayName string      `json:"display_name"`
	Email       *string     `json:"email"`
	IsActive    bool        `json:"is_active"`
	IsGuest     *bool       `json:"is_guest"`
}

type UpdateOrgUnitParams

type UpdateOrgUnitParams struct {
	ID       pgtype.UUID `json:"id"`
	ParentID pgtype.UUID `json:"parent_id"`
	Code     string      `json:"code"`
	Name     string      `json:"name"`
	IsActive bool        `json:"is_active"`
}

type UpdatePositionParams

type UpdatePositionParams struct {
	ID        pgtype.UUID `json:"id"`
	Title     string      `json:"title"`
	OrgUnitID pgtype.UUID `json:"org_unit_id"`
}

type ValidationError

type ValidationError struct {
	Field   string
	Message string
}

ValidationError is a 422 VALIDATION_ERROR {field} condition — returned by both application-level input validation and by classifying a Postgres CHECK/trigger violation back to its field.

func (*ValidationError) Error

func (e *ValidationError) Error() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL