feat(accounts): add consent settings and organization management

This commit is contained in:
TakuyaYagam1 committed 2026-10-07 13:00:39 +03:00
1 parent 24638d46d2
commit 391af7a1ef
83 files changed
+10198 -613

No files matched your search

@@ -17,9 +17,11 @@ import (
type Handler struct {
api.UnimplementedHandler
health *HealthHandler
identity *IdentityHandler
problems *problem.Responder
health *HealthHandler
identity *IdentityHandler
consent *ConsentHandler
organization *OrganizationHandler
problems *problem.Responder
}
var _ api.Handler = (*Handler)(nil)
@@ -32,6 +34,16 @@ func WithIdentity(identity *IdentityHandler) HandlerOption {
return func(handler *Handler) { handler.identity = identity }
}
// WithConsent serves the published texts and ledger operations.
func WithConsent(consent *ConsentHandler) HandlerOption {
return func(handler *Handler) { handler.consent = consent }
}
// WithOrganization serves company profiles and owner operations.
func WithOrganization(organization *OrganizationHandler) HandlerOption {
return func(handler *Handler) { handler.organization = organization }
}
func NewHandler(health *HealthHandler, problems *problem.Responder, options ...HandlerOption) *Handler {
handler := &Handler{health: health, problems: problems}
for _, option := range options {
@@ -0,0 +1,432 @@
package v1
import (
"context"
"encoding/base64"
"encoding/binary"
"errors"
"fmt"
"time"
"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/consent"
)
const (
defaultConsentPageLimit = 20
consentCursorVersion = 1
consentCursorBytes = 42
maxConsentCursorNanos = int64(1<<63 - 1)
minConsentCursorNanos = -maxConsentCursorNanos - 1
)
// ConsentQueries reads current texts and a subject's own consent history.
type ConsentQueries interface {
CurrentText(ctx context.Context, purpose domain.ConsentPurpose) (domain.ConsentText, error)
List(ctx context.Context, query outbound.ConsentListQuery) (outbound.ConsentPage, error)
}
// ConsentCommands records grants, revocations, and deletion requests.
type ConsentCommands interface {
GrantInSettingsInNewTransaction(ctx context.Context, input consent.SettingsGrantInput) (consent.GrantResult, error)
RevokeInSettingsInNewTransaction(ctx context.Context, input consent.SettingsRevocationInput) (consent.RevocationResult, error)
RequestAccountDeletionInNewTransaction(ctx context.Context, subjectID uuid.UUID) (domain.AccountDeletionRequest, error)
}
// ConsentHandler serves consent text and ledger operations.
type ConsentHandler struct {
queries ConsentQueries
commands ConsentCommands
}
func NewConsentHandler(queries ConsentQueries, commands ConsentCommands) *ConsentHandler {
if queries == nil || commands == nil {
panic("v1.NewConsentHandler - query and command services must not be nil")
}
return &ConsentHandler{queries: queries, commands: commands}
}
func (handler *Handler) GetConsentText(ctx context.Context, params api.GetConsentTextParams) (api.GetConsentTextRes, error) {
if handler.consent == nil {
return handler.UnimplementedHandler.GetConsentText(ctx, params)
}
return handler.consent.GetConsentText(ctx, params)
}
func (handler *Handler) GetMyConsentText(ctx context.Context, params api.GetMyConsentTextParams) (api.GetMyConsentTextRes, error) {
if handler.consent == nil {
return handler.UnimplementedHandler.GetMyConsentText(ctx, params)
}
return handler.consent.GetMyConsentText(ctx, params)
}
func (handler *Handler) ListMyConsents(ctx context.Context, params api.ListMyConsentsParams) (api.ListMyConsentsRes, error) {
if handler.consent == nil {
return handler.UnimplementedHandler.ListMyConsents(ctx, params)
}
return handler.consent.ListMyConsents(ctx, params)
}
func (handler *Handler) GrantMyConsent(ctx context.Context, request *api.ConsentSettingsGrantRequest, params api.GrantMyConsentParams) (api.GrantMyConsentRes, error) {
if handler.consent == nil {
return handler.UnimplementedHandler.GrantMyConsent(ctx, request, params)
}
return handler.consent.GrantMyConsent(ctx, request, params)
}
func (handler *Handler) RevokeMyConsent(ctx context.Context, params api.RevokeMyConsentParams) (api.RevokeMyConsentRes, error) {
if handler.consent == nil {
return handler.UnimplementedHandler.RevokeMyConsent(ctx, params)
}
return handler.consent.RevokeMyConsent(ctx, params)
}
func (handler *Handler) RevokeMyOrganizationContactConsent(ctx context.Context, params api.RevokeMyOrganizationContactConsentParams) (api.RevokeMyOrganizationContactConsentRes, error) {
if handler.consent == nil {
return handler.UnimplementedHandler.RevokeMyOrganizationContactConsent(ctx, params)
}
return handler.consent.RevokeMyOrganizationContactConsent(ctx, params)
}
func (handler *Handler) RequestMyAccountDeletion(ctx context.Context) (api.RequestMyAccountDeletionRes, error) {
if handler.consent == nil {
return handler.UnimplementedHandler.RequestMyAccountDeletion(ctx)
}
return handler.consent.RequestMyAccountDeletion(ctx)
}
func (handler *ConsentHandler) GetConsentText(ctx context.Context, params api.GetConsentTextParams) (api.GetConsentTextRes, error) {
purpose := domain.ConsentPurpose(params.Purpose)
if purpose != domain.ConsentPurposePersonalData {
response := problem.New(ctx, api.ProblemCodeValidationFailed).Response
return &response, nil
}
text, err := handler.queries.CurrentText(ctx, purpose)
if err != nil {
return nil, err
}
response := consentTextResponse(text)
return &response, nil
}
func (handler *ConsentHandler) GetMyConsentText(ctx context.Context, params api.GetMyConsentTextParams) (api.GetMyConsentTextRes, error) {
if _, ok := currentConsentPrincipal(ctx); !ok {
return (*api.GetMyConsentTextUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
text, err := handler.queries.CurrentText(ctx, domain.ConsentPurpose(params.Purpose))
if err != nil {
return nil, err
}
return &api.ConsentTextHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: consentTextResponse(text),
}, nil
}
func (handler *ConsentHandler) ListMyConsents(ctx context.Context, params api.ListMyConsentsParams) (api.ListMyConsentsRes, error) {
principal, ok := currentConsentPrincipal(ctx)
if !ok {
return (*api.ListMyConsentsUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
query, err := consentListQuery(principal.UserID, params)
if err != nil {
return consentListInvalid(ctx, err), nil
}
page, err := handler.queries.List(ctx, query)
if err != nil {
if errors.Is(err, domain.ErrInvalidConsent) {
return consentListInvalid(ctx, err), nil
}
return nil, err
}
items := make([]api.ConsentRecord, 0, len(page.Records))
for _, record := range page.Records {
items = append(items, consentRecordResponse(record))
}
var nextCursor api.NilString
nextCursor.SetToNull()
if page.HasMore && len(page.Records) > 0 {
last := page.Records[len(page.Records)-1]
cursor, err := encodeConsentCursor(principal.UserID, query.State, outbound.ConsentPositionOf(last))
if err != nil {
return nil, fmt.Errorf("ConsentHandler.ListMyConsents - encode cursor: %w", err)
}
nextCursor.SetTo(cursor)
}
return &api.ConsentRecordListHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: api.ConsentRecordList{
Items: items,
Page: api.PageInfo{HasMore: page.HasMore, NextCursor: nextCursor},
},
}, nil
}
func (handler *ConsentHandler) GrantMyConsent(ctx context.Context, request *api.ConsentSettingsGrantRequest, params api.GrantMyConsentParams) (api.GrantMyConsentRes, error) {
principal, session, ok := currentConsentSession(ctx)
if !ok {
return (*api.GrantMyConsentUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
purpose := domain.ConsentPurpose(params.Purpose)
if candidateOnlyConsent(purpose) && session.User.Scenario != domain.ScenarioCandidate {
return (*api.GrantMyConsentForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
}
if request == nil || !bool(request.Accepted) {
return consentGrantInvalid(ctx, "/accepted"), nil
}
result, err := handler.commands.GrantInSettingsInNewTransaction(ctx, consent.SettingsGrantInput{
SubjectID: principal.UserID, Purpose: purpose, TextVersion: domain.ConsentTextVersion(request.TextVersion),
})
if err != nil {
if errors.Is(err, consent.ErrStaleConsentText) {
return consentGrantInvalid(ctx, "/text_version"), nil
}
return nil, err
}
return &api.ConsentRecordHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: consentRecordResponse(result.Record),
}, nil
}
func (handler *ConsentHandler) RevokeMyConsent(ctx context.Context, params api.RevokeMyConsentParams) (api.RevokeMyConsentRes, error) {
principal, session, ok := currentConsentSession(ctx)
if !ok {
return (*api.RevokeMyConsentUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
if session.User.Scenario != domain.ScenarioCandidate {
return (*api.RevokeMyConsentForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
}
_, err := handler.commands.RevokeInSettingsInNewTransaction(ctx, consent.SettingsRevocationInput{
SubjectID: principal.UserID, Purpose: domain.ConsentPurpose(params.Purpose),
})
if err != nil {
return nil, err
}
return &api.RevokeMyConsentNoContent{}, nil
}
func (handler *ConsentHandler) RevokeMyOrganizationContactConsent(ctx context.Context, params api.RevokeMyOrganizationContactConsentParams) (api.RevokeMyOrganizationContactConsentRes, error) {
principal, session, ok := currentConsentSession(ctx)
if !ok {
return (*api.RevokeMyOrganizationContactConsentUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
if session.User.Scenario != domain.ScenarioCandidate {
return (*api.RevokeMyOrganizationContactConsentForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
}
_, err := handler.commands.RevokeInSettingsInNewTransaction(ctx, consent.SettingsRevocationInput{
SubjectID: principal.UserID, Purpose: domain.ConsentPurposeContactDisclosure, OrganizationID: params.OrgID,
})
if err != nil {
return nil, err
}
return &api.RevokeMyOrganizationContactConsentNoContent{}, nil
}
func (handler *ConsentHandler) RequestMyAccountDeletion(ctx context.Context) (api.RequestMyAccountDeletionRes, error) {
principal, ok := currentConsentPrincipal(ctx)
if !ok {
return (*api.RequestMyAccountDeletionUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
request, err := handler.commands.RequestAccountDeletionInNewTransaction(ctx, principal.UserID)
if err != nil {
return nil, err
}
return &api.ConsentDeletionRequestHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: api.ConsentDeletionRequest{
ID: request.ID(), Status: api.ConsentDeletionRequestStatus(request.Status()), RequestedAt: api.Timestamp(request.RequestedAt()),
},
}, nil
}
func currentConsentPrincipal(ctx context.Context) (Principal, bool) {
principal, ok := PrincipalFromContext(ctx)
if !ok || !principal.EmailVerified {
return Principal{}, false
}
session, ok := sessionFromContext(ctx)
if !ok || session.Principal != principal || session.User.ID != principal.UserID || !session.User.EmailVerified() {
return Principal{}, false
}
return principal, true
}
func currentConsentSession(ctx context.Context) (Principal, authenticatedSession, bool) {
principal, ok := currentConsentPrincipal(ctx)
if !ok {
return Principal{}, authenticatedSession{}, false
}
session, ok := sessionFromContext(ctx)
return principal, session, ok
}
func candidateOnlyConsent(purpose domain.ConsentPurpose) bool {
return purpose == domain.ConsentPurposePublication || purpose == domain.ConsentPurposeAutoCategorization ||
purpose == domain.ConsentPurposeFSPImport
}
func consentTextResponse(text domain.ConsentText) api.ConsentText {
return api.ConsentText{
Purpose: api.ConsentPurposeCode(text.Purpose()), TextVersion: api.ConsentTextVersion(text.Version()),
Text: text.Body(), PublishedAt: api.Timestamp(text.PublishedAt()),
}
}
func consentRecordResponse(record domain.ConsentRecord) api.ConsentRecord {
response := api.ConsentRecord{
ID: record.ID(), Purpose: api.ConsentPurposeCode(record.Purpose()), State: api.ConsentState(record.State()),
TextVersion: api.ConsentTextVersion(record.TextVersion()), Source: api.ConsentSource(record.Source()),
GrantedAt: api.Timestamp(record.GrantedAt()), Fields: mapContactFields(record.Fields().Fields()),
}
if revokedAt, ok := record.RevokedAt(); ok {
response.RevokedAt.SetTo(api.Timestamp(revokedAt))
response.RevocationSource.SetTo(api.ConsentRevocationSource(record.RevocationSource()))
} else {
response.RevokedAt.SetToNull()
response.RevocationSource.SetToNull()
}
if record.Purpose().OrganizationScoped() {
response.Organization.SetTo(api.ConsentOrganization{ID: record.OrganizationID(), Name: record.OrganizationName()})
response.InvitationID.SetTo(record.InvitationID())
response.InvitationTermsVersion.SetTo(api.InvitationTermsVersion(record.InvitationTermsVersion()))
} else {
response.Organization.SetToNull()
response.InvitationID.SetToNull()
response.InvitationTermsVersion.SetToNull()
}
return response
}
func mapContactFields(fields []domain.ContactField) []api.ContactFieldKind {
if fields == nil {
return nil
}
mapped := make([]api.ContactFieldKind, 0, len(fields))
for _, field := range fields {
mapped = append(mapped, api.ContactFieldKind(field))
}
return mapped
}
func consentListQuery(subjectID uuid.UUID, params api.ListMyConsentsParams) (outbound.ConsentListQuery, error) {
query := outbound.ConsentListQuery{SubjectID: subjectID, Limit: defaultConsentPageLimit}
if state, ok := params.State.Get(); ok {
query.State = domain.ConsentState(state)
}
if limit, ok := params.Limit.Get(); ok {
query.Limit = limit
}
if cursor, ok := params.Cursor.Get(); ok {
position, state, err := decodeConsentCursor(cursor, subjectID)
if err != nil || state != query.State {
return outbound.ConsentListQuery{}, errors.New("consent cursor is invalid")
}
query.After = &position
}
return query, nil
}
func encodeConsentCursor(subjectID uuid.UUID, state domain.ConsentState, position outbound.ConsentListPosition) (string, error) {
nanos, inRange := consentCursorNanos(position.GrantedAt)
if subjectID == uuid.Nil || position.ID == uuid.Nil || !inRange {
return "", fmt.Errorf("encodeConsentCursor - subject and position are required: %w", domain.ErrInvalidConsent)
}
stateCode, ok := consentCursorStateCode(state)
if !ok {
return "", fmt.Errorf("encodeConsentCursor - state is invalid: %w", domain.ErrInvalidConsent)
}
var value [consentCursorBytes]byte
value[0] = consentCursorVersion
copy(value[1:17], subjectID[:])
value[17] = stateCode
binary.BigEndian.PutUint64(value[18:26], encodeConsentCursorNanos(nanos))
copy(value[26:], position.ID[:])
return base64.RawURLEncoding.EncodeToString(value[:]), nil
}
func decodeConsentCursor(cursor string, subjectID uuid.UUID) (outbound.ConsentListPosition, domain.ConsentState, error) {
value, err := base64.RawURLEncoding.DecodeString(cursor)
if err != nil || len(value) != consentCursorBytes || subjectID == uuid.Nil || value[0] != consentCursorVersion ||
base64.RawURLEncoding.EncodeToString(value) != cursor || uuid.UUID(value[1:17]) != subjectID {
return outbound.ConsentListPosition{}, "", errors.New("consent cursor is invalid")
}
state, ok := consentCursorState(value[17])
if !ok {
return outbound.ConsentListPosition{}, "", errors.New("consent cursor is invalid")
}
grantedAt := time.Unix(0, decodeConsentCursorNanos(binary.BigEndian.Uint64(value[18:26]))).UTC()
positionID := uuid.UUID(value[26:42])
if positionID == uuid.Nil || grantedAt.IsZero() {
return outbound.ConsentListPosition{}, "", errors.New("consent cursor is invalid")
}
return outbound.ConsentListPosition{GrantedAt: grantedAt, ID: positionID}, state, nil
}
func consentCursorNanos(at time.Time) (int64, bool) {
if at.IsZero() || at.Before(time.Unix(0, minConsentCursorNanos)) || at.After(time.Unix(0, maxConsentCursorNanos)) {
return 0, false
}
return at.UnixNano(), true
}
func decodeConsentCursorNanos(encoded uint64) int64 {
if encoded <= uint64(maxConsentCursorNanos) {
return int64(encoded)
}
complement := ^encoded & uint64(maxConsentCursorNanos)
if complement == uint64(maxConsentCursorNanos) {
return minConsentCursorNanos
}
return -int64(complement) - 1
}
func encodeConsentCursorNanos(nanos int64) uint64 {
if nanos >= 0 {
return uint64(nanos)
}
return uint64(nanos&maxConsentCursorNanos) | uint64(1)<<63
}
func consentCursorStateCode(state domain.ConsentState) (byte, bool) {
switch state {
case "":
return 0, true
case domain.ConsentStateActive:
return 1, true
case domain.ConsentStateSuperseded:
return 2, true
case domain.ConsentStateRevoked:
return 3, true
default:
return 0, false
}
}
func consentCursorState(code byte) (domain.ConsentState, bool) {
switch code {
case 0:
return "", true
case 1:
return domain.ConsentStateActive, true
case 2:
return domain.ConsentStateSuperseded, true
case 3:
return domain.ConsentStateRevoked, true
default:
return "", false
}
}
func consentListInvalid(ctx context.Context, _ error) *api.ListMyConsentsBadRequest {
return (*api.ListMyConsentsBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationQuery, "/cursor").Response)
}
func consentGrantInvalid(ctx context.Context, pointer string) *api.GrantMyConsentBadRequest {
return (*api.GrantMyConsentBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, pointer).Response)
}
@@ -0,0 +1,46 @@
package v1
import (
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
func TestConsentCursorTimeBounds(t *testing.T) {
subjectID := uuid.New()
positionID := uuid.New()
for _, grantedAt := range []time.Time{
time.Unix(0, minConsentCursorNanos).UTC(),
time.Unix(0, -1).UTC(),
time.Unix(0, 0).UTC(),
time.Unix(0, maxConsentCursorNanos).UTC(),
} {
t.Run(grantedAt.String(), func(t *testing.T) {
cursor, err := encodeConsentCursor(subjectID, domain.ConsentStateActive, outbound.ConsentListPosition{
GrantedAt: grantedAt, ID: positionID,
})
if err != nil {
t.Fatalf("encode cursor at %s: %v", grantedAt, err)
}
position, state, err := decodeConsentCursor(cursor, subjectID)
if err != nil || !position.GrantedAt.Equal(grantedAt) || position.ID != positionID || state != domain.ConsentStateActive {
t.Fatalf("decode cursor = %#v, %q, %v; want time %s and matching position", position, state, err, grantedAt)
}
})
}
for _, grantedAt := range []time.Time{
time.Unix(0, minConsentCursorNanos).Add(-time.Nanosecond),
time.Unix(0, maxConsentCursorNanos).Add(time.Nanosecond),
} {
if _, err := encodeConsentCursor(subjectID, domain.ConsentStateActive, outbound.ConsentListPosition{
GrantedAt: grantedAt, ID: positionID,
}); err == nil {
t.Fatalf("encode cursor outside Unix-nanosecond range at %s: got nil error", grantedAt)
}
}
}
@@ -0,0 +1,358 @@
package v1
import (
"context"
"encoding/json"
"errors"
"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)
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)
}
// 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}
}
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 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):
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)
}