Files
lincodex/backend/internal/usecase/organization/service.go
T

462 lines
18 KiB
Go

// Package organization creates organizations and lets their owners edit the
// company profile.
package organization
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
const (
createOperation = "organization.create"
createLocation = "organization.Service.Create"
maxIdempotencyKeySize = 255
maxCanonicalBodySize = 1 << 20
purgeExpiredBatch = 100
)
// Keyring computes scoped idempotency digests. identity.Keyring implements
// this interface so the feature uses the existing server secret and storage.
type Keyring interface {
IdempotencyScope(operation, key, principal string) [outbound.IdempotencyDigestSize]byte
Fingerprint(canonicalBody []byte) [outbound.IdempotencyDigestSize]byte
}
// Dependencies are the collaborators of Service.
type Dependencies struct {
Transactor outbound.Transactor
Keyring Keyring
Clock func() time.Time
}
// Service applies organization commands. It stores no request state.
type Service struct {
transactor outbound.Transactor
keyring Keyring
clock func() time.Time
}
// NewService fails at startup when a required dependency is missing.
func NewService(deps Dependencies) (*Service, error) {
if deps.Transactor == nil || deps.Keyring == nil || deps.Clock == nil {
return nil, errors.New("organization.NewService - every dependency must be set")
}
return &Service{transactor: deps.Transactor, keyring: deps.Keyring, clock: deps.Clock}, nil
}
// CreateCommand is the caller and profile content of one create request.
type CreateCommand struct {
ActorID uuid.UUID
IdempotencyKey string
CanonicalBody []byte
Profile domain.OrganizationProfileInput
}
// CreateResult is the organization and owner membership created by a request.
// Replayed marks an identical request answered from the immutable result
// snapshot; it does not change the public status or body.
type CreateResult struct {
Organization domain.Organization
Owner domain.Membership
Replayed bool
}
type createRequest struct {
command CreateCommand
fingerprint [outbound.IdempotencyDigestSize]byte
scope [outbound.IdempotencyDigestSize]byte
record outbound.IdempotencyRecord
now time.Time
}
// Create creates a company and its active owner membership in one
// transaction. An identical key and body returns the original creation
// snapshot, even if the live profile has since changed.
func (service *Service) Create(ctx context.Context, command CreateCommand) (CreateResult, error) {
request, err := service.prepareCreateRequest(command)
if err != nil {
return CreateResult{}, err
}
var result CreateResult
err = service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
created, err := service.createInTransaction(ctx, unit, request)
if err != nil {
return err
}
result = created
return nil
})
if err != nil {
return CreateResult{}, fmt.Errorf("%s - run transaction: %w", createLocation, err)
}
return result, nil
}
func (service *Service) prepareCreateRequest(command CreateCommand) (createRequest, error) {
switch {
case command.ActorID == uuid.Nil:
return createRequest{}, fmt.Errorf("%s - actor ID must be set: %w", createLocation, ErrForbidden)
case command.IdempotencyKey == "" || len(command.IdempotencyKey) > maxIdempotencyKeySize:
return createRequest{}, fmt.Errorf("%s - idempotency key must have 1 to 255 bytes: %w", createLocation, ErrInvalidIdempotencyKey)
}
canonical := command.CanonicalBody
if len(canonical) == 0 {
var err error
canonical, err = canonicalCreateBody(command.Profile)
if err != nil {
return createRequest{}, fmt.Errorf("%s - encode canonical profile", createLocation)
}
}
if len(canonical) > maxCanonicalBodySize {
return createRequest{}, fmt.Errorf("%s - request body exceeds its bound: %w", createLocation, ErrInvalidCreateRequest)
}
fingerprint := service.keyring.Fingerprint(canonical)
scope := service.keyring.IdempotencyScope(createOperation, command.IdempotencyKey, command.ActorID.String())
now := service.clock()
if now.IsZero() {
return createRequest{}, fmt.Errorf("%s - application time must be set", createLocation)
}
record := outbound.IdempotencyRecord{
Scope: scope, Fingerprint: fingerprint, CreatedAt: now, ExpiresAt: now.Add(outbound.IdempotencyRetention),
}
return createRequest{command: command, fingerprint: fingerprint, scope: scope, record: record, now: now}, nil
}
func (service *Service) createInTransaction(
ctx context.Context,
unit outbound.UnitOfWork,
request createRequest,
) (CreateResult, error) {
if err := requireEmployer(ctx, unit, request.command.ActorID, createLocation); err != nil {
return CreateResult{}, fmt.Errorf("%s - authorize creator: %w", createLocation, err)
}
stored, created, err := unit.IdempotencyRecords().Reserve(ctx, request.record)
if err != nil {
return CreateResult{}, fmt.Errorf("%s - reserve idempotency record: %w", createLocation, err)
}
if !created {
return replayCreation(ctx, unit, request, stored)
}
return service.createOrganization(ctx, unit, request)
}
func replayCreation(
ctx context.Context,
unit outbound.UnitOfWork,
request createRequest,
stored outbound.IdempotencyRecord,
) (CreateResult, error) {
if stored.Fingerprint != request.fingerprint {
return CreateResult{}, ErrIdempotencyKeyReused
}
snapshot, err := unit.Organizations().GetCreationResult(ctx, request.scope)
if err != nil {
return CreateResult{}, fmt.Errorf("%s - read creation snapshot: %w", createLocation, err)
}
if !validCreationSnapshot(snapshot, request.command.ActorID) {
return CreateResult{}, fmt.Errorf("%s - stored creation snapshot does not match the actor: %w", createLocation, domain.ErrInvalidMembership)
}
return CreateResult{Organization: snapshot.Organization, Owner: snapshot.Owner, Replayed: true}, nil
}
func validCreationSnapshot(snapshot outbound.OrganizationCreationResult, actorID uuid.UUID) bool {
if snapshot.Organization.IsZero() || snapshot.Owner.IsZero() {
return false
}
return snapshot.Owner.UserID() == actorID &&
snapshot.Owner.OrganizationID() == snapshot.Organization.ID() &&
snapshot.Owner.Role() == domain.OrganizationRoleOwner && snapshot.Owner.GrantsAccess()
}
func (service *Service) createOrganization(
ctx context.Context,
unit outbound.UnitOfWork,
request createRequest,
) (CreateResult, error) {
profile, err := domain.NewOrganizationProfile(request.command.Profile)
if err != nil {
return CreateResult{}, fmt.Errorf("%s - validate profile: %w", createLocation, err)
}
company, err := domain.NewOrganization(profile, request.now)
if err != nil {
return CreateResult{}, fmt.Errorf("%s - build organization: %w", createLocation, err)
}
owner, err := domain.NewOwnerMembership(company.ID(), request.command.ActorID, request.now)
if err != nil {
return CreateResult{}, fmt.Errorf("%s - build owner membership: %w", createLocation, err)
}
if err := unit.Organizations().CreateWithOwner(ctx, company, owner); err != nil {
return CreateResult{}, fmt.Errorf("%s - store organization and owner: %w", createLocation, err)
}
creation := outbound.OrganizationCreationResult{Organization: company, Owner: owner}
if err := unit.Organizations().SaveCreationResult(ctx, request.scope, creation); err != nil {
return CreateResult{}, fmt.Errorf("%s - store creation snapshot: %w", createLocation, err)
}
if _, err := unit.IdempotencyRecords().PurgeExpired(ctx, request.now, purgeExpiredBatch); err != nil {
return CreateResult{}, fmt.Errorf("%s - purge expired idempotency records: %w", createLocation, err)
}
return CreateResult{Organization: company, Owner: owner}, nil
}
func canonicalCreateBody(profile domain.OrganizationProfileInput) ([]byte, error) {
// An ordered array makes the fingerprint stable for non-HTTP callers.
return json.Marshal([]any{
profile.Name,
profile.Description,
profile.Sphere,
profile.Contacts.Website,
profile.Contacts.Email,
profile.Contacts.Phone,
profile.Contacts.Telegram,
profile.Representatives,
})
}
// OptionalString distinguishes an absent field from a present value. An empty
// value clears nullable description and sphere fields.
type OptionalString struct {
Set bool
Value string
}
// ProfilePatch is the set of editable fields present in an update request.
// Contacts and representatives replace their complete value when set.
type ProfilePatch struct {
Name OptionalString
Description OptionalString
Sphere OptionalString
Contacts *domain.OrganizationContactsInput
Representatives *[]domain.OrganizationRepresentativeInput
}
// UpdateCommand describes a versioned profile edit.
type UpdateCommand struct {
ActorID uuid.UUID
OrganizationID uuid.UUID
ExpectedVersion int64
Patch ProfilePatch
}
// Update merges the patch over the current profile, preserves verification,
// and checks that the acting account is the active owner.
func (service *Service) Update(ctx context.Context, command UpdateCommand) (domain.Organization, error) {
const location = "organization.Service.Update"
if command.ActorID == uuid.Nil || command.OrganizationID == uuid.Nil {
return domain.Organization{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", location, ErrForbidden)
}
if err := matchCompanyContext(ctx, command.ActorID, command.OrganizationID, location); err != nil {
return domain.Organization{}, err
}
if command.ExpectedVersion < 1 {
return domain.Organization{}, fmt.Errorf("%s - expected version must be positive: %w", location, domain.ErrInvalidOrganization)
}
var result domain.Organization
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := requireEmployer(ctx, unit, command.ActorID, location); err != nil {
return fmt.Errorf("%s - authorize editor: %w", location, err)
}
current, membership, err := unit.Organizations().GetForMember(ctx, command.OrganizationID, command.ActorID)
if err != nil {
return fmt.Errorf("%s - read organization for member: %w", location, err)
}
if !membership.CanManageOrganization() {
return fmt.Errorf("%s - require active owner: %w", location, outbound.ErrOrganizationManagerRequired)
}
profile, err := applyPatch(current.Profile(), command.Patch)
if err != nil {
if command.ExpectedVersion != current.Version() {
return fmt.Errorf("%s - expected version %d, current version %d: %w", location,
command.ExpectedVersion, current.Version(), outbound.ErrOrganizationVersionConflict)
}
return fmt.Errorf("%s - validate profile: %w", location, err)
}
if current.Profile().Equal(profile) {
result = current
return nil
}
if command.ExpectedVersion != current.Version() {
return fmt.Errorf("%s - expected version %d, current version %d: %w", location,
command.ExpectedVersion, current.Version(), outbound.ErrOrganizationVersionConflict)
}
updated, err := current.ApplyProfile(profile, service.clock())
if err != nil {
return fmt.Errorf("%s - apply profile: %w", location, err)
}
result, err = unit.Organizations().UpdateProfile(ctx, command.ActorID, updated)
if err != nil {
return fmt.Errorf("%s - store profile: %w", location, err)
}
return nil
})
if err != nil {
return domain.Organization{}, fmt.Errorf("%s - run transaction: %w", location, err)
}
return result, nil
}
// Get reads an organization only for its active owner. The membership is
// checked in the same transaction as the account.
func (service *Service) Get(ctx context.Context, actorID, organizationID uuid.UUID) (domain.Organization, error) {
const location = "organization.Service.Get"
if actorID == uuid.Nil || organizationID == uuid.Nil {
return domain.Organization{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", location, ErrForbidden)
}
if err := matchCompanyContext(ctx, actorID, organizationID, location); err != nil {
return domain.Organization{}, err
}
var result domain.Organization
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := requireEmployer(ctx, unit, actorID, location); err != nil {
return fmt.Errorf("%s - authorize reader: %w", location, err)
}
organization, membership, err := unit.Organizations().GetForMember(ctx, organizationID, actorID)
if err != nil {
return fmt.Errorf("%s - read organization for member: %w", location, err)
}
if !membership.GrantsAccess() {
return fmt.Errorf("%s - require active membership: %w", location, outbound.ErrOrganizationNotFound)
}
if membership.Role() != domain.OrganizationRoleOwner {
return fmt.Errorf("%s - require active owner: %w", location, outbound.ErrOrganizationManagerRequired)
}
result = organization
return nil
})
if err != nil {
return domain.Organization{}, fmt.Errorf("%s - run transaction: %w", location, err)
}
return result, nil
}
// AuthorizeCompany verifies the current verified employer account, active
// membership, and owner role before issuing a request-scoped capability.
func (service *Service) AuthorizeCompany(ctx context.Context, actorID, organizationID uuid.UUID) (CompanyAccess, error) {
const location = "organization.Service.AuthorizeCompany"
if actorID == uuid.Nil || organizationID == uuid.Nil {
return CompanyAccess{}, fmt.Errorf("%s - actor and organization IDs must be set: %w", location, ErrForbidden)
}
var access CompanyAccess
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := requireEmployer(ctx, unit, actorID, location); err != nil {
return fmt.Errorf("%s - authorize company actor: %w", location, err)
}
_, membership, err := unit.Organizations().GetForMember(ctx, organizationID, actorID)
if err != nil {
return fmt.Errorf("%s - read active company membership: %w", location, err)
}
if !membership.GrantsAccess() {
return fmt.Errorf("%s - require active membership: %w", location, outbound.ErrOrganizationNotFound)
}
if membership.Role() != domain.OrganizationRoleOwner {
return fmt.Errorf("%s - require active owner: %w", location, outbound.ErrOrganizationManagerRequired)
}
access = CompanyAccess{actorID: actorID, organizationID: organizationID, membershipID: membership.ID()}
return nil
})
if err != nil {
return CompanyAccess{}, fmt.Errorf("%s - run transaction: %w", location, err)
}
return access, nil
}
// ListMyOrganizations returns active organization memberships for one
// verified employer. The actor always comes from the authenticated session.
func (service *Service) ListMyOrganizations(ctx context.Context, command OrganizationListCommand) (outbound.OrganizationPage, error) {
const location = "organization.Service.ListMyOrganizations"
if command.ActorID == uuid.Nil {
return outbound.OrganizationPage{}, fmt.Errorf("%s - actor ID must be set: %w", location, ErrForbidden)
}
if command.Limit < 1 || command.Limit > outbound.MaxOrganizationPageSize {
return outbound.OrganizationPage{}, fmt.Errorf("%s - limit must be 1 to %d: %w", location, outbound.MaxOrganizationPageSize, domain.ErrInvalidMembership)
}
var result outbound.OrganizationPage
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if err := requireEmployer(ctx, unit, command.ActorID, location); err != nil {
return fmt.Errorf("%s - authorize list actor: %w", location, err)
}
page, err := unit.Organizations().ListForUser(ctx, outbound.OrganizationListQuery{
UserID: command.ActorID, After: command.After, Limit: command.Limit,
})
if err != nil {
return fmt.Errorf("%s - list active memberships: %w", location, err)
}
result = page
return nil
})
if err != nil {
return outbound.OrganizationPage{}, fmt.Errorf("%s - run transaction: %w", location, err)
}
return result, nil
}
// OrganizationListCommand selects a page of the actor's own memberships.
type OrganizationListCommand struct {
ActorID uuid.UUID
After *outbound.OrganizationListPosition
Limit int32
}
func matchCompanyContext(ctx context.Context, actorID, organizationID uuid.UUID, location string) error {
access, ok := CompanyAccessFromContext(ctx)
if ok && !access.Matches(actorID, organizationID) {
return fmt.Errorf("%s - company context does not match the operation: %w", location, ErrForbidden)
}
return nil
}
func applyPatch(current domain.OrganizationProfile, patch ProfilePatch) (domain.OrganizationProfile, error) {
contacts := current.Contacts()
input := domain.OrganizationProfileInput{
Name: current.Name(), Description: current.Description(), Sphere: current.Sphere(),
Contacts: domain.OrganizationContactsInput{
Website: contacts.Website(), Email: contacts.Email(), Phone: contacts.Phone(), Telegram: contacts.Telegram(),
},
}
for _, representative := range current.Representatives() {
input.Representatives = append(input.Representatives, domain.OrganizationRepresentativeInput{
Name: representative.Name(), JobTitle: representative.JobTitle(),
})
}
if patch.Name.Set {
input.Name = patch.Name.Value
}
if patch.Description.Set {
input.Description = patch.Description.Value
}
if patch.Sphere.Set {
input.Sphere = patch.Sphere.Value
}
if patch.Contacts != nil {
input.Contacts = *patch.Contacts
}
if patch.Representatives != nil {
input.Representatives = append([]domain.OrganizationRepresentativeInput(nil), (*patch.Representatives)...)
}
return domain.NewOrganizationProfile(input)
}
func requireEmployer(ctx context.Context, unit outbound.UnitOfWork, actorID uuid.UUID, location string) error {
user, err := unit.Users().GetByID(ctx, actorID)
if err != nil {
if errors.Is(err, outbound.ErrUserNotFound) {
return ErrForbidden
}
return fmt.Errorf("%s - read account: %w", location, err)
}
if !user.EmailVerified() {
return ErrEmailNotVerified
}
if user.Scenario != domain.ScenarioEmployer {
return ErrForbidden
}
return nil
}