Files
lincodex/backend/internal/adapter/primary/http/v1/organization.go
T

432 lines
17 KiB
Go

package v1
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/adapter/primary/http/problem"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/organization"
)
// OrganizationOperations are the organization commands and reads served by
// this HTTP adapter.
type OrganizationOperations interface {
Create(ctx context.Context, command organization.CreateCommand) (organization.CreateResult, error)
Get(ctx context.Context, actorID, organizationID uuid.UUID) (domain.Organization, error)
AuthorizeCompany(ctx context.Context, actorID, organizationID uuid.UUID) (organization.CompanyAccess, error)
ListMyOrganizations(ctx context.Context, command organization.OrganizationListCommand) (outbound.OrganizationPage, error)
Update(ctx context.Context, command organization.UpdateCommand) (domain.Organization, error)
}
// CreateOrganization delegates company creation to its business-area handler.
func (handler *Handler) CreateOrganization(
ctx context.Context,
request *api.OrganizationCreate,
params api.CreateOrganizationParams,
) (api.CreateOrganizationRes, error) {
if handler.organization == nil {
return handler.UnimplementedHandler.CreateOrganization(ctx, request, params)
}
return handler.organization.CreateOrganization(ctx, request, params)
}
// GetOrganization delegates company reads to their business-area handler.
func (handler *Handler) GetOrganization(
ctx context.Context,
params api.GetOrganizationParams,
) (api.GetOrganizationRes, error) {
if handler.organization == nil {
return handler.UnimplementedHandler.GetOrganization(ctx, params)
}
return handler.organization.GetOrganization(ctx, params)
}
// ListMyOrganizations delegates the session-scoped company directory to its
// business-area handler.
func (handler *Handler) ListMyOrganizations(
ctx context.Context,
params api.ListMyOrganizationsParams,
) (api.ListMyOrganizationsRes, error) {
if handler.organization == nil {
return handler.UnimplementedHandler.ListMyOrganizations(ctx, params)
}
return handler.organization.ListMyOrganizations(ctx, params)
}
// UpdateOrganization delegates company edits to their business-area handler.
func (handler *Handler) UpdateOrganization(
ctx context.Context,
request *api.OrganizationUpdate,
params api.UpdateOrganizationParams,
) (api.UpdateOrganizationRes, error) {
if handler.organization == nil {
return handler.UnimplementedHandler.UpdateOrganization(ctx, request, params)
}
return handler.organization.UpdateOrganization(ctx, request, params)
}
// OrganizationHandler serves organization create, read, and profile update
// operations.
type OrganizationHandler struct {
operations OrganizationOperations
publicOrigin string
}
func NewOrganizationHandler(operations OrganizationOperations, publicOrigin string) *OrganizationHandler {
return &OrganizationHandler{operations: operations, publicOrigin: publicOrigin}
}
// AuthorizeCompany delegates current owner membership checks to the use case.
func (handler *OrganizationHandler) AuthorizeCompany(
ctx context.Context,
actorID, organizationID uuid.UUID,
) (organization.CompanyAccess, error) {
if handler == nil || handler.operations == nil {
return organization.CompanyAccess{}, errors.New("OrganizationHandler.AuthorizeCompany - organization operations are not configured")
}
return handler.operations.AuthorizeCompany(ctx, actorID, organizationID)
}
func (handler *OrganizationHandler) CreateOrganization(
ctx context.Context,
request *api.OrganizationCreate,
params api.CreateOrganizationParams,
) (api.CreateOrganizationRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.CreateOrganizationUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
if !originAllowed(ctx, handler.publicOrigin) {
return (*api.CreateOrganizationForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil
}
if request == nil {
return (*api.CreateOrganizationBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
}
canonicalBody, err := json.Marshal(request)
if err != nil {
return nil, err
}
result, err := handler.operations.Create(ctx, organization.CreateCommand{
ActorID: principal.UserID, IdempotencyKey: params.IdempotencyKey, CanonicalBody: canonicalBody,
Profile: createProfileInput(request),
})
if err != nil {
return createOrganizationFailure(ctx, err)
}
return &api.OrganizationHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: organizationFromDomain(result.Organization),
}, nil
}
func (handler *OrganizationHandler) GetOrganization(
ctx context.Context,
params api.GetOrganizationParams,
) (api.GetOrganizationRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.GetOrganizationUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
company, err := handler.operations.Get(ctx, principal.UserID, params.OrgID)
if err != nil {
return getOrganizationFailure(ctx, err)
}
return &api.OrganizationHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: organizationFromDomain(company),
}, nil
}
func (handler *OrganizationHandler) UpdateOrganization(
ctx context.Context,
request *api.OrganizationUpdate,
params api.UpdateOrganizationParams,
) (api.UpdateOrganizationRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.UpdateOrganizationUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
if !originAllowed(ctx, handler.publicOrigin) {
return (*api.UpdateOrganizationForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil
}
if request == nil {
return (*api.UpdateOrganizationBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
}
company, err := handler.operations.Update(ctx, organization.UpdateCommand{
ActorID: principal.UserID, OrganizationID: params.OrgID,
ExpectedVersion: int64(request.ExpectedVersion), Patch: updateProfilePatch(request),
})
if err != nil {
return updateOrganizationFailure(ctx, err)
}
return &api.OrganizationHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: organizationFromDomain(company),
}, nil
}
func (handler *OrganizationHandler) ListMyOrganizations(
ctx context.Context,
params api.ListMyOrganizationsParams,
) (api.ListMyOrganizationsRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.ListMyOrganizationsUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
command, paramErr := organizationListCommand(principal.UserID, params)
if paramErr != nil {
return organizationListInvalid(ctx, paramErr.pointer), nil
}
page, err := handler.operations.ListMyOrganizations(ctx, command)
if err != nil {
switch {
case errors.Is(err, organization.ErrForbidden):
return (*api.ListMyOrganizationsForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, organization.ErrEmailNotVerified):
return (*api.ListMyOrganizationsForbidden)(&problem.New(ctx, api.ProblemCodeEmailNotVerified).Response), nil
case errors.Is(err, domain.ErrInvalidMembership):
return organizationListInvalid(ctx, "cursor"), nil
default:
return nil, err
}
}
items := make([]api.MyOrganization, 0, len(page.Items))
for _, item := range page.Items {
items = append(items, myOrganizationFromDomain(item))
}
var nextCursor api.NilString
nextCursor.SetToNull()
if page.HasMore && len(page.Items) > 0 {
cursor, err := encodeOrganizationCursor(principal.UserID, outbound.OrganizationPositionOf(page.Items[len(page.Items)-1]))
if err != nil {
return nil, fmt.Errorf("OrganizationHandler.ListMyOrganizations - encode cursor: %w", err)
}
nextCursor.SetTo(cursor)
}
return &api.MyOrganizationListHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: api.MyOrganizationList{
Items: items,
Page: api.PageInfo{HasMore: page.HasMore, NextCursor: nextCursor},
},
}, nil
}
func createProfileInput(request *api.OrganizationCreate) domain.OrganizationProfileInput {
contacts := request.Contacts.Or(api.OrganizationContactChannels{})
description, _ := request.Description.Get()
sphere, _ := request.Sphere.Get()
representatives := make([]domain.OrganizationRepresentativeInput, 0, len(request.Representatives))
for _, representative := range request.Representatives {
representatives = append(representatives, domain.OrganizationRepresentativeInput{
Name: representative.Name, JobTitle: representative.JobTitle,
})
}
return domain.OrganizationProfileInput{
Name: string(request.Name), Description: string(description), Sphere: string(sphere),
Contacts: contactsToDomain(contacts), Representatives: representatives,
}
}
func updateProfilePatch(request *api.OrganizationUpdate) organization.ProfilePatch {
var patch organization.ProfilePatch
if request.Name.Set {
patch.Name = organization.OptionalString{Set: true, Value: string(request.Name.Value)}
}
if request.Description.Set {
value := ""
if !request.Description.Null {
value = string(request.Description.Value)
}
patch.Description = organization.OptionalString{Set: true, Value: value}
}
if request.Sphere.Set {
value := ""
if !request.Sphere.Null {
value = string(request.Sphere.Value)
}
patch.Sphere = organization.OptionalString{Set: true, Value: value}
}
if request.Contacts.Set {
contacts, _ := request.Contacts.Get()
input := contactsToDomain(contacts)
patch.Contacts = &input
}
if request.Representatives != nil {
representatives := make([]domain.OrganizationRepresentativeInput, 0, len(request.Representatives))
for _, representative := range request.Representatives {
representatives = append(representatives, domain.OrganizationRepresentativeInput{
Name: representative.Name, JobTitle: representative.JobTitle,
})
}
patch.Representatives = &representatives
}
return patch
}
func contactsToDomain(contacts api.OrganizationContactChannels) domain.OrganizationContactsInput {
website, _ := contacts.Website.Get()
email, _ := contacts.Email.Get()
phone, _ := contacts.Phone.Get()
telegram, _ := contacts.Telegram.Get()
return domain.OrganizationContactsInput{
Website: string(website), Email: string(email), Phone: string(phone), Telegram: string(telegram),
}
}
func organizationFromDomain(company domain.Organization) api.Organization {
profile := company.Profile()
verification := company.Verification()
representatives := representativesFromDomain(profile.Representatives())
card := company.CandidateCard()
return api.Organization{
ID: company.ID(), Version: api.OrganizationVersion(company.Version()),
Name: api.OrganizationName(profile.Name()), Description: nullableDescription(profile.Description()),
Sphere: nullableSphere(profile.Sphere()), Contacts: contactsFromDomain(profile.Contacts()),
Representatives: representatives,
Verification: api.OrganizationVerification{
Level: api.OrganizationVerificationLevel(verification.Level()),
Basis: api.OrganizationVerificationBasis(verification.Basis()),
ChangedAt: api.Timestamp(verification.ChangedAt()),
},
CandidateCard: candidateCardFromDomain(card),
CreatedAt: api.Timestamp(company.CreatedAt()),
UpdatedAt: api.Timestamp(company.UpdatedAt()),
}
}
func candidateCardFromDomain(card domain.OrganizationCandidateCard) api.CandidateOrganizationCard {
profile := card.Profile()
representatives := representativesFromDomain(profile.Representatives())
optionalRepresentatives := api.NewOptNilOrganizationRepresentativeArray(representatives)
return api.CandidateOrganizationCard{
ID: card.ID(), Name: api.OrganizationName(profile.Name()),
Description: nullableDescription(profile.Description()), Sphere: nullableSphere(profile.Sphere()),
Contacts: contactsFromDomain(profile.Contacts()), Representatives: optionalRepresentatives,
VerificationLevel: api.OrganizationVerificationLevel(card.VerificationLevel()),
}
}
func representativesFromDomain(source []domain.OrganizationRepresentative) []api.OrganizationRepresentative {
representatives := make([]api.OrganizationRepresentative, 0, len(source))
for _, representative := range source {
representatives = append(representatives, api.OrganizationRepresentative{
Name: representative.Name(), JobTitle: representative.JobTitle(),
})
}
return representatives
}
func nullableDescription(value string) api.NilOrganizationDescription {
if value == "" {
return api.NilOrganizationDescription{Null: true}
}
return api.NewNilOrganizationDescription(api.OrganizationDescription(value))
}
func nullableSphere(value string) api.NilOrganizationSphere {
if value == "" {
return api.NilOrganizationSphere{Null: true}
}
return api.NewNilOrganizationSphere(api.OrganizationSphere(value))
}
func contactsFromDomain(contacts domain.OrganizationContacts) api.OrganizationContactChannels {
return api.OrganizationContactChannels{
Website: nullableWebsite(contacts.Website()), Email: nullableEmail(contacts.Email()),
Phone: nullablePhone(contacts.Phone()), Telegram: nullableTelegram(contacts.Telegram()),
}
}
func nullableWebsite(value string) api.NilOrganizationWebsite {
if value == "" {
return api.NilOrganizationWebsite{Null: true}
}
return api.NewNilOrganizationWebsite(api.OrganizationWebsite(value))
}
func nullableEmail(value string) api.NilEmailAddress {
if value == "" {
return api.NilEmailAddress{Null: true}
}
return api.NewNilEmailAddress(api.EmailAddress(value))
}
func nullablePhone(value string) api.NilContactPhoneNumber {
if value == "" {
return api.NilContactPhoneNumber{Null: true}
}
return api.NewNilContactPhoneNumber(api.ContactPhoneNumber(value))
}
func nullableTelegram(value string) api.NilContactTelegramUsername {
if value == "" {
return api.NilContactTelegramUsername{Null: true}
}
return api.NewNilContactTelegramUsername(api.ContactTelegramUsername(value))
}
func createOrganizationFailure(ctx context.Context, err error) (api.CreateOrganizationRes, error) {
switch {
case errors.Is(err, organization.ErrForbidden):
return (*api.CreateOrganizationForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, organization.ErrEmailNotVerified):
return (*api.CreateOrganizationForbidden)(&problem.New(ctx, api.ProblemCodeEmailNotVerified).Response), nil
case errors.Is(err, organization.ErrIdempotencyKeyReused):
return (*api.CreateOrganizationUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil
case errors.Is(err, organization.ErrInvalidIdempotencyKey):
return (*api.CreateOrganizationBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationHeader, "/Idempotency-Key").Response), nil
case errors.Is(err, organization.ErrInvalidCreateRequest):
return (*api.CreateOrganizationBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
case errors.Is(err, domain.ErrInvalidOrganization):
return (*api.CreateOrganizationBadRequest)(&organizationFieldProblem(ctx, err).Response), nil
default:
return nil, err
}
}
func getOrganizationFailure(ctx context.Context, err error) (api.GetOrganizationRes, error) {
switch {
case errors.Is(err, organization.ErrForbidden), errors.Is(err, outbound.ErrOrganizationManagerRequired):
return (*api.GetOrganizationForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, organization.ErrEmailNotVerified):
return (*api.GetOrganizationForbidden)(&problem.New(ctx, api.ProblemCodeEmailNotVerified).Response), nil
case errors.Is(err, outbound.ErrOrganizationNotFound):
return (*api.GetOrganizationNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
default:
return nil, err
}
}
func updateOrganizationFailure(ctx context.Context, err error) (api.UpdateOrganizationRes, error) {
switch {
case errors.Is(err, organization.ErrForbidden), errors.Is(err, outbound.ErrOrganizationManagerRequired):
return (*api.UpdateOrganizationForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, organization.ErrEmailNotVerified):
return (*api.UpdateOrganizationForbidden)(&problem.New(ctx, api.ProblemCodeEmailNotVerified).Response), nil
case errors.Is(err, outbound.ErrOrganizationNotFound):
return (*api.UpdateOrganizationNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
case errors.Is(err, outbound.ErrOrganizationVersionConflict):
return (*api.UpdateOrganizationPreconditionFailed)(&problem.New(ctx, api.ProblemCodeVersionConflict).Response), nil
case errors.Is(err, domain.ErrInvalidOrganization):
return (*api.UpdateOrganizationBadRequest)(&organizationFieldProblem(ctx, err).Response), nil
default:
return nil, err
}
}
func organizationFieldProblem(ctx context.Context, err error) *api.ProblemStatusCode {
field, ok := errors.AsType[*domain.OrganizationFieldError](err)
if !ok {
return problem.InvalidField(ctx, api.ProblemFieldLocationBody, "")
}
return problem.InvalidField(ctx, api.ProblemFieldLocationBody, field.Pointer)
}