feat(org): add organization and membership contract and storage

This commit is contained in:
shira committed 2026-10-06 15:55:29 +03:00
1 parent a0551a34b8
commit bdc5855001
90 files changed
+17545 -480

No files matched your search

@@ -17,20 +17,22 @@ import (
)
var regexMap = map[string]ogenregex.Regexp{
"\\S": ogenregex.MustCompile("\\S"),
"^(/([^~/]|~[01])*)*$": ogenregex.MustCompile("^(/([^~/]|~[01])*)*$"),
"^@[A-Za-z0-9_]{5,32}$": ogenregex.MustCompile("^@[A-Za-z0-9_]{5,32}$"),
"^SC-[0-9]{4}-[0-9]{6,10}$": ogenregex.MustCompile("^SC-[0-9]{4}-[0-9]{6,10}$"),
"^[A-Za-z0-9._-]+$": ogenregex.MustCompile("^[A-Za-z0-9._-]+$"),
"^[A-Za-z0-9._:-]+$": ogenregex.MustCompile("^[A-Za-z0-9._:-]+$"),
"^[A-Za-z0-9_-]+$": ogenregex.MustCompile("^[A-Za-z0-9_-]+$"),
"^[a-z0-9][a-z0-9_.+#-]*$": ogenregex.MustCompile("^[a-z0-9][a-z0-9_.+#-]*$"),
"^[a-z0-9_+-]+$": ogenregex.MustCompile("^[a-z0-9_+-]+$"),
"^[a-z0-9_]+$": ogenregex.MustCompile("^[a-z0-9_]+$"),
"^[a-z][a-z0-9_]*$": ogenregex.MustCompile("^[a-z][a-z0-9_]*$"),
"^\\+[1-9][0-9]{6,14}$": ogenregex.MustCompile("^\\+[1-9][0-9]{6,14}$"),
"^\\S(?:.*\\S)?$": ogenregex.MustCompile("^\\S(?:.*\\S)?$"),
"^__Host-lincodex_session=": ogenregex.MustCompile("^__Host-lincodex_session="),
"\\S": ogenregex.MustCompile("\\S"),
"^(/([^~/]|~[01])*)*$": ogenregex.MustCompile("^(/([^~/]|~[01])*)*$"),
"^@[A-Za-z0-9_]{5,32}$": ogenregex.MustCompile("^@[A-Za-z0-9_]{5,32}$"),
"^SC-[0-9]{4}-[0-9]{6,10}$": ogenregex.MustCompile("^SC-[0-9]{4}-[0-9]{6,10}$"),
"^[A-Za-z0-9._-]+$": ogenregex.MustCompile("^[A-Za-z0-9._-]+$"),
"^[A-Za-z0-9._:-]+$": ogenregex.MustCompile("^[A-Za-z0-9._:-]+$"),
"^[A-Za-z0-9_-]+$": ogenregex.MustCompile("^[A-Za-z0-9_-]+$"),
"^[a-z0-9][a-z0-9_.+#-]*$": ogenregex.MustCompile("^[a-z0-9][a-z0-9_.+#-]*$"),
"^[a-z0-9_+-]+$": ogenregex.MustCompile("^[a-z0-9_+-]+$"),
"^[a-z0-9_]+$": ogenregex.MustCompile("^[a-z0-9_]+$"),
"^[a-z][a-z0-9_]*$": ogenregex.MustCompile("^[a-z][a-z0-9_]*$"),
"^\\+[1-9][0-9]{6,14}$": ogenregex.MustCompile("^\\+[1-9][0-9]{6,14}$"),
"^\\S(?:.*\\S)?$": ogenregex.MustCompile("^\\S(?:.*\\S)?$"),
"^\\S(?:[^\\n\\r]*\\S)?$": ogenregex.MustCompile("^\\S(?:[^\\n\\r]*\\S)?$"),
"^__Host-lincodex_session=": ogenregex.MustCompile("^__Host-lincodex_session="),
"^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$": ogenregex.MustCompile("^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$"),
}
var (
// Allocate option closure once.
@@ -1342,6 +1342,263 @@ func (s *Server) handleCreateMySupportCaseRequest(args [0]string, argsEscaped bo
}
}
// handleCreateOrganizationRequest handles CreateOrganization operation.
//
// Requires the session cookie of an employer account with a confirmed email, the CSRF token of that
// session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The owner is the account of the
// session: the body has no owner, membership, role, verification, or version field, and unknown fields
// fail validation.
//
// The server creates the organization and the owner membership of the caller (role `owner`, state
// `active`) in one transaction, so an organization never exists without its owner. The organization
// starts at the verification level `e0` with the basis `confirmed_email`. The level cannot be
// requested: the creator of a company with a corporate domain, a long description, or many
// representatives still gets `e0`, and `e1`, `e2`, and `e3` come only from verification processes of
// the server that do not exist yet. Only `name` is required; the rest of the card can be completed
// with UpdateOrganization.
//
// Idempotency: a retry with the same key and body within 24 hours replays the stored 201 and creates
// nothing, so a lost response never creates a second organization. A different body with the same key
// answers 422 idempotency_key_reused. 400 is never stored, so a corrected retry is evaluated again.
// Two requests with different keys are two organizations; the product may limit the number of
// organizations per account (open question), which would answer 409 `state_conflict` without a change
// of the schema.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden for a candidate account), the Idempotency-Key (422, 409
// idempotency_in_progress, replay), domain rules (400 with a pointer such as `/contacts/website` for a
// website that is not an https URL of a host name, `/name` for a name with surrounding whitespace).
// The general rate limit can answer 429 with Retry-After before any check; 429 is never stored.
//
// POST /api/v1/organizations
func (s *Server) handleCreateOrganizationRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("CreateOrganization"),
semconv.HTTPRequestMethodKey.String("POST"),
semconv.HTTPRouteKey.String("/api/v1/organizations"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), CreateOrganizationOperation,
trace.WithAttributes(otelAttrs...),
serverSpanKind,
)
defer span.End()
// Add Labeler to context.
labeler := &Labeler{attrs: otelAttrs}
ctx = contextWithLabeler(ctx, labeler)
// Run stopwatch.
startTime := time.Now()
defer func() {
elapsedDuration := time.Since(startTime)
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
code := statusWriter.status
if code != 0 {
codeAttr := semconv.HTTPResponseStatusCode(code)
attrs = append(attrs, codeAttr)
span.SetAttributes(attrs...)
}
attrOpt := metric.WithAttributes(attrs...)
// Increment request counter.
s.requests.Add(ctx, 1, attrOpt)
// Use floating point division here for higher precision (instead of Millisecond method).
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
}()
var (
recordError = func(stage string, err error) {
span.RecordError(err)
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
// max redirects exceeded), in which case status MUST be set to Error.
code := statusWriter.status
if code < 100 || code >= 500 {
span.SetStatus(codes.Error, stage)
}
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
if code != 0 {
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
}
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
}
err error
opErrContext = ogenerrors.OperationContext{
Name: CreateOrganizationOperation,
ID: "CreateOrganization",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, CreateOrganizationOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCookie",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCookie", err)
}
return
}
if ok {
satisfied[0] |= 1 << 0
ctx = sctx
}
}
{
sctx, ok, err := s.securitySessionCsrf(ctx, CreateOrganizationOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCsrf",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCsrf", err)
}
return
}
if ok {
satisfied[0] |= 1 << 1
ctx = sctx
}
}
if ok := func() bool {
nextRequirement:
for _, requirement := range []bitset{
{0b00000011},
} {
for i, mask := range requirement {
if satisfied[i]&mask != mask {
continue nextRequirement
}
}
return true
}
return false
}(); !ok {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security", err)
}
return
}
}
params, err := decodeCreateOrganizationParams(args, argsEscaped, r)
if err != nil {
err = &ogenerrors.DecodeParamsError{
OperationContext: opErrContext,
Err: err,
}
defer recordError("DecodeParams", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
var rawBody []byte
request, rawBody, close, err := s.decodeCreateOrganizationRequest(r)
if err != nil {
err = &ogenerrors.DecodeRequestError{
OperationContext: opErrContext,
Err: err,
}
defer recordError("DecodeRequest", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
defer func() {
if err := close(); err != nil {
recordError("CloseRequest", err)
}
}()
var response CreateOrganizationRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: CreateOrganizationOperation,
OperationSummary: "Create an organization; the caller becomes its owner.",
OperationID: "CreateOrganization",
Body: request,
RawBody: rawBody,
Params: middleware.Parameters{
{
Name: "Idempotency-Key",
In: "header",
}: params.IdempotencyKey,
},
Raw: r,
}
type (
Request = *OrganizationCreate
Params = CreateOrganizationParams
Response = CreateOrganizationRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
unpackCreateOrganizationParams,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.CreateOrganization(ctx, request, params)
return response, err
},
)
} else {
response, err = s.h.CreateOrganization(ctx, request, params)
}
if err != nil {
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
if err := encodeErrorResponse(errRes, w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if errors.Is(err, ht.ErrNotImplemented) {
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if err := encodeCreateOrganizationResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleCreateOrganizationInvitationRequest handles CreateOrganizationInvitation operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
@@ -4390,6 +4647,224 @@ func (s *Server) handleGetMySupportCaseRequest(args [1]string, argsEscaped bool,
}
}
// handleGetOrganizationRequest handles GetOrganization operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
// organization comes from the path and is checked against the membership that the server holds for the
// session account on every request; the identifier itself grants nothing.
//
// Returns the profile with its current `version`, the verification level (`verification`), and the
// card as a candidate sees it (`candidate_card`). The verification level is always the one the server
// holds: it never rises because the profile is complete, because the organization has members, or
// because of an email domain. The role of the caller is not part of this resource; ListMyOrganizations
// returns it with the membership.
//
// In the MVP the profile is readable by any active member; every member is an owner, because the
// operations that add members are planned. The roles of PRD FR07 that read a company card without
// managing it change no field of this contract.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate
// account answers 403 forbidden; an account without an active membership in the organization,
// including a `suspended`, `removed`, or `left` one, and an unknown organization all answer 404
// not_found, so organizations cannot be enumerated. A malformed `org_id` answers 400 validation_failed
// with the path pointer.
//
// GET /api/v1/organizations/{org_id}
func (s *Server) handleGetOrganizationRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("GetOrganization"),
semconv.HTTPRequestMethodKey.String("GET"),
semconv.HTTPRouteKey.String("/api/v1/organizations/{org_id}"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), GetOrganizationOperation,
trace.WithAttributes(otelAttrs...),
serverSpanKind,
)
defer span.End()
// Add Labeler to context.
labeler := &Labeler{attrs: otelAttrs}
ctx = contextWithLabeler(ctx, labeler)
// Run stopwatch.
startTime := time.Now()
defer func() {
elapsedDuration := time.Since(startTime)
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
code := statusWriter.status
if code != 0 {
codeAttr := semconv.HTTPResponseStatusCode(code)
attrs = append(attrs, codeAttr)
span.SetAttributes(attrs...)
}
attrOpt := metric.WithAttributes(attrs...)
// Increment request counter.
s.requests.Add(ctx, 1, attrOpt)
// Use floating point division here for higher precision (instead of Millisecond method).
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
}()
var (
recordError = func(stage string, err error) {
span.RecordError(err)
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
// max redirects exceeded), in which case status MUST be set to Error.
code := statusWriter.status
if code < 100 || code >= 500 {
span.SetStatus(codes.Error, stage)
}
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
if code != 0 {
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
}
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
}
err error
opErrContext = ogenerrors.OperationContext{
Name: GetOrganizationOperation,
ID: "GetOrganization",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, GetOrganizationOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCookie",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCookie", err)
}
return
}
if ok {
satisfied[0] |= 1 << 0
ctx = sctx
}
}
if ok := func() bool {
nextRequirement:
for _, requirement := range []bitset{
{0b00000001},
} {
for i, mask := range requirement {
if satisfied[i]&mask != mask {
continue nextRequirement
}
}
return true
}
return false
}(); !ok {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security", err)
}
return
}
}
params, err := decodeGetOrganizationParams(args, argsEscaped, r)
if err != nil {
err = &ogenerrors.DecodeParamsError{
OperationContext: opErrContext,
Err: err,
}
defer recordError("DecodeParams", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
var rawBody []byte
var response GetOrganizationRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: GetOrganizationOperation,
OperationSummary: "Read an organization of which the caller is a member.",
OperationID: "GetOrganization",
Body: nil,
RawBody: rawBody,
Params: middleware.Parameters{
{
Name: "org_id",
In: "path",
}: params.OrgID,
},
Raw: r,
}
type (
Request = struct{}
Params = GetOrganizationParams
Response = GetOrganizationRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
unpackGetOrganizationParams,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.GetOrganization(ctx, params)
return response, err
},
)
} else {
response, err = s.h.GetOrganization(ctx, params)
}
if err != nil {
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
if err := encodeErrorResponse(errRes, w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if errors.Is(err, ht.ErrNotImplemented) {
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if err := encodeGetOrganizationResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleGetOrganizationInvitationRequest handles GetOrganizationInvitation operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
@@ -5670,6 +6145,233 @@ func (s *Server) handleListMyInvitationsRequest(args [0]string, argsEscaped bool
}
}
// handleListMyOrganizationsRequest handles ListMyOrganizations operation.
//
// Requires the session cookie of an employer account. The account comes from the session, never from a
// request parameter, so the response holds only the caller's own memberships and no request can name
// another account.
//
// Returns a page of the organizations in which the caller has an `active` membership, newest
// membership first with the organization identifier as the tie-breaker, with cursor pagination. Each
// item names the organization (`OrganizationSummary`) and holds the caller's role and state in it
// (`OrganizationMembership`). A membership in another state (`suspended`, `removed`, `left`) does not
// list its organization, so an organization the caller cannot enter is never named, and one that the
// caller was removed from disappears from the list at once.
//
// The list is the directory of the active organization context. The context is not stored on the
// server: every organization-scoped operation names its organization in the path `org_id`, and the
// server checks that identifier against the caller's active membership on every request, so a switch
// between organizations is a different `org_id` in the client's routes and cannot outlive a revoked
// membership. A client picks the context from this list, may remember the last choice in the browser
// as a convenience, and must read the list again after any answer 404 `not_found` from an organization
// path. An account with several memberships sees all of them here and works in one at a time; the
// rights and the data of the organizations stay separate.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate
// account answers 403 forbidden. An employer account without an organization gets an empty page, which
// tells the client to offer CreateOrganization. A malformed `limit` or `cursor` answers 400
// validation_failed.
//
// GET /api/v1/me/organizations
func (s *Server) handleListMyOrganizationsRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("ListMyOrganizations"),
semconv.HTTPRequestMethodKey.String("GET"),
semconv.HTTPRouteKey.String("/api/v1/me/organizations"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), ListMyOrganizationsOperation,
trace.WithAttributes(otelAttrs...),
serverSpanKind,
)
defer span.End()
// Add Labeler to context.
labeler := &Labeler{attrs: otelAttrs}
ctx = contextWithLabeler(ctx, labeler)
// Run stopwatch.
startTime := time.Now()
defer func() {
elapsedDuration := time.Since(startTime)
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
code := statusWriter.status
if code != 0 {
codeAttr := semconv.HTTPResponseStatusCode(code)
attrs = append(attrs, codeAttr)
span.SetAttributes(attrs...)
}
attrOpt := metric.WithAttributes(attrs...)
// Increment request counter.
s.requests.Add(ctx, 1, attrOpt)
// Use floating point division here for higher precision (instead of Millisecond method).
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
}()
var (
recordError = func(stage string, err error) {
span.RecordError(err)
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
// max redirects exceeded), in which case status MUST be set to Error.
code := statusWriter.status
if code < 100 || code >= 500 {
span.SetStatus(codes.Error, stage)
}
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
if code != 0 {
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
}
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
}
err error
opErrContext = ogenerrors.OperationContext{
Name: ListMyOrganizationsOperation,
ID: "ListMyOrganizations",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, ListMyOrganizationsOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCookie",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCookie", err)
}
return
}
if ok {
satisfied[0] |= 1 << 0
ctx = sctx
}
}
if ok := func() bool {
nextRequirement:
for _, requirement := range []bitset{
{0b00000001},
} {
for i, mask := range requirement {
if satisfied[i]&mask != mask {
continue nextRequirement
}
}
return true
}
return false
}(); !ok {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security", err)
}
return
}
}
params, err := decodeListMyOrganizationsParams(args, argsEscaped, r)
if err != nil {
err = &ogenerrors.DecodeParamsError{
OperationContext: opErrContext,
Err: err,
}
defer recordError("DecodeParams", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
var rawBody []byte
var response ListMyOrganizationsRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: ListMyOrganizationsOperation,
OperationSummary: "List the organizations available to the current account.",
OperationID: "ListMyOrganizations",
Body: nil,
RawBody: rawBody,
Params: middleware.Parameters{
{
Name: "limit",
In: "query",
}: params.Limit,
{
Name: "cursor",
In: "query",
}: params.Cursor,
},
Raw: r,
}
type (
Request = struct{}
Params = ListMyOrganizationsParams
Response = ListMyOrganizationsRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
unpackListMyOrganizationsParams,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.ListMyOrganizations(ctx, params)
return response, err
},
)
} else {
response, err = s.h.ListMyOrganizations(ctx, params)
}
if err != nil {
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
if err := encodeErrorResponse(errRes, w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if errors.Is(err, ht.ErrNotImplemented) {
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if err := encodeListMyOrganizationsResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleListMySupportCasesRequest handles ListMySupportCases operation.
//
// Requires the session cookie of a candidate or an employer account. Returns a page of the cases that
@@ -8162,6 +8864,269 @@ func (s *Server) handleSubmitMyAssessmentAnswerRequest(args [1]string, argsEscap
}
}
// handleUpdateOrganizationRequest handles UpdateOrganization operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
// token of that session in X-CSRF-Token, and an allowed Origin. Only the owner manages the
// organization (the FR07 matrix gives this to no other role), so a member with another role answers
// 403 forbidden. The role comes from the server-side membership; the body has no organization,
// membership, role, owner, or verification field.
//
// Merge rules: the body is `application/json` with explicit field replacement, not JSON Merge Patch.
// Each field present replaces that field as a whole and an absent field stays unchanged; `contacts`
// and `representatives` are replaced entirely and never merged. `description` and `sphere` sent as
// null become unset; `name`, `contacts`, and `representatives` cannot be null.
//
// The body can change the profile only. The verification level, its basis, the card, the members, and
// every role are not fields of it, and unknown fields fail validation, so the owner can neither raise
// the trust level of the organization nor the rights of anyone by editing the profile; a longer
// description, a verified-looking website, or a new representative leaves the level unchanged. The
// level and the roles change only through processes of the server.
//
// Versions: every committed change creates version `expected_version + 1` and answers 200 with the
// organization. `expected_version` is the `version` the client read; when it is not current, the
// server answers 412 version_conflict and changes nothing, and the client reads the organization again
// and reapplies its edits. The version travels in the body rather than in If-Match because the
// generated client cannot read the ETag response header yet, as for needs. A body that changes nothing
// when applied to the current profile keeps the version and answers 200 with the current organization
// even when `expected_version` is older, so the operation needs no Idempotency-Key and a retry of a
// change that already succeeded is harmless.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden for a candidate account), membership (404 not_found) and role (403
// forbidden), a body that changes nothing (200), the version (412), domain rules (400 with a pointer
// such as `/contacts/website`, `/name`, or `/representatives/0/job_title`). The general rate limit can
// answer 429 with Retry-After before any check.
//
// PATCH /api/v1/organizations/{org_id}
func (s *Server) handleUpdateOrganizationRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("UpdateOrganization"),
semconv.HTTPRequestMethodKey.String("PATCH"),
semconv.HTTPRouteKey.String("/api/v1/organizations/{org_id}"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), UpdateOrganizationOperation,
trace.WithAttributes(otelAttrs...),
serverSpanKind,
)
defer span.End()
// Add Labeler to context.
labeler := &Labeler{attrs: otelAttrs}
ctx = contextWithLabeler(ctx, labeler)
// Run stopwatch.
startTime := time.Now()
defer func() {
elapsedDuration := time.Since(startTime)
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
code := statusWriter.status
if code != 0 {
codeAttr := semconv.HTTPResponseStatusCode(code)
attrs = append(attrs, codeAttr)
span.SetAttributes(attrs...)
}
attrOpt := metric.WithAttributes(attrs...)
// Increment request counter.
s.requests.Add(ctx, 1, attrOpt)
// Use floating point division here for higher precision (instead of Millisecond method).
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
}()
var (
recordError = func(stage string, err error) {
span.RecordError(err)
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
// max redirects exceeded), in which case status MUST be set to Error.
code := statusWriter.status
if code < 100 || code >= 500 {
span.SetStatus(codes.Error, stage)
}
attrSet := labeler.AttributeSet()
attrs := attrSet.ToSlice()
if code != 0 {
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
}
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
}
err error
opErrContext = ogenerrors.OperationContext{
Name: UpdateOrganizationOperation,
ID: "UpdateOrganization",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, UpdateOrganizationOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCookie",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCookie", err)
}
return
}
if ok {
satisfied[0] |= 1 << 0
ctx = sctx
}
}
{
sctx, ok, err := s.securitySessionCsrf(ctx, UpdateOrganizationOperation, r)
if err != nil {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Security: "SessionCsrf",
Err: err,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security:SessionCsrf", err)
}
return
}
if ok {
satisfied[0] |= 1 << 1
ctx = sctx
}
}
if ok := func() bool {
nextRequirement:
for _, requirement := range []bitset{
{0b00000011},
} {
for i, mask := range requirement {
if satisfied[i]&mask != mask {
continue nextRequirement
}
}
return true
}
return false
}(); !ok {
err = &ogenerrors.SecurityError{
OperationContext: opErrContext,
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
}
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
defer recordError("Security", err)
}
return
}
}
params, err := decodeUpdateOrganizationParams(args, argsEscaped, r)
if err != nil {
err = &ogenerrors.DecodeParamsError{
OperationContext: opErrContext,
Err: err,
}
defer recordError("DecodeParams", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
var rawBody []byte
request, rawBody, close, err := s.decodeUpdateOrganizationRequest(r)
if err != nil {
err = &ogenerrors.DecodeRequestError{
OperationContext: opErrContext,
Err: err,
}
defer recordError("DecodeRequest", err)
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
defer func() {
if err := close(); err != nil {
recordError("CloseRequest", err)
}
}()
var response UpdateOrganizationRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: UpdateOrganizationOperation,
OperationSummary: "Change the profile of an organization.",
OperationID: "UpdateOrganization",
Body: request,
RawBody: rawBody,
Params: middleware.Parameters{
{
Name: "org_id",
In: "path",
}: params.OrgID,
},
Raw: r,
}
type (
Request = *OrganizationUpdate
Params = UpdateOrganizationParams
Response = UpdateOrganizationRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
unpackUpdateOrganizationParams,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.UpdateOrganization(ctx, request, params)
return response, err
},
)
} else {
response, err = s.h.UpdateOrganization(ctx, request, params)
}
if err != nil {
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
if err := encodeErrorResponse(errRes, w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if errors.Is(err, ht.ErrNotImplemented) {
s.cfg.ErrorHandler(ctx, w, r, err)
return
}
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
defer recordError("Internal", err)
}
return
}
if err := encodeUpdateOrganizationResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleUpdateOrganizationInvitationRequest handles UpdateOrganizationInvitation operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
@@ -29,6 +29,10 @@ type CreateOrganizationNeedRes interface {
createOrganizationNeedRes()
}
type CreateOrganizationRes interface {
createOrganizationRes()
}
type DeclineMyInvitationRes interface {
declineMyInvitationRes()
}
@@ -85,6 +89,10 @@ type GetOrganizationNeedRes interface {
getOrganizationNeedRes()
}
type GetOrganizationRes interface {
getOrganizationRes()
}
type ListMyConsentsRes interface {
listMyConsentsRes()
}
@@ -93,6 +101,10 @@ type ListMyInvitationsRes interface {
listMyInvitationsRes()
}
type ListMyOrganizationsRes interface {
listMyOrganizationsRes()
}
type ListMySupportCasesRes interface {
listMySupportCasesRes()
}
@@ -145,6 +157,10 @@ type UpdateOrganizationNeedRes interface {
updateOrganizationNeedRes()
}
type UpdateOrganizationRes interface {
updateOrganizationRes()
}
type ViewMyInvitationRes interface {
viewMyInvitationRes()
}
File diff suppressed because it is too large. Load diff
@@ -11,6 +11,7 @@ const (
ConfirmEmailOperation OperationName = "ConfirmEmail"
CreateMyAssessmentAttemptOperation OperationName = "CreateMyAssessmentAttempt"
CreateMySupportCaseOperation OperationName = "CreateMySupportCase"
CreateOrganizationOperation OperationName = "CreateOrganization"
CreateOrganizationInvitationOperation OperationName = "CreateOrganizationInvitation"
CreateOrganizationNeedOperation OperationName = "CreateOrganizationNeed"
DeclineMyInvitationOperation OperationName = "DeclineMyInvitation"
@@ -25,12 +26,14 @@ const (
GetMyInvitationOperation OperationName = "GetMyInvitation"
GetMyQuestionnaireOperation OperationName = "GetMyQuestionnaire"
GetMySupportCaseOperation OperationName = "GetMySupportCase"
GetOrganizationOperation OperationName = "GetOrganization"
GetOrganizationInvitationOperation OperationName = "GetOrganizationInvitation"
GetOrganizationInvitationContactsOperation OperationName = "GetOrganizationInvitationContacts"
GetOrganizationNeedOperation OperationName = "GetOrganizationNeed"
GetSpecializationCatalogOperation OperationName = "GetSpecializationCatalog"
ListMyConsentsOperation OperationName = "ListMyConsents"
ListMyInvitationsOperation OperationName = "ListMyInvitations"
ListMyOrganizationsOperation OperationName = "ListMyOrganizations"
ListMySupportCasesOperation OperationName = "ListMySupportCases"
ListOrganizationInvitationsOperation OperationName = "ListOrganizationInvitations"
ListOrganizationNeedsOperation OperationName = "ListOrganizationNeeds"
@@ -42,6 +45,7 @@ const (
SaveMyQuestionnaireOperation OperationName = "SaveMyQuestionnaire"
SendOrganizationInvitationOperation OperationName = "SendOrganizationInvitation"
SubmitMyAssessmentAnswerOperation OperationName = "SubmitMyAssessmentAnswer"
UpdateOrganizationOperation OperationName = "UpdateOrganization"
UpdateOrganizationInvitationOperation OperationName = "UpdateOrganizationInvitation"
UpdateOrganizationNeedOperation OperationName = "UpdateOrganizationNeed"
ViewMyInvitationOperation OperationName = "ViewMyInvitation"
@@ -503,6 +503,100 @@ func decodeCreateMySupportCaseParams(args [0]string, argsEscaped bool, r *http.R
return params, nil
}
// CreateOrganizationParams is parameters of CreateOrganization operation.
type CreateOrganizationParams struct {
// Client-generated key that makes a retried mutating command safe; a UUID v4 is recommended. The value
// is sent without quotes. The server scopes the key by caller and operation and fingerprints the
// request by method, path, and body.
//
// Stored for 24 hours after the first request and replayed with the same status, headers, and body:
// the final 2xx outcome and final deterministic 4xx business outcomes of the command, such as 404
// not_found or 409 state_conflict. A replay does not repeat the side effect.
//
// Not stored, so a retry with the same key is evaluated again: 400 validation_failed, 413, and 415 for
// the request itself, 401 and 403, 409 idempotency_in_progress, 412 version_conflict and 428
// precondition_required (nothing changed; read the resource again and retry), 422
// idempotency_key_reused, 429, and every 5xx.
//
// Order of checks: authentication (401), request validation (400, 413, 415), authorization (403), then
// the key. A stored or running request with a different fingerprint returns 422 idempotency_key_reused
// before any other key check; a running request with the same fingerprint returns 409
// idempotency_in_progress; a stored outcome with the same fingerprint is replayed. Only after that
// does the server check If-Match, so a retry of a completed change replays its outcome instead of
// failing on the version it has just changed. After 24 hours the key may be accepted as new.
IdempotencyKey string
}
func unpackCreateOrganizationParams(packed middleware.Parameters) (params CreateOrganizationParams) {
{
key := middleware.ParameterKey{
Name: "Idempotency-Key",
In: "header",
}
params.IdempotencyKey = packed[key].(string)
}
return params
}
func decodeCreateOrganizationParams(args [0]string, argsEscaped bool, r *http.Request) (params CreateOrganizationParams, _ error) {
h := uri.NewHeaderDecoder(r.Header)
// Decode header: Idempotency-Key.
if err := func() error {
cfg := uri.HeaderParameterDecodingConfig{
Name: "Idempotency-Key",
Explode: false,
}
if err := h.HasParam(cfg); err == nil {
if err := h.DecodeParam(cfg, func(d uri.Decoder) error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToString(val)
if err != nil {
return err
}
params.IdempotencyKey = c
return nil
}); err != nil {
return err
}
if err := func() error {
if err := (validate.String{
MinLength: 1,
MinLengthSet: true,
MaxLength: 255,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: regexMap["^[A-Za-z0-9._:-]+$"],
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(params.IdempotencyKey)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
return err
}
} else {
return err
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "Idempotency-Key",
In: "header",
Err: err,
}
}
return params, nil
}
// CreateOrganizationInvitationParams is parameters of CreateOrganizationInvitation operation.
type CreateOrganizationInvitationParams struct {
// Identifier of an organization. Access comes only from an active membership of the session account in
@@ -1447,6 +1541,75 @@ func decodeGetMySupportCaseParams(args [1]string, argsEscaped bool, r *http.Requ
return params, nil
}
// GetOrganizationParams is parameters of GetOrganization operation.
type GetOrganizationParams struct {
// Identifier of an organization. Access comes only from an active membership of the session account in
// this organization, checked by the server on every request; the identifier itself grants nothing. An
// organization without such a membership and an unknown identifier both answer 404 not_found, so
// organizations cannot be enumerated.
OrgID uuid.UUID
}
func unpackGetOrganizationParams(packed middleware.Parameters) (params GetOrganizationParams) {
{
key := middleware.ParameterKey{
Name: "org_id",
In: "path",
}
params.OrgID = packed[key].(uuid.UUID)
}
return params
}
func decodeGetOrganizationParams(args [1]string, argsEscaped bool, r *http.Request) (params GetOrganizationParams, _ error) {
// Decode path: org_id.
if err := func() error {
param := args[0]
if argsEscaped {
unescaped, err := url.PathUnescape(args[0])
if err != nil {
return errors.Wrap(err, "unescape path")
}
param = unescaped
}
if len(param) > 0 {
d := uri.NewPathDecoder(uri.PathDecoderConfig{
Param: "org_id",
Value: param,
Style: uri.PathStyleSimple,
Explode: false,
})
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToUUID(val)
if err != nil {
return err
}
params.OrgID = c
return nil
}(); err != nil {
return err
}
} else {
return validate.ErrFieldRequired
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "org_id",
In: "path",
Err: err,
}
}
return params, nil
}
// GetOrganizationInvitationParams is parameters of GetOrganizationInvitation operation.
type GetOrganizationInvitationParams struct {
// Identifier of an organization. Access comes only from an active membership of the session account in
@@ -2238,6 +2401,182 @@ func decodeListMyInvitationsParams(args [0]string, argsEscaped bool, r *http.Req
return params, nil
}
// ListMyOrganizationsParams is parameters of ListMyOrganizations operation.
type ListMyOrganizationsParams struct {
// Maximum number of items in the page. The server may return fewer items even when more remain; use
// `page.has_more` to detect the end.
Limit OptInt32 `json:",omitempty,omitzero"`
// Opaque `page.next_cursor` value from the previous page of the same listing. Omit it to read the
// first page. A malformed or foreign cursor returns 400 with code validation_failed.
Cursor OptString `json:",omitempty,omitzero"`
}
func unpackListMyOrganizationsParams(packed middleware.Parameters) (params ListMyOrganizationsParams) {
{
key := middleware.ParameterKey{
Name: "limit",
In: "query",
}
if v, ok := packed[key]; ok {
params.Limit = v.(OptInt32)
}
}
{
key := middleware.ParameterKey{
Name: "cursor",
In: "query",
}
if v, ok := packed[key]; ok {
params.Cursor = v.(OptString)
}
}
return params
}
func decodeListMyOrganizationsParams(args [0]string, argsEscaped bool, r *http.Request) (params ListMyOrganizationsParams, _ error) {
q := uri.NewQueryDecoder(r.URL.Query())
// Set default value for query: limit.
{
val := int32(20)
params.Limit.SetTo(val)
}
// Decode query: limit.
if err := func() error {
cfg := uri.QueryParameterDecodingConfig{
Name: "limit",
Style: uri.QueryStyleForm,
Explode: true,
}
if err := q.HasParam(cfg); err == nil {
if err := q.DecodeParam(cfg, func(d uri.Decoder) error {
var paramsDotLimitVal int32
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToInt32(val)
if err != nil {
return err
}
paramsDotLimitVal = c
return nil
}(); err != nil {
return err
}
params.Limit.SetTo(paramsDotLimitVal)
return nil
}); err != nil {
return err
}
if err := func() error {
if value, ok := params.Limit.Get(); ok {
if err := func() error {
if err := (validate.Int{
MinSet: true,
Min: 1,
MaxSet: true,
Max: 100,
MinExclusive: false,
MaxExclusive: false,
MultipleOfSet: false,
MultipleOf: 0,
Pattern: nil,
}).Validate(int64(value)); err != nil {
return errors.Wrap(err, "int")
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "limit",
In: "query",
Err: err,
}
}
// Decode query: cursor.
if err := func() error {
cfg := uri.QueryParameterDecodingConfig{
Name: "cursor",
Style: uri.QueryStyleForm,
Explode: true,
}
if err := q.HasParam(cfg); err == nil {
if err := q.DecodeParam(cfg, func(d uri.Decoder) error {
var paramsDotCursorVal string
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToString(val)
if err != nil {
return err
}
paramsDotCursorVal = c
return nil
}(); err != nil {
return err
}
params.Cursor.SetTo(paramsDotCursorVal)
return nil
}); err != nil {
return err
}
if err := func() error {
if value, ok := params.Cursor.Get(); ok {
if err := func() error {
if err := (validate.String{
MinLength: 1,
MinLengthSet: true,
MaxLength: 512,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: regexMap["^[A-Za-z0-9_-]+$"],
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(value)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "cursor",
In: "query",
Err: err,
}
}
return params, nil
}
// ListMySupportCasesParams is parameters of ListMySupportCases operation.
type ListMySupportCasesParams struct {
// Maximum number of items in the page. The server may return fewer items even when more remain; use
@@ -3535,6 +3874,75 @@ func decodeSubmitMyAssessmentAnswerParams(args [1]string, argsEscaped bool, r *h
return params, nil
}
// UpdateOrganizationParams is parameters of UpdateOrganization operation.
type UpdateOrganizationParams struct {
// Identifier of an organization. Access comes only from an active membership of the session account in
// this organization, checked by the server on every request; the identifier itself grants nothing. An
// organization without such a membership and an unknown identifier both answer 404 not_found, so
// organizations cannot be enumerated.
OrgID uuid.UUID
}
func unpackUpdateOrganizationParams(packed middleware.Parameters) (params UpdateOrganizationParams) {
{
key := middleware.ParameterKey{
Name: "org_id",
In: "path",
}
params.OrgID = packed[key].(uuid.UUID)
}
return params
}
func decodeUpdateOrganizationParams(args [1]string, argsEscaped bool, r *http.Request) (params UpdateOrganizationParams, _ error) {
// Decode path: org_id.
if err := func() error {
param := args[0]
if argsEscaped {
unescaped, err := url.PathUnescape(args[0])
if err != nil {
return errors.Wrap(err, "unescape path")
}
param = unescaped
}
if len(param) > 0 {
d := uri.NewPathDecoder(uri.PathDecoderConfig{
Param: "org_id",
Value: param,
Style: uri.PathStyleSimple,
Explode: false,
})
if err := func() error {
val, err := d.DecodeValue()
if err != nil {
return err
}
c, err := conv.ToUUID(val)
if err != nil {
return err
}
params.OrgID = c
return nil
}(); err != nil {
return err
}
} else {
return validate.ErrFieldRequired
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "org_id",
In: "path",
Err: err,
}
}
return params, nil
}
// UpdateOrganizationInvitationParams is parameters of UpdateOrganizationInvitation operation.
type UpdateOrganizationInvitationParams struct {
// Identifier of an organization. Access comes only from an active membership of the session account in
@@ -409,6 +409,85 @@ func (s *Server) decodeCreateMySupportCaseRequest(r *http.Request) (
}
}
func (s *Server) decodeCreateOrganizationRequest(r *http.Request) (
req *OrganizationCreate,
rawBody []byte,
close func() error,
rerr error,
) {
var closers []func() error
close = func() error {
var merr error
// Close in reverse order, to match defer behavior.
for i := len(closers) - 1; i >= 0; i-- {
c := closers[i]
merr = errors.Join(merr, c())
}
return merr
}
defer func() {
if rerr != nil {
rerr = errors.Join(rerr, close())
}
}()
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil {
return req, rawBody, close, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/json":
if r.ContentLength == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
buf, err := io.ReadAll(r.Body)
defer func() {
_ = r.Body.Close()
}()
if err != nil {
return req, rawBody, close, err
}
// Reset the body to allow for downstream reading.
r.Body = io.NopCloser(bytes.NewBuffer(buf))
if len(buf) == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
rawBody = append(rawBody, buf...)
d := jx.DecodeBytes(buf)
var request OrganizationCreate
if err := func() error {
if err := request.Decode(d); err != nil {
return err
}
if err := d.Skip(); err != io.EOF {
return errors.New("unexpected trailing data")
}
return nil
}(); err != nil {
err = &ogenerrors.DecodeBodyError{
ContentType: ct,
Body: buf,
Err: err,
}
return req, rawBody, close, err
}
if err := func() error {
if err := request.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return req, rawBody, close, errors.Wrap(err, "validate")
}
return &request, rawBody, close, nil
default:
return req, rawBody, close, validate.InvalidContentType(ct)
}
}
func (s *Server) decodeCreateOrganizationInvitationRequest(r *http.Request) (
req *OrganizationInvitationCreate,
rawBody []byte,
@@ -1278,6 +1357,85 @@ func (s *Server) decodeSubmitMyAssessmentAnswerRequest(r *http.Request) (
}
}
func (s *Server) decodeUpdateOrganizationRequest(r *http.Request) (
req *OrganizationUpdate,
rawBody []byte,
close func() error,
rerr error,
) {
var closers []func() error
close = func() error {
var merr error
// Close in reverse order, to match defer behavior.
for i := len(closers) - 1; i >= 0; i-- {
c := closers[i]
merr = errors.Join(merr, c())
}
return merr
}
defer func() {
if rerr != nil {
rerr = errors.Join(rerr, close())
}
}()
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil {
return req, rawBody, close, errors.Wrap(err, "parse media type")
}
switch {
case ct == "application/json":
if r.ContentLength == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
buf, err := io.ReadAll(r.Body)
defer func() {
_ = r.Body.Close()
}()
if err != nil {
return req, rawBody, close, err
}
// Reset the body to allow for downstream reading.
r.Body = io.NopCloser(bytes.NewBuffer(buf))
if len(buf) == 0 {
return req, rawBody, close, validate.ErrBodyRequired
}
rawBody = append(rawBody, buf...)
d := jx.DecodeBytes(buf)
var request OrganizationUpdate
if err := func() error {
if err := request.Decode(d); err != nil {
return err
}
if err := d.Skip(); err != io.EOF {
return errors.New("unexpected trailing data")
}
return nil
}(); err != nil {
err = &ogenerrors.DecodeBodyError{
ContentType: ct,
Body: buf,
Err: err,
}
return req, rawBody, close, err
}
if err := func() error {
if err := request.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return req, rawBody, close, errors.Wrap(err, "validate")
}
return &request, rawBody, close, nil
default:
return req, rawBody, close, validate.InvalidContentType(ct)
}
}
func (s *Server) decodeUpdateOrganizationInvitationRequest(r *http.Request) (
req *OrganizationInvitationUpdate,
rawBody []byte,
@@ -657,6 +657,133 @@ func encodeCreateMySupportCaseResponse(response CreateMySupportCaseRes, w http.R
}
}
func encodeCreateOrganizationResponse(response CreateOrganizationRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *OrganizationHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Cache-Control" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Cache-Control",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
return e.EncodeValue(conv.StringToString(string(response.CacheControl)))
}); err != nil {
return errors.Wrap(err, "encode Cache-Control header")
}
}
}
w.WriteHeader(201)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *CreateOrganizationBadRequest:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(400)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *CreateOrganizationUnauthorized:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(401)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *CreateOrganizationForbidden:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(403)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *CreateOrganizationConflict:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(409)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *CreateOrganizationUnprocessableEntity:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(422)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *TooManyRequestsHeaders:
w.Header().Set("Content-Type", "application/problem+json")
w.Header().Set("Access-Control-Expose-Headers", "Retry-After")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Retry-After" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Retry-After",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
if val, ok := response.RetryAfter.Get(); ok {
return e.EncodeValue(conv.Int32ToString(val))
}
return nil
}); err != nil {
return errors.Wrap(err, "encode Retry-After header")
}
}
}
w.WriteHeader(429)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeCreateOrganizationInvitationResponse(response CreateOrganizationInvitationRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *OrganizationInvitationHeaders:
@@ -1769,6 +1896,89 @@ func encodeGetMySupportCaseResponse(response GetMySupportCaseRes, w http.Respons
}
}
func encodeGetOrganizationResponse(response GetOrganizationRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *OrganizationHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Cache-Control" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Cache-Control",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
return e.EncodeValue(conv.StringToString(string(response.CacheControl)))
}); err != nil {
return errors.Wrap(err, "encode Cache-Control header")
}
}
}
w.WriteHeader(200)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *GetOrganizationBadRequest:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(400)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *GetOrganizationUnauthorized:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(401)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *GetOrganizationForbidden:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(403)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *GetOrganizationNotFound:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(404)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeGetOrganizationInvitationResponse(response GetOrganizationInvitationRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *OrganizationInvitationHeaders:
@@ -2161,6 +2371,77 @@ func encodeListMyInvitationsResponse(response ListMyInvitationsRes, w http.Respo
}
}
func encodeListMyOrganizationsResponse(response ListMyOrganizationsRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *MyOrganizationListHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Cache-Control" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Cache-Control",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
return e.EncodeValue(conv.StringToString(string(response.CacheControl)))
}); err != nil {
return errors.Wrap(err, "encode Cache-Control header")
}
}
}
w.WriteHeader(200)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *ListMyOrganizationsBadRequest:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(400)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *ListMyOrganizationsUnauthorized:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(401)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *ListMyOrganizationsForbidden:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(403)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeListMySupportCasesResponse(response ListMySupportCasesRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *SupportCaseListHeaders:
@@ -3282,6 +3563,133 @@ func encodeSubmitMyAssessmentAnswerResponse(response SubmitMyAssessmentAnswerRes
}
}
func encodeUpdateOrganizationResponse(response UpdateOrganizationRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *OrganizationHeaders:
w.Header().Set("Content-Type", "application/json; charset=utf-8")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Cache-Control" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Cache-Control",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
return e.EncodeValue(conv.StringToString(string(response.CacheControl)))
}); err != nil {
return errors.Wrap(err, "encode Cache-Control header")
}
}
}
w.WriteHeader(200)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *UpdateOrganizationBadRequest:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(400)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *UpdateOrganizationUnauthorized:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(401)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *UpdateOrganizationForbidden:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(403)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *UpdateOrganizationNotFound:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(404)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *UpdateOrganizationPreconditionFailed:
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(412)
e := new(jx.Encoder)
response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
case *TooManyRequestsHeaders:
w.Header().Set("Content-Type", "application/problem+json")
w.Header().Set("Access-Control-Expose-Headers", "Retry-After")
// Encoding response headers.
{
h := uri.NewHeaderEncoder(w.Header())
// Encode "Retry-After" header.
{
cfg := uri.HeaderParameterEncodingConfig{
Name: "Retry-After",
Explode: false,
}
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
if val, ok := response.RetryAfter.Get(); ok {
return e.EncodeValue(conv.Int32ToString(val))
}
return nil
}); err != nil {
return errors.Wrap(err, "encode Retry-After header")
}
}
}
w.WriteHeader(429)
e := new(jx.Encoder)
response.Response.Encode(e)
if _, err := e.WriteTo(w); err != nil {
return errors.Wrap(err, "write")
}
return nil
default:
return errors.Errorf("unexpected response type: %T", response)
}
}
func encodeUpdateOrganizationInvitationResponse(response UpdateOrganizationInvitationRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *OrganizationInvitationHeaders:
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -60,6 +60,7 @@ var operationRolesSessionCookie = map[string][]string{
CancelMyInvitationOperation: []string{},
CreateMyAssessmentAttemptOperation: []string{},
CreateMySupportCaseOperation: []string{},
CreateOrganizationOperation: []string{},
CreateOrganizationInvitationOperation: []string{},
CreateOrganizationNeedOperation: []string{},
DeclineMyInvitationOperation: []string{},
@@ -72,11 +73,13 @@ var operationRolesSessionCookie = map[string][]string{
GetMyInvitationOperation: []string{},
GetMyQuestionnaireOperation: []string{},
GetMySupportCaseOperation: []string{},
GetOrganizationOperation: []string{},
GetOrganizationInvitationOperation: []string{},
GetOrganizationInvitationContactsOperation: []string{},
GetOrganizationNeedOperation: []string{},
ListMyConsentsOperation: []string{},
ListMyInvitationsOperation: []string{},
ListMyOrganizationsOperation: []string{},
ListMySupportCasesOperation: []string{},
ListOrganizationInvitationsOperation: []string{},
ListOrganizationNeedsOperation: []string{},
@@ -85,6 +88,7 @@ var operationRolesSessionCookie = map[string][]string{
SaveMyQuestionnaireOperation: []string{},
SendOrganizationInvitationOperation: []string{},
SubmitMyAssessmentAnswerOperation: []string{},
UpdateOrganizationOperation: []string{},
UpdateOrganizationInvitationOperation: []string{},
UpdateOrganizationNeedOperation: []string{},
ViewMyInvitationOperation: []string{},
@@ -118,6 +122,7 @@ var operationRolesSessionCsrf = map[string][]string{
CancelMyInvitationOperation: []string{},
CreateMyAssessmentAttemptOperation: []string{},
CreateMySupportCaseOperation: []string{},
CreateOrganizationOperation: []string{},
CreateOrganizationInvitationOperation: []string{},
CreateOrganizationNeedOperation: []string{},
DeclineMyInvitationOperation: []string{},
@@ -127,6 +132,7 @@ var operationRolesSessionCsrf = map[string][]string{
SaveMyQuestionnaireOperation: []string{},
SendOrganizationInvitationOperation: []string{},
SubmitMyAssessmentAnswerOperation: []string{},
UpdateOrganizationOperation: []string{},
UpdateOrganizationInvitationOperation: []string{},
UpdateOrganizationNeedOperation: []string{},
ViewMyInvitationOperation: []string{},
@@ -253,6 +253,36 @@ type Handler interface {
//
// POST /api/v1/me/support-cases
CreateMySupportCase(ctx context.Context, req SupportCaseCreate, params CreateMySupportCaseParams) (CreateMySupportCaseRes, error)
// CreateOrganization implements CreateOrganization operation.
//
// Requires the session cookie of an employer account with a confirmed email, the CSRF token of that
// session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The owner is the account of the
// session: the body has no owner, membership, role, verification, or version field, and unknown fields
// fail validation.
//
// The server creates the organization and the owner membership of the caller (role `owner`, state
// `active`) in one transaction, so an organization never exists without its owner. The organization
// starts at the verification level `e0` with the basis `confirmed_email`. The level cannot be
// requested: the creator of a company with a corporate domain, a long description, or many
// representatives still gets `e0`, and `e1`, `e2`, and `e3` come only from verification processes of
// the server that do not exist yet. Only `name` is required; the rest of the card can be completed
// with UpdateOrganization.
//
// Idempotency: a retry with the same key and body within 24 hours replays the stored 201 and creates
// nothing, so a lost response never creates a second organization. A different body with the same key
// answers 422 idempotency_key_reused. 400 is never stored, so a corrected retry is evaluated again.
// Two requests with different keys are two organizations; the product may limit the number of
// organizations per account (open question), which would answer 409 `state_conflict` without a change
// of the schema.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden for a candidate account), the Idempotency-Key (422, 409
// idempotency_in_progress, replay), domain rules (400 with a pointer such as `/contacts/website` for a
// website that is not an https URL of a host name, `/name` for a name with surrounding whitespace).
// The general rate limit can answer 429 with Retry-After before any check; 429 is never stored.
//
// POST /api/v1/organizations
CreateOrganization(ctx context.Context, req *OrganizationCreate, params CreateOrganizationParams) (CreateOrganizationRes, error)
// CreateOrganizationInvitation implements CreateOrganizationInvitation operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
@@ -608,6 +638,30 @@ type Handler interface {
//
// GET /api/v1/me/support-cases/{case_id}
GetMySupportCase(ctx context.Context, params GetMySupportCaseParams) (GetMySupportCaseRes, error)
// GetOrganization implements GetOrganization operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
// organization comes from the path and is checked against the membership that the server holds for the
// session account on every request; the identifier itself grants nothing.
//
// Returns the profile with its current `version`, the verification level (`verification`), and the
// card as a candidate sees it (`candidate_card`). The verification level is always the one the server
// holds: it never rises because the profile is complete, because the organization has members, or
// because of an email domain. The role of the caller is not part of this resource; ListMyOrganizations
// returns it with the membership.
//
// In the MVP the profile is readable by any active member; every member is an owner, because the
// operations that add members are planned. The roles of PRD FR07 that read a company card without
// managing it change no field of this contract.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate
// account answers 403 forbidden; an account without an active membership in the organization,
// including a `suspended`, `removed`, or `left` one, and an unknown organization all answer 404
// not_found, so organizations cannot be enumerated. A malformed `org_id` answers 400 validation_failed
// with the path pointer.
//
// GET /api/v1/organizations/{org_id}
GetOrganization(ctx context.Context, params GetOrganizationParams) (GetOrganizationRes, error)
// GetOrganizationInvitation implements GetOrganizationInvitation operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
@@ -765,6 +819,35 @@ type Handler interface {
//
// GET /api/v1/me/invitations
ListMyInvitations(ctx context.Context, params ListMyInvitationsParams) (ListMyInvitationsRes, error)
// ListMyOrganizations implements ListMyOrganizations operation.
//
// Requires the session cookie of an employer account. The account comes from the session, never from a
// request parameter, so the response holds only the caller's own memberships and no request can name
// another account.
//
// Returns a page of the organizations in which the caller has an `active` membership, newest
// membership first with the organization identifier as the tie-breaker, with cursor pagination. Each
// item names the organization (`OrganizationSummary`) and holds the caller's role and state in it
// (`OrganizationMembership`). A membership in another state (`suspended`, `removed`, `left`) does not
// list its organization, so an organization the caller cannot enter is never named, and one that the
// caller was removed from disappears from the list at once.
//
// The list is the directory of the active organization context. The context is not stored on the
// server: every organization-scoped operation names its organization in the path `org_id`, and the
// server checks that identifier against the caller's active membership on every request, so a switch
// between organizations is a different `org_id` in the client's routes and cannot outlive a revoked
// membership. A client picks the context from this list, may remember the last choice in the browser
// as a convenience, and must read the list again after any answer 404 `not_found` from an organization
// path. An account with several memberships sees all of them here and works in one at a time; the
// rights and the data of the organizations stay separate.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate
// account answers 403 forbidden. An employer account without an organization gets an empty page, which
// tells the client to offer CreateOrganization. A malformed `limit` or `cursor` answers 400
// validation_failed.
//
// GET /api/v1/me/organizations
ListMyOrganizations(ctx context.Context, params ListMyOrganizationsParams) (ListMyOrganizationsRes, error)
// ListMySupportCases implements ListMySupportCases operation.
//
// Requires the session cookie of a candidate or an employer account. Returns a page of the cases that
@@ -1086,6 +1169,42 @@ type Handler interface {
//
// POST /api/v1/me/assessment-attempts/{attempt_id}/answers
SubmitMyAssessmentAnswer(ctx context.Context, req *AssessmentAnswerSubmission, params SubmitMyAssessmentAnswerParams) (SubmitMyAssessmentAnswerRes, error)
// UpdateOrganization implements UpdateOrganization operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
// token of that session in X-CSRF-Token, and an allowed Origin. Only the owner manages the
// organization (the FR07 matrix gives this to no other role), so a member with another role answers
// 403 forbidden. The role comes from the server-side membership; the body has no organization,
// membership, role, owner, or verification field.
//
// Merge rules: the body is `application/json` with explicit field replacement, not JSON Merge Patch.
// Each field present replaces that field as a whole and an absent field stays unchanged; `contacts`
// and `representatives` are replaced entirely and never merged. `description` and `sphere` sent as
// null become unset; `name`, `contacts`, and `representatives` cannot be null.
//
// The body can change the profile only. The verification level, its basis, the card, the members, and
// every role are not fields of it, and unknown fields fail validation, so the owner can neither raise
// the trust level of the organization nor the rights of anyone by editing the profile; a longer
// description, a verified-looking website, or a new representative leaves the level unchanged. The
// level and the roles change only through processes of the server.
//
// Versions: every committed change creates version `expected_version + 1` and answers 200 with the
// organization. `expected_version` is the `version` the client read; when it is not current, the
// server answers 412 version_conflict and changes nothing, and the client reads the organization again
// and reapplies its edits. The version travels in the body rather than in If-Match because the
// generated client cannot read the ETag response header yet, as for needs. A body that changes nothing
// when applied to the current profile keeps the version and answers 200 with the current organization
// even when `expected_version` is older, so the operation needs no Idempotency-Key and a retry of a
// change that already succeeded is harmless.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden for a candidate account), membership (404 not_found) and role (403
// forbidden), a body that changes nothing (200), the version (412), domain rules (400 with a pointer
// such as `/contacts/website`, `/name`, or `/representatives/0/job_title`). The general rate limit can
// answer 429 with Retry-After before any check.
//
// PATCH /api/v1/organizations/{org_id}
UpdateOrganization(ctx context.Context, req *OrganizationUpdate, params UpdateOrganizationParams) (UpdateOrganizationRes, error)
// UpdateOrganizationInvitation implements UpdateOrganizationInvitation operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
@@ -273,6 +273,39 @@ func (UnimplementedHandler) CreateMySupportCase(ctx context.Context, req Support
return r, ht.ErrNotImplemented
}
// CreateOrganization implements CreateOrganization operation.
//
// Requires the session cookie of an employer account with a confirmed email, the CSRF token of that
// session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The owner is the account of the
// session: the body has no owner, membership, role, verification, or version field, and unknown fields
// fail validation.
//
// The server creates the organization and the owner membership of the caller (role `owner`, state
// `active`) in one transaction, so an organization never exists without its owner. The organization
// starts at the verification level `e0` with the basis `confirmed_email`. The level cannot be
// requested: the creator of a company with a corporate domain, a long description, or many
// representatives still gets `e0`, and `e1`, `e2`, and `e3` come only from verification processes of
// the server that do not exist yet. Only `name` is required; the rest of the card can be completed
// with UpdateOrganization.
//
// Idempotency: a retry with the same key and body within 24 hours replays the stored 201 and creates
// nothing, so a lost response never creates a second organization. A different body with the same key
// answers 422 idempotency_key_reused. 400 is never stored, so a corrected retry is evaluated again.
// Two requests with different keys are two organizations; the product may limit the number of
// organizations per account (open question), which would answer 409 `state_conflict` without a change
// of the schema.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden for a candidate account), the Idempotency-Key (422, 409
// idempotency_in_progress, replay), domain rules (400 with a pointer such as `/contacts/website` for a
// website that is not an https URL of a host name, `/name` for a name with surrounding whitespace).
// The general rate limit can answer 429 with Retry-After before any check; 429 is never stored.
//
// POST /api/v1/organizations
func (UnimplementedHandler) CreateOrganization(ctx context.Context, req *OrganizationCreate, params CreateOrganizationParams) (r CreateOrganizationRes, _ error) {
return r, ht.ErrNotImplemented
}
// CreateOrganizationInvitation implements CreateOrganizationInvitation operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
@@ -670,6 +703,33 @@ func (UnimplementedHandler) GetMySupportCase(ctx context.Context, params GetMySu
return r, ht.ErrNotImplemented
}
// GetOrganization implements GetOrganization operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
// organization comes from the path and is checked against the membership that the server holds for the
// session account on every request; the identifier itself grants nothing.
//
// Returns the profile with its current `version`, the verification level (`verification`), and the
// card as a candidate sees it (`candidate_card`). The verification level is always the one the server
// holds: it never rises because the profile is complete, because the organization has members, or
// because of an email domain. The role of the caller is not part of this resource; ListMyOrganizations
// returns it with the membership.
//
// In the MVP the profile is readable by any active member; every member is an owner, because the
// operations that add members are planned. The roles of PRD FR07 that read a company card without
// managing it change no field of this contract.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate
// account answers 403 forbidden; an account without an active membership in the organization,
// including a `suspended`, `removed`, or `left` one, and an unknown organization all answer 404
// not_found, so organizations cannot be enumerated. A malformed `org_id` answers 400 validation_failed
// with the path pointer.
//
// GET /api/v1/organizations/{org_id}
func (UnimplementedHandler) GetOrganization(ctx context.Context, params GetOrganizationParams) (r GetOrganizationRes, _ error) {
return r, ht.ErrNotImplemented
}
// GetOrganizationInvitation implements GetOrganizationInvitation operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`. The
@@ -845,6 +905,38 @@ func (UnimplementedHandler) ListMyInvitations(ctx context.Context, params ListMy
return r, ht.ErrNotImplemented
}
// ListMyOrganizations implements ListMyOrganizations operation.
//
// Requires the session cookie of an employer account. The account comes from the session, never from a
// request parameter, so the response holds only the caller's own memberships and no request can name
// another account.
//
// Returns a page of the organizations in which the caller has an `active` membership, newest
// membership first with the organization identifier as the tie-breaker, with cursor pagination. Each
// item names the organization (`OrganizationSummary`) and holds the caller's role and state in it
// (`OrganizationMembership`). A membership in another state (`suspended`, `removed`, `left`) does not
// list its organization, so an organization the caller cannot enter is never named, and one that the
// caller was removed from disappears from the list at once.
//
// The list is the directory of the active organization context. The context is not stored on the
// server: every organization-scoped operation names its organization in the path `org_id`, and the
// server checks that identifier against the caller's active membership on every request, so a switch
// between organizations is a different `org_id` in the client's routes and cannot outlive a revoked
// membership. A client picks the context from this list, may remember the last choice in the browser
// as a convenience, and must read the list again after any answer 404 `not_found` from an organization
// path. An account with several memberships sees all of them here and works in one at a time; the
// rights and the data of the organizations stay separate.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate
// account answers 403 forbidden. An employer account without an organization gets an empty page, which
// tells the client to offer CreateOrganization. A malformed `limit` or `cursor` answers 400
// validation_failed.
//
// GET /api/v1/me/organizations
func (UnimplementedHandler) ListMyOrganizations(ctx context.Context, params ListMyOrganizationsParams) (r ListMyOrganizationsRes, _ error) {
return r, ht.ErrNotImplemented
}
// ListMySupportCases implements ListMySupportCases operation.
//
// Requires the session cookie of a candidate or an employer account. Returns a page of the cases that
@@ -1199,6 +1291,45 @@ func (UnimplementedHandler) SubmitMyAssessmentAnswer(ctx context.Context, req *A
return r, ht.ErrNotImplemented
}
// UpdateOrganization implements UpdateOrganization operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
// token of that session in X-CSRF-Token, and an allowed Origin. Only the owner manages the
// organization (the FR07 matrix gives this to no other role), so a member with another role answers
// 403 forbidden. The role comes from the server-side membership; the body has no organization,
// membership, role, owner, or verification field.
//
// Merge rules: the body is `application/json` with explicit field replacement, not JSON Merge Patch.
// Each field present replaces that field as a whole and an absent field stays unchanged; `contacts`
// and `representatives` are replaced entirely and never merged. `description` and `sphere` sent as
// null become unset; `name`, `contacts`, and `representatives` cannot be null.
//
// The body can change the profile only. The verification level, its basis, the card, the members, and
// every role are not fields of it, and unknown fields fail validation, so the owner can neither raise
// the trust level of the organization nor the rights of anyone by editing the profile; a longer
// description, a verified-looking website, or a new representative leaves the level unchanged. The
// level and the roles change only through processes of the server.
//
// Versions: every committed change creates version `expected_version + 1` and answers 200 with the
// organization. `expected_version` is the `version` the client read; when it is not current, the
// server answers 412 version_conflict and changes nothing, and the client reads the organization again
// and reapplies its edits. The version travels in the body rather than in If-Match because the
// generated client cannot read the ETag response header yet, as for needs. A body that changes nothing
// when applied to the current profile keeps the version and answers 200 with the current organization
// even when `expected_version` is older, so the operation needs no Idempotency-Key and a retry of a
// change that already succeeded is harmless.
//
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
// account scenario (403 forbidden for a candidate account), membership (404 not_found) and role (403
// forbidden), a body that changes nothing (200), the version (412), domain rules (400 with a pointer
// such as `/contacts/website`, `/name`, or `/representatives/0/job_title`). The general rate limit can
// answer 429 with Retry-After before any check.
//
// PATCH /api/v1/organizations/{org_id}
func (UnimplementedHandler) UpdateOrganization(ctx context.Context, req *OrganizationUpdate, params UpdateOrganizationParams) (r UpdateOrganizationRes, _ error) {
return r, ht.ErrNotImplemented
}
// UpdateOrganizationInvitation implements UpdateOrganizationInvitation operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,576 @@
package httpadapter
import (
"context"
"log/slog"
"net/http"
"reflect"
"slices"
"strings"
"testing"
"github.com/ogen-go/ogen"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/adapter/primary/http/problem"
v1 "lincodex/backend/internal/adapter/primary/http/v1"
metrics "lincodex/backend/internal/adapter/secondary/prometheus"
)
// Organization request fixtures shared by the organization tests.
const (
myOrganizationsPath = "/api/v1/me/organizations"
organizationsPath = "/api/v1/organizations"
organizationPath = organizationsPath + "/01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01"
validOrganizationContacts = `{"website":"https://payments.example.com","email":"careers@payments.example.com","phone":"+74950000000","telegram":"@payments_careers"}`
emptyOrganizationContacts = `{"website":null,"email":null,"phone":null,"telegram":null}`
)
// organizationBody builds a JSON object from the given members.
func organizationBody(members ...string) string {
return "{" + strings.Join(members, ",") + "}"
}
// The schemas alone must accept the profile a company may send and reject
// what no request may carry: a role, an owner, a verification level or its
// basis, the members, the card, a version, or an identifier. Security accepts
// the session here, so the request reaches validation; a valid request then
// answers 501 until the operations are implemented. The rules that need
// storage, such as the website host or the version, pass the schema and are
// checked by the server.
func TestOrganizationSchemaValidationPrecedesImplementation(t *testing.T) {
session := map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken}
command := map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken, "Idempotency-Key": testIdempotencyKey}
create := func(body string) identityRequest {
return identityRequest{method: http.MethodPost, path: organizationsPath, body: body, headers: command}
}
update := func(members ...string) identityRequest {
return identityRequest{method: http.MethodPatch, path: organizationPath, body: organizationBody(append([]string{`"expected_version":1`}, members...)...), headers: session}
}
forbiddenFields := []string{
`"role":"owner"`,
`"owner_id":"01928f7a-0000-7000-8000-00000000c0de"`,
`"verification_level":"e1"`,
`"verification":{"level":"e2","basis":"manual_review","changed_at":"2026-10-06T09:00:00Z"}`,
`"verification_basis":"corporate_domain"`,
`"members":[{"user_id":"01928f7a-0000-7000-8000-00000000c0de","role":"owner"}]`,
`"membership":{"organization_id":"01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01","role":"owner","state":"active","joined_at":"2026-10-06T09:00:00Z"}`,
`"candidate_card":{}`,
`"id":"01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01"`,
`"version":3`,
`"created_at":"2026-10-06T09:00:00Z"`,
}
type expectation struct {
name string
request identityRequest
location api.ProblemFieldLocation
pointer string
code string
}
tests := make([]expectation, 0, 36+2*len(forbiddenFields))
tests = append(tests, []expectation{
{
name: "list",
request: identityRequest{method: http.MethodGet, path: myOrganizationsPath + "?limit=20", headers: session},
},
{
name: "list with a limit above the maximum",
request: identityRequest{method: http.MethodGet, path: myOrganizationsPath + "?limit=101", headers: session},
location: api.ProblemFieldLocationQuery, pointer: "/limit", code: "invalid",
},
{
name: "list with a malformed cursor",
request: identityRequest{method: http.MethodGet, path: myOrganizationsPath + "?cursor=not%20a%20cursor", headers: session},
location: api.ProblemFieldLocationQuery, pointer: "/cursor", code: "invalid",
},
{
name: "create with a name only",
request: create(organizationBody(`"name":"ООО Пример Платежи"`)),
},
{
name: "create with a complete card",
request: create(organizationBody(
`"name":"ООО Пример Платежи"`,
`"description":"Платежный сервис.\nСобственное ядро."`,
`"sphere":"Платежи и финансовые сервисы"`,
`"contacts":`+validOrganizationContacts,
`"representatives":[{"name":"Анна Тестова","job_title":"Руководитель по подбору"}]`,
)),
},
{
name: "create with an explicit null description and sphere",
request: create(organizationBody(`"name":"ООО Пример"`, `"description":null`, `"sphere":null`, `"contacts":`+emptyOrganizationContacts, `"representatives":[]`)),
},
{
// A domain rule of the server: the schema accepts any https
// string without credentials, and the host rules come after it.
name: "create with a website that has a port",
request: create(organizationBody(`"name":"ООО Пример"`, `"contacts":{"website":"https://payments.example.com:8443","email":null,"phone":null,"telegram":null}`)),
},
{
name: "create without a name",
request: create(organizationBody(`"sphere":"Платежи"`)),
location: api.ProblemFieldLocationBody, pointer: "/name", code: "required",
},
{
name: "create without an Idempotency-Key",
request: identityRequest{method: http.MethodPost, path: organizationsPath, body: organizationBody(`"name":"ООО Пример"`), headers: session},
location: api.ProblemFieldLocationHeader, pointer: "/Idempotency-Key", code: "required",
},
{
name: "create with an empty name",
request: create(organizationBody(`"name":""`)),
location: api.ProblemFieldLocationBody, pointer: "/name", code: "invalid",
},
{
name: "create with a name over 200 characters",
request: create(organizationBody(`"name":"` + strings.Repeat("я", 201) + `"`)),
location: api.ProblemFieldLocationBody, pointer: "/name", code: "invalid",
},
{
name: "create with a name that has a leading space",
request: create(organizationBody(`"name":" ООО"`)),
location: api.ProblemFieldLocationBody, pointer: "/name", code: "invalid",
},
{
name: "create with a name that has a line break",
request: create(organizationBody(`"name":"ООО\nПример"`)),
location: api.ProblemFieldLocationBody, pointer: "/name", code: "invalid",
},
{
name: "create with a sphere that has a trailing space",
request: create(organizationBody(`"name":"ООО"`, `"sphere":"Платежи "`)),
location: api.ProblemFieldLocationBody, pointer: "/sphere", code: "invalid",
},
{
name: "create with an empty description",
request: create(organizationBody(`"name":"ООО"`, `"description":""`)),
location: api.ProblemFieldLocationBody, pointer: "/description", code: "invalid",
},
{
name: "create with contacts that omit a field",
request: create(organizationBody(`"name":"ООО"`, `"contacts":{"website":null,"email":null,"phone":null}`)),
location: api.ProblemFieldLocationBody, pointer: "/contacts/telegram", code: "required",
},
{
name: "create with a personal contact kind",
request: create(organizationBody(`"name":"ООО"`, `"contacts":{"website":null,"email":null,"phone":null,"telegram":null,"home_address":"ул. Тестовая"}`)),
location: api.ProblemFieldLocationBody, pointer: "/contacts", code: "invalid",
},
{
name: "create with an http website",
request: create(organizationBody(`"name":"ООО"`, `"contacts":{"website":"http://payments.example.com","email":null,"phone":null,"telegram":null}`)),
location: api.ProblemFieldLocationBody, pointer: "/contacts/website", code: "invalid",
},
{
name: "create with a website that has credentials",
request: create(organizationBody(`"name":"ООО"`, `"contacts":{"website":"https://user:secret@payments.example.com","email":null,"phone":null,"telegram":null}`)),
location: api.ProblemFieldLocationBody, pointer: "/contacts/website", code: "invalid",
},
{
name: "create with a phone that is not E.164",
request: create(organizationBody(`"name":"ООО"`, `"contacts":{"website":null,"email":null,"phone":"8 495 000-00-00","telegram":null}`)),
location: api.ProblemFieldLocationBody, pointer: "/contacts/phone", code: "invalid",
},
{
name: "create with a Telegram username without the at sign",
request: create(organizationBody(`"name":"ООО"`, `"contacts":{"website":null,"email":null,"phone":null,"telegram":"payments_careers"}`)),
location: api.ProblemFieldLocationBody, pointer: "/contacts/telegram", code: "invalid",
},
{
name: "create with an email that is not an address",
request: create(organizationBody(`"name":"ООО"`, `"contacts":{"website":null,"email":"careers","phone":null,"telegram":null}`)),
location: api.ProblemFieldLocationBody, pointer: "/contacts/email", code: "invalid",
},
{
name: "create with eleven representatives",
request: create(organizationBody(`"name":"ООО"`, `"representatives":[`+
strings.TrimSuffix(strings.Repeat(`{"name":"Имя","job_title":"Должность"},`, 11), ",")+`]`)),
location: api.ProblemFieldLocationBody, pointer: "/representatives", code: "invalid",
},
{
// A failure inside an array element during decoding reports the
// pointer of the array, because jx reports no element index.
name: "create with a representative that has no job title",
request: create(organizationBody(`"name":"ООО"`, `"representatives":[{"name":"Анна Тестова"}]`)),
location: api.ProblemFieldLocationBody, pointer: "/representatives", code: "invalid",
},
{
name: "create with a representative contact",
request: create(organizationBody(`"name":"ООО"`, `"representatives":[{"name":"Анна Тестова","job_title":"HR","email":"anna@example.com"}]`)),
location: api.ProblemFieldLocationBody, pointer: "/representatives", code: "invalid",
},
{
name: "update with the version only",
request: update(),
},
{
name: "update of the profile with explicit nulls",
request: update(`"description":null`, `"sphere":null`),
},
{
name: "update of the contacts and representatives as a whole",
request: update(`"contacts":`+emptyOrganizationContacts, `"representatives":[]`),
},
{
name: "update without expected_version",
request: identityRequest{method: http.MethodPatch, path: organizationPath, body: organizationBody(`"name":"ООО Новое"`), headers: session},
location: api.ProblemFieldLocationBody, pointer: "/expected_version", code: "required",
},
{
name: "update with expected_version zero",
request: identityRequest{method: http.MethodPatch, path: organizationPath, body: organizationBody(`"expected_version":0`), headers: session},
location: api.ProblemFieldLocationBody, pointer: "/expected_version", code: "invalid",
},
{
name: "update with a null name",
request: update(`"name":null`),
location: api.ProblemFieldLocationBody, pointer: "/name", code: "invalid",
},
{
name: "update with null representatives",
request: update(`"representatives":null`),
location: api.ProblemFieldLocationBody, pointer: "/representatives", code: "invalid",
},
{
name: "update with null contacts",
request: update(`"contacts":null`),
location: api.ProblemFieldLocationBody, pointer: "/contacts", code: "invalid",
},
{
name: "read",
request: identityRequest{method: http.MethodGet, path: organizationPath, headers: session},
},
{
name: "read an organization identifier that is not a UUID",
request: identityRequest{method: http.MethodGet, path: organizationsPath + "/acme", headers: session},
location: api.ProblemFieldLocationPath, pointer: "/org_id", code: "invalid",
},
{
name: "update an organization identifier that is not a UUID",
request: identityRequest{method: http.MethodPatch, path: organizationsPath + "/acme", body: organizationBody(`"expected_version":1`), headers: session},
location: api.ProblemFieldLocationPath, pointer: "/org_id", code: "invalid",
},
}...)
// No request of either command may carry a right or a trust level, each
// one alone, as a whole-body rejection of an unknown field.
for _, field := range forbiddenFields {
tests = append(tests,
expectation{
name: "create with the forbidden field " + strings.SplitN(field, ":", 2)[0],
request: create(organizationBody(`"name":"ООО Пример"`, field)),
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
},
expectation{
name: "update with the forbidden field " + strings.SplitN(field, ":", 2)[0],
request: update(field),
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
},
)
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
logger := slog.New(slog.DiscardHandler)
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
response := serveIdentityRequest(t, router, test.request)
switch test.code {
case "":
requireProblem(t, response, http.StatusNotImplemented, api.ProblemCodeNotImplemented)
default:
body := requireProblem(t, response, http.StatusBadRequest, api.ProblemCodeValidationFailed)
want := api.ProblemFieldError{In: test.location, Pointer: test.pointer, Code: test.code}
for _, field := range body.Errors {
if field.In == want.In && field.Pointer == want.Pointer && field.Code == want.Code {
return
}
}
t.Fatalf("errors = %+v, want an entry %+v", body.Errors, want)
}
})
}
}
// Every organization operation requires an employer session; DenyAllSecurity
// grants none, with or without a cookie and a CSRF token, and no request can
// name another account.
func TestOrganizationAccessBeforeImplementation(t *testing.T) {
session := map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken}
command := map[string]string{"Cookie": testSessionCookie, "X-CSRF-Token": testCSRFToken, "Idempotency-Key": testIdempotencyKey}
for _, test := range []identityRequest{
{method: http.MethodGet, path: myOrganizationsPath},
{method: http.MethodGet, path: myOrganizationsPath, headers: map[string]string{"Cookie": testSessionCookie}},
{method: http.MethodGet, path: myOrganizationsPath + "?user_id=01928f7a-0000-7000-8000-00000000c0de", headers: map[string]string{"Cookie": testSessionCookie}},
{method: http.MethodPost, path: organizationsPath, body: organizationBody(`"name":"ООО Пример"`), headers: command},
{method: http.MethodGet, path: organizationPath},
{method: http.MethodGet, path: organizationPath, headers: map[string]string{"Cookie": testSessionCookie}},
{method: http.MethodPatch, path: organizationPath, body: organizationBody(`"expected_version":1`, `"name":"ООО Новое"`), headers: session},
} {
t.Run(test.method+" "+test.path, func(t *testing.T) {
router := newTestRouter(t, func(context.Context) error { return nil })
requireProblem(t, serveIdentityRequest(t, router, test), http.StatusUnauthorized, api.ProblemCodeUnauthenticated)
})
}
}
// A role and a verification level never travel in the company DTOs: not in
// the response a member reads, not in the create or the update body. The
// role lives in OrganizationMembership, which a client cannot send, and the
// level in OrganizationVerification, which only the response carries.
func TestOrganizationDTOsCarryNoRoleOrVerificationInTheirRequests(t *testing.T) {
raising := []string{
"role", "roles", "verification", "verification_level", "verification_basis", "level", "basis", "trust_level",
"owner", "owner_id", "members", "membership", "user_id", "account_id", "permissions", "e0", "e1", "e2", "e3",
}
for _, dto := range []any{api.Organization{}, api.OrganizationCreate{}, api.OrganizationUpdate{}, api.CandidateOrganizationCard{}, api.OrganizationContactChannels{}, api.OrganizationRepresentative{}} {
typ := reflect.TypeOf(dto)
for i := range typ.NumField() {
name, _, _ := strings.Cut(typ.Field(i).Tag.Get("json"), ",")
isVerificationReadModel := (typ == reflect.TypeFor[api.Organization]() && name == "verification") ||
(typ == reflect.TypeFor[api.CandidateOrganizationCard]() && name == "verification_level")
for _, field := range raising {
if name == field && !isVerificationReadModel {
t.Errorf("%s exposes the field %q", typ.Name(), name)
}
}
}
}
// The two request DTOs have no verification field at all, not even the
// read-only ones of the response.
for _, dto := range []any{api.OrganizationCreate{}, api.OrganizationUpdate{}} {
assertNoJSONFields(t, dto, []string{"verification", "verification_level", "candidate_card", "id", "version", "created_at", "updated_at"})
}
// The profile fields of a request are the whole editable surface.
for _, profile := range []struct {
dto any
want []string
}{
{api.OrganizationCreate{}, []string{"name", "description", "sphere", "contacts", "representatives"}},
{api.OrganizationUpdate{}, []string{"expected_version", "name", "description", "sphere", "contacts", "representatives"}},
} {
typ, want := reflect.TypeOf(profile.dto), profile.want
got := make([]string, 0, typ.NumField())
for i := range typ.NumField() {
name, _, _ := strings.Cut(typ.Field(i).Tag.Get("json"), ",")
got = append(got, name)
}
if strings.Join(got, ",") != strings.Join(want, ",") {
t.Errorf("%s fields = %v, want exactly %v", typ.Name(), got, want)
}
}
// The candidate's card holds neither a member, a role, nor the ground
// of the verification.
assertNoJSONFields(t, api.CandidateOrganizationCard{}, []string{"role", "membership", "members", "verification", "basis", "version", "created_at", "updated_at", "user_id"})
// The caller's own membership is the only place of a role, and it names
// no account.
assertNoJSONFields(t, api.OrganizationMembership{}, []string{"user_id", "account_id", "email"})
// The list takes only the page, so no parameter names another account.
params := reflect.TypeFor[api.ListMyOrganizationsParams]()
names := make([]string, 0, params.NumField())
for i := range params.NumField() {
names = append(names, params.Field(i).Name)
}
if got := strings.Join(names, ","); got != "Limit,Cursor" {
t.Fatalf("ListMyOrganizationsParams fields = %s, want only the page", got)
}
}
// An update separates an absent list (unchanged) from an empty one (replaced
// by an empty list) by nil, and null is not a list or an object.
func TestOrganizationUpdateDecodingKeepsAbsentAndEmptyListsApart(t *testing.T) {
var empty api.OrganizationUpdate
if err := empty.UnmarshalJSON([]byte(`{"expected_version":1,"representatives":[]}`)); err != nil {
t.Fatalf("decode an empty list: %v", err)
}
if empty.Representatives == nil || len(empty.Representatives) != 0 {
t.Fatalf("representatives = %#v, want a non-nil empty slice", empty.Representatives)
}
var absent api.OrganizationUpdate
if err := absent.UnmarshalJSON([]byte(`{"expected_version":1}`)); err != nil {
t.Fatalf("decode an absent list: %v", err)
}
if absent.Representatives != nil || absent.Name.IsSet() || absent.Contacts.IsSet() || absent.Description.IsSet() || absent.Sphere.IsSet() {
t.Fatal("absent fields are set, want unset")
}
var cleared api.OrganizationUpdate
if err := cleared.UnmarshalJSON([]byte(`{"expected_version":1,"description":null,"sphere":"Платежи"}`)); err != nil {
t.Fatalf("decode a null description: %v", err)
}
if !cleared.Description.IsSet() || !cleared.Description.IsNull() || !cleared.Sphere.IsSet() || cleared.Sphere.IsNull() {
t.Fatal("description sent as null is not a set null, or the sphere is not a value")
}
for _, body := range []string{
`{"expected_version":1,"representatives":null}`,
`{"expected_version":1,"name":null}`,
`{"expected_version":1,"contacts":null}`,
} {
var null api.OrganizationUpdate
if err := null.UnmarshalJSON([]byte(body)); err == nil {
t.Fatalf("decode %s succeeded, want an error", body)
}
}
}
// The representatives of the candidate card are optional and nullable: absent
// or null means that they are not published.
func TestCandidateOrganizationCardRepresentativesAreOptional(t *testing.T) {
const base = `"id":"01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01","name":"ООО Пример","description":null,"sphere":null,"contacts":` + emptyOrganizationContacts + `,"verification_level":"e0"`
for name, body := range map[string]string{
"absent": "{" + base + "}",
"null": "{" + base + `,"representatives":null}`,
"empty": "{" + base + `,"representatives":[]}`,
} {
var card api.CandidateOrganizationCard
if err := card.UnmarshalJSON([]byte(body)); err != nil {
t.Fatalf("decode a card with %s representatives: %v", name, err)
}
if err := card.Validate(); err != nil {
t.Fatalf("validate a card with %s representatives: %v", name, err)
}
}
var withoutContacts api.CandidateOrganizationCard
if err := withoutContacts.UnmarshalJSON([]byte(`{"id":"01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01","name":"ООО","description":null,"sphere":null,"verification_level":"e0"}`)); err == nil {
t.Fatal("decode a card without contacts succeeded, want an error")
}
}
// The documented examples are valid values of the generated types, and the
// organizations they show never claim a level above e0 on their own.
func TestOrganizationExamplesAreValidResponsesAndNeverRaiseTheLevel(t *testing.T) {
for _, name := range []string{"OrganizationNameOnly", "OrganizationCompleteCard"} {
var organization api.Organization
if err := organization.UnmarshalJSON(supportCaseExample(t, name)); err != nil {
t.Fatalf("decode the %s example: %v", name, err)
}
if err := organization.Validate(); err != nil {
t.Fatalf("validate the %s example: %v", name, err)
}
if organization.Verification.Level != api.OrganizationVerificationLevelE0 || organization.Verification.Basis != api.OrganizationVerificationBasisConfirmedEmail ||
organization.CandidateCard.VerificationLevel != api.OrganizationVerificationLevelE0 {
t.Fatalf("%s example verification = %+v, want e0 on the confirmed email", name, organization.Verification)
}
if organization.CandidateCard.ID != organization.ID || organization.CandidateCard.Name != organization.Name {
t.Fatalf("%s example card does not repeat the profile", name)
}
}
var page api.MyOrganizationList
if err := page.UnmarshalJSON(supportCaseExample(t, "MyOrganizationListPage")); err != nil {
t.Fatalf("decode the MyOrganizationListPage example: %v", err)
}
if err := page.Validate(); err != nil {
t.Fatalf("validate the MyOrganizationListPage example: %v", err)
}
for _, item := range page.Items {
if item.Membership.State != api.MembershipStateActive || item.Membership.OrganizationID != item.Organization.ID {
t.Fatalf("listed item %+v, want an active membership of the listed organization", item)
}
}
for _, name := range []string{"OrganizationCreateNameOnly", "OrganizationCreateCompleteCard"} {
var create api.OrganizationCreate
if err := create.UnmarshalJSON(supportCaseExample(t, name)); err != nil {
t.Fatalf("decode the %s example: %v", name, err)
}
if err := create.Validate(); err != nil {
t.Fatalf("validate the %s example: %v", name, err)
}
}
var update api.OrganizationUpdate
if err := update.UnmarshalJSON(supportCaseExample(t, "OrganizationUpdateCompleteCard")); err != nil {
t.Fatalf("decode the OrganizationUpdateCompleteCard example: %v", err)
}
if err := update.Validate(); err != nil {
t.Fatalf("validate the OrganizationUpdateCompleteCard example: %v", err)
}
}
// The contract enums list every level, basis, role, and state of the PRD now,
// so adding one later is not a contract change. At the contract level, the
// profile bodies are closed objects without a role or a level, and no
// operation sets the verification level or a role.
func TestOrganizationContractFollowsThePRD(t *testing.T) {
spec := parsePublicContract(t)
for name, want := range map[string][]string{
"OrganizationVerificationLevel": {"e0", "e1", "e2", "e3"},
"OrganizationVerificationBasis": {"confirmed_email", "corporate_domain", "requisites_and_authority", "manual_review", "partner_status"},
"OrganizationRole": {"owner", "recruiter", "hiring_manager", "technical_expert"},
"MembershipState": {"active", "suspended", "removed", "left"},
} {
if got := enumValues(t, resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/" + name})); !slices.Equal(got, want) {
t.Errorf("%s = %v, want %v", name, got, want)
}
}
// The requests are closed objects whose properties are the profile.
for name, want := range map[string][]string{
"OrganizationCreate": {"name", "description", "sphere", "contacts", "representatives"},
"OrganizationUpdate": {"expected_version", "name", "description", "sphere", "contacts", "representatives"},
} {
schema := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/" + name})
if schema.AdditionalProperties == nil || schema.AdditionalProperties.Bool == nil || *schema.AdditionalProperties.Bool {
t.Errorf("%s accepts unknown fields", name)
}
got := make([]string, 0, len(schema.Properties))
for _, property := range schema.Properties {
got = append(got, property.Name)
}
slices.Sort(got)
sorted := slices.Clone(want)
slices.Sort(sorted)
if !slices.Equal(got, sorted) {
t.Errorf("%s properties = %v, want %v", name, got, sorted)
}
}
update := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/OrganizationUpdate"})
if !slices.Contains(update.Required, "expected_version") {
t.Error("OrganizationUpdate does not require expected_version")
}
create := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/OrganizationCreate"})
if !slices.Equal(create.Required, []string{"name"}) {
t.Errorf("OrganizationCreate required = %v, want only the name", create.Required)
}
// Writing needs the CSRF token, and creating needs an Idempotency-Key.
for _, id := range []string{"CreateOrganization", "UpdateOrganization"} {
operation := operationByID(t, spec, id)
if len(operation.Security) != 1 {
t.Fatalf("%s security = %v, want one requirement", id, operation.Security)
}
if _, ok := operation.Security[0][sessionCSRFScheme]; !ok {
t.Errorf("%s does not require the CSRF token", id)
}
}
if !slices.ContainsFunc(operationByID(t, spec, "CreateOrganization").Parameters, func(parameter *ogen.Parameter) bool {
return parameter.Ref == "#/components/parameters/IdempotencyKey"
}) {
t.Error("CreateOrganization does not require an Idempotency-Key")
}
if _, ok := operationByID(t, spec, "UpdateOrganization").Responses["412"]; !ok {
t.Error("UpdateOrganization does not declare 412")
}
// Nothing in the organization paths sets a verification level or a role.
for path, item := range spec.Paths {
if !strings.HasPrefix(path, "/api/v1/organizations") && path != myOrganizationsPath {
continue
}
for _, operation := range []*ogen.Operation{item.Get, item.Post, item.Put, item.Patch, item.Delete} {
if operation == nil {
continue
}
id := strings.ToLower(operation.OperationID)
if strings.Contains(id, "verification") || strings.Contains(id, "verify") || strings.Contains(id, "role") || strings.Contains(id, "promote") {
t.Errorf("%s %s sets a level or a role", path, operation.OperationID)
}
}
}
}
@@ -0,0 +1,430 @@
package postgres
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// organizationConstraintErrors maps the organization constraints whose
// violation is a caller-visible outcome to port sentinels by SQLSTATE and
// constraint name, never by text.
var organizationConstraintErrors = map[constraintViolation]error{
{uniqueViolationCode, "memberships_user_id_organization_id_key"}: outbound.ErrMembershipExists,
{foreignKeyViolationCode, "memberships_organization_id_fkey"}: outbound.ErrOrganizationNotFound,
{foreignKeyViolationCode, "memberships_user_id_fkey"}: outbound.ErrUserNotFound,
{foreignKeyViolationCode, "organization_representatives_organization_id_fkey"}: outbound.ErrOrganizationNotFound,
}
// mapOrganizationError turns a known organization constraint violation into
// its port sentinel and keeps the constraint name. Any other PostgreSQL error
// is replaced by its SQLSTATE and constraint name, because its detail quotes
// the failing row, which holds names of representatives. Deadlocks and
// serialization failures also match ErrTransactionConflict. A connection
// error loses the pgx prefix that names the database user and database.
func mapOrganizationError(err error) error {
var pgError *pgconn.PgError
if !errors.As(err, &pgError) {
return sanitizeConnectError(err)
}
if sentinel, ok := organizationConstraintErrors[constraintViolation{code: pgError.Code, constraint: pgError.ConstraintName}]; ok {
return fmt.Errorf("postgres.mapOrganizationError - violate constraint %s: %w", pgError.ConstraintName, sentinel)
}
return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName})
}
var _ outbound.OrganizationRepositories = (*UnitOfWork)(nil)
func (unit *UnitOfWork) Organizations() outbound.OrganizationRepository {
return organizationRepository{queries: unit.queries}
}
func (unit *UnitOfWork) Memberships() outbound.MembershipRepository {
return membershipRepository{queries: unit.queries}
}
type organizationRepository struct {
queries *sqlc.Queries
}
var _ outbound.OrganizationRepository = organizationRepository{}
func (repository organizationRepository) CreateWithOwner(ctx context.Context, organization domain.Organization, owner domain.Membership) error {
const location = "organizationRepository.CreateWithOwner"
switch {
case organization.IsZero():
return fmt.Errorf("%s - organization was not built by domain.NewOrganization: %w", location, domain.ErrInvalidOrganization)
case owner.IsZero():
return fmt.Errorf("%s - owner was not built by domain.NewOwnerMembership: %w", location, domain.ErrInvalidMembership)
case owner.OrganizationID() != organization.ID() || owner.Role() != domain.OrganizationRoleOwner || !owner.GrantsAccess():
return fmt.Errorf("%s - owner must be the active owner membership of the organization: %w", location, domain.ErrInvalidMembership)
}
profile := organization.Profile()
contacts := profile.Contacts()
verification := organization.Verification()
err := repository.queries.InsertOrganization(ctx, sqlc.InsertOrganizationParams{
ID: pgUUID(organization.ID()),
Name: profile.Name(),
Description: pgOptionalText(profile.Description()),
Sphere: pgOptionalText(profile.Sphere()),
ContactWebsite: pgOptionalText(contacts.Website()),
ContactEmail: pgOptionalText(contacts.Email()),
ContactPhone: pgOptionalText(contacts.Phone()),
ContactTelegram: pgOptionalText(contacts.Telegram()),
VerificationLevel: string(verification.Level()),
VerificationBasis: string(verification.Basis()),
VerificationChangedAt: pgTime(verification.ChangedAt()),
Version: organization.Version(),
CreatedAt: pgTime(organization.CreatedAt()),
UpdatedAt: pgTime(organization.UpdatedAt()),
})
if err != nil {
return fmt.Errorf("%s - insert organization: %w", location, mapOrganizationError(err))
}
if err := repository.insertRepresentatives(ctx, organization.ID(), profile.Representatives()); err != nil {
return fmt.Errorf("%s - insert representatives: %w", location, err)
}
if err := insertMembership(ctx, repository.queries, owner); err != nil {
return fmt.Errorf("%s - insert owner membership: %w", location, err)
}
return nil
}
func (repository organizationRepository) insertRepresentatives(
ctx context.Context,
organizationID uuid.UUID,
representatives []domain.OrganizationRepresentative,
) error {
for index, representative := range representatives {
err := repository.queries.InsertOrganizationRepresentative(ctx, sqlc.InsertOrganizationRepresentativeParams{
OrganizationID: pgUUID(organizationID),
Ordinal: int16(index),
Name: representative.Name(),
JobTitle: representative.JobTitle(),
})
if err != nil {
return mapOrganizationError(err)
}
}
return nil
}
func (repository organizationRepository) GetForMember(
ctx context.Context,
organizationID, userID uuid.UUID,
) (domain.Organization, domain.Membership, error) {
const location = "organizationRepository.GetForMember"
row, err := repository.queries.GetOrganizationForMember(ctx, sqlc.GetOrganizationForMemberParams{
OrganizationID: pgUUID(organizationID),
UserID: pgUUID(userID),
})
if err != nil {
return domain.Organization{}, domain.Membership{}, fmt.Errorf("%s - select organization: %w", location, mapOrganizationNoRows(err, outbound.ErrOrganizationNotFound))
}
representatives, err := decodeRepresentatives(row.Representatives)
if err != nil {
return domain.Organization{}, domain.Membership{}, fmt.Errorf("%s - decode representatives: %w", location, err)
}
organization, err := organizationFromColumns(organizationColumns{
ID: row.ID, Name: row.Name, Description: row.Description, Sphere: row.Sphere,
ContactWebsite: row.ContactWebsite, ContactEmail: row.ContactEmail,
ContactPhone: row.ContactPhone, ContactTelegram: row.ContactTelegram,
VerificationLevel: row.VerificationLevel, VerificationBasis: row.VerificationBasis,
VerificationChangedAt: row.VerificationChangedAt, Version: row.Version,
CreatedAt: row.CreatedAt, UpdatedAt: row.UpdatedAt,
}, representatives)
if err != nil {
return domain.Organization{}, domain.Membership{}, err
}
membership, err := domain.RestoreMembership(domain.StoredMembership{
ID: optionalUUID(row.MembershipID),
OrganizationID: organizationID,
UserID: userID,
Role: row.MembershipRole,
State: row.MembershipState,
CreatedAt: row.MembershipCreatedAt.Time,
UpdatedAt: row.MembershipUpdatedAt.Time,
})
if err != nil {
return domain.Organization{}, domain.Membership{}, fmt.Errorf("%s - restore membership: %w", location, err)
}
return organization, membership, nil
}
// representativeJSON is one element of the representatives column that
// GetOrganizationForMember aggregates in the same statement as the
// organization, so the profile and the list come from one snapshot.
type representativeJSON struct {
Name string `json:"name"`
JobTitle string `json:"job_title"`
}
func decodeRepresentatives(column string) ([]domain.StoredRepresentative, error) {
var decoded []representativeJSON
if err := json.Unmarshal([]byte(column), &decoded); err != nil {
// The error of the decoder can quote the document, which holds names.
return nil, errors.New("postgres.decodeRepresentatives - the representatives column is not a list of name and job title")
}
representatives := make([]domain.StoredRepresentative, 0, len(decoded))
for _, representative := range decoded {
representatives = append(representatives, domain.StoredRepresentative(representative))
}
return representatives, nil
}
func (repository organizationRepository) ListForUser(ctx context.Context, query outbound.OrganizationListQuery) (outbound.OrganizationPage, error) {
const location = "organizationRepository.ListForUser"
if query.UserID == uuid.Nil {
return outbound.OrganizationPage{}, fmt.Errorf("%s - user ID must not be nil: %w", location, domain.ErrInvalidMembership)
}
if query.Limit < 1 || query.Limit > outbound.MaxOrganizationPageSize {
return outbound.OrganizationPage{}, fmt.Errorf("%s - limit must be 1 to %d: %w", location, outbound.MaxOrganizationPageSize, domain.ErrInvalidMembership)
}
params := sqlc.ListOrganizationsForUserParams{
UserID: pgUUID(query.UserID),
// One extra row tells whether another page follows.
RowLimit: query.Limit + 1,
}
if query.After != nil {
if err := requireTime(location, query.After.JoinedAt, domain.ErrInvalidMembership); err != nil {
return outbound.OrganizationPage{}, err
}
if query.After.OrganizationID == uuid.Nil {
return outbound.OrganizationPage{}, fmt.Errorf("%s - position organization ID must not be nil: %w", location, domain.ErrInvalidMembership)
}
params.AfterJoinedAt = pgTime(query.After.JoinedAt)
params.AfterOrganizationID = pgUUID(query.After.OrganizationID)
}
rows, err := repository.queries.ListOrganizationsForUser(ctx, params)
if err != nil {
return outbound.OrganizationPage{}, fmt.Errorf("%s - select organizations: %w", location, mapOrganizationError(err))
}
page := outbound.OrganizationPage{HasMore: len(rows) > int(query.Limit)}
if page.HasMore {
rows = rows[:query.Limit]
}
page.Items = make([]outbound.MemberOrganization, 0, len(rows))
for _, row := range rows {
summary, err := domain.RestoreOrganizationSummary(optionalUUID(row.ID), row.Name, row.VerificationLevel)
if err != nil {
return outbound.OrganizationPage{}, fmt.Errorf("%s - restore organization: %w", location, err)
}
membership, err := domain.RestoreMembership(domain.StoredMembership{
ID: optionalUUID(row.MembershipID),
OrganizationID: summary.ID(),
UserID: query.UserID,
Role: row.MembershipRole,
State: row.MembershipState,
CreatedAt: row.MembershipCreatedAt.Time,
UpdatedAt: row.MembershipUpdatedAt.Time,
})
if err != nil {
return outbound.OrganizationPage{}, fmt.Errorf("%s - restore membership: %w", location, err)
}
page.Items = append(page.Items, outbound.MemberOrganization{Organization: summary, Membership: membership})
}
return page, nil
}
func (repository organizationRepository) UpdateProfile(
ctx context.Context,
actorID uuid.UUID,
organization domain.Organization,
) (domain.Organization, error) {
const location = "organizationRepository.UpdateProfile"
if organization.IsZero() || actorID == uuid.Nil {
return domain.Organization{}, fmt.Errorf("%s - organization and actor must be set: %w", location, domain.ErrInvalidOrganization)
}
// The generated parameter structs of this repository hold representative
// names and contacts: never log them.
profile := organization.Profile()
contacts := profile.Contacts()
row, err := repository.queries.UpdateOrganizationProfile(ctx, sqlc.UpdateOrganizationProfileParams{
Name: profile.Name(),
Description: pgOptionalText(profile.Description()),
Sphere: pgOptionalText(profile.Sphere()),
ContactWebsite: pgOptionalText(contacts.Website()),
ContactEmail: pgOptionalText(contacts.Email()),
ContactPhone: pgOptionalText(contacts.Phone()),
ContactTelegram: pgOptionalText(contacts.Telegram()),
UpdatedAt: pgTime(organization.UpdatedAt()),
ID: pgUUID(organization.ID()),
ExpectedVersion: organization.Version(),
ActorID: pgUUID(actorID),
ManagerRoles: managerRoleNames(),
})
if errors.Is(err, pgx.ErrNoRows) {
return domain.Organization{}, fmt.Errorf("%s - update organization: %w", location, repository.explainRejectedUpdate(ctx, actorID, organization))
}
if err != nil {
return domain.Organization{}, fmt.Errorf("%s - update organization: %w", location, mapOrganizationError(err))
}
// The row lock of the update holds until the transaction ends, so no
// other writer replaces the list between these statements.
if err := repository.queries.DeleteOrganizationRepresentatives(ctx, row.ID); err != nil {
return domain.Organization{}, fmt.Errorf("%s - delete representatives: %w", location, mapOrganizationError(err))
}
if err := repository.insertRepresentatives(ctx, organization.ID(), profile.Representatives()); err != nil {
return domain.Organization{}, fmt.Errorf("%s - insert representatives: %w", location, err)
}
stored := make([]domain.StoredRepresentative, 0, len(profile.Representatives()))
for _, representative := range profile.Representatives() {
stored = append(stored, domain.StoredRepresentative{Name: representative.Name(), JobTitle: representative.JobTitle()})
}
return organizationFromColumns(organizationColumns(row), stored)
}
// explainRejectedUpdate tells why the update matched no row: an unknown
// organization or an actor without an active membership, a membership whose
// role cannot manage, or a stale version, in that order.
func (repository organizationRepository) explainRejectedUpdate(
ctx context.Context,
actorID uuid.UUID,
organization domain.Organization,
) error {
row, err := repository.queries.GetOrganizationForMember(ctx, sqlc.GetOrganizationForMemberParams{
OrganizationID: pgUUID(organization.ID()),
UserID: pgUUID(actorID),
})
switch {
case errors.Is(err, pgx.ErrNoRows):
return outbound.ErrOrganizationNotFound
case err != nil:
return mapOrganizationError(err)
}
role, err := domain.ParseOrganizationRole(row.MembershipRole)
switch {
case err != nil:
return fmt.Errorf("postgres.explainRejectedUpdate - validate role: %w", err)
case !role.CanManageOrganization():
return outbound.ErrOrganizationManagerRequired
default:
return outbound.ErrOrganizationVersionConflict
}
}
func managerRoleNames() []string {
roles := domain.ManagerRoles()
names := make([]string, 0, len(roles))
for _, role := range roles {
names = append(names, string(role))
}
return names
}
// organizationColumns has the columns of an organization row that every
// organization query returns. The generated row of UpdateOrganizationProfile
// converts to it.
type organizationColumns struct {
ID pgtype.UUID
Name string
Description pgtype.Text
Sphere pgtype.Text
ContactWebsite pgtype.Text
ContactEmail pgtype.Text
ContactPhone pgtype.Text
ContactTelegram pgtype.Text
VerificationLevel string
VerificationBasis string
VerificationChangedAt pgtype.Timestamptz
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
func organizationFromColumns(columns organizationColumns, representatives []domain.StoredRepresentative) (domain.Organization, error) {
organization, err := domain.RestoreOrganization(domain.StoredOrganization{
ID: optionalUUID(columns.ID),
Name: columns.Name,
Description: columns.Description.String,
Sphere: columns.Sphere.String,
Website: columns.ContactWebsite.String,
Email: columns.ContactEmail.String,
Phone: columns.ContactPhone.String,
Telegram: columns.ContactTelegram.String,
Representatives: representatives,
VerificationLevel: columns.VerificationLevel,
VerificationBasis: columns.VerificationBasis,
VerificationChangedAt: columns.VerificationChangedAt.Time,
Version: columns.Version,
CreatedAt: columns.CreatedAt.Time,
UpdatedAt: columns.UpdatedAt.Time,
})
if err != nil {
return domain.Organization{}, fmt.Errorf("postgres.organizationFromColumns - restore organization: %w", err)
}
return organization, nil
}
type membershipRepository struct {
queries *sqlc.Queries
}
var _ outbound.MembershipRepository = membershipRepository{}
func (repository membershipRepository) Insert(ctx context.Context, membership domain.Membership) error {
if membership.IsZero() {
return fmt.Errorf("membershipRepository.Insert - membership was not built by domain.NewMembership: %w", domain.ErrInvalidMembership)
}
if err := insertMembership(ctx, repository.queries, membership); err != nil {
return fmt.Errorf("membershipRepository.Insert - insert membership: %w", err)
}
return nil
}
func insertMembership(ctx context.Context, queries *sqlc.Queries, membership domain.Membership) error {
err := queries.InsertMembership(ctx, sqlc.InsertMembershipParams{
ID: pgUUID(membership.ID()),
OrganizationID: pgUUID(membership.OrganizationID()),
UserID: pgUUID(membership.UserID()),
Role: string(membership.Role()),
State: string(membership.State()),
CreatedAt: pgTime(membership.CreatedAt()),
UpdatedAt: pgTime(membership.UpdatedAt()),
})
if err != nil {
return mapOrganizationError(err)
}
return nil
}
func (repository membershipRepository) Get(ctx context.Context, organizationID, userID uuid.UUID) (domain.Membership, error) {
const location = "membershipRepository.Get"
row, err := repository.queries.GetMembership(ctx, sqlc.GetMembershipParams{
OrganizationID: pgUUID(organizationID),
UserID: pgUUID(userID),
})
if err != nil {
return domain.Membership{}, fmt.Errorf("%s - select membership: %w", location, mapOrganizationNoRows(err, outbound.ErrMembershipNotFound))
}
membership, err := domain.RestoreMembership(domain.StoredMembership{
ID: optionalUUID(row.ID),
OrganizationID: optionalUUID(row.OrganizationID),
UserID: optionalUUID(row.UserID),
Role: row.Role,
State: row.State,
CreatedAt: row.CreatedAt.Time,
UpdatedAt: row.UpdatedAt.Time,
})
if err != nil {
return domain.Membership{}, fmt.Errorf("%s - restore membership: %w", location, err)
}
return membership, nil
}
func mapOrganizationNoRows(err, sentinel error) error {
if errors.Is(err, pgx.ErrNoRows) {
return sentinel
}
return mapOrganizationError(err)
}
@@ -0,0 +1,83 @@
package postgres
import (
"context"
"errors"
"strings"
"testing"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgconn"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// organizationDetailMarker stands for a row value that a PostgreSQL detail
// can quote, such as the name of a representative.
const organizationDetailMarker = "Failing row contains (Анна Тестова, Руководитель)"
func TestMapOrganizationErrorRecognizesOrganizationConstraints(t *testing.T) {
for _, test := range []struct {
code string
constraint string
want error
}{
{code: uniqueViolationCode, constraint: "memberships_user_id_organization_id_key", want: outbound.ErrMembershipExists},
{code: foreignKeyViolationCode, constraint: "memberships_organization_id_fkey", want: outbound.ErrOrganizationNotFound},
{code: foreignKeyViolationCode, constraint: "memberships_user_id_fkey", want: outbound.ErrUserNotFound},
{code: foreignKeyViolationCode, constraint: "organization_representatives_organization_id_fkey", want: outbound.ErrOrganizationNotFound},
} {
err := mapOrganizationError(&pgconn.PgError{Code: test.code, ConstraintName: test.constraint, Detail: organizationDetailMarker})
if !errors.Is(err, test.want) {
t.Fatalf("mapOrganizationError(%s %s) = %v, want %v", test.code, test.constraint, err, test.want)
}
if !strings.Contains(err.Error(), test.constraint) || strings.Contains(err.Error(), "Failing row") {
t.Fatalf("mapOrganizationError(%s) = %v, want the constraint name and no detail", test.constraint, err)
}
}
}
func TestMapOrganizationErrorDropsDetailOfOtherErrors(t *testing.T) {
// A CHECK violation that the domain should have prevented keeps only the
// SQLSTATE and the constraint, never the failing row with its names.
err := mapOrganizationError(&pgconn.PgError{Code: checkViolationCode, ConstraintName: "organization_representatives_name_format", Detail: organizationDetailMarker})
var stateError sqlStateError
if !errors.As(err, &stateError) || stateError.SQLState() != checkViolationCode {
t.Fatalf("mapOrganizationError() = %v, want SQLSTATE %s", err, checkViolationCode)
}
if strings.Contains(err.Error(), "Анна") || strings.Contains(err.Error(), "Failing row") {
t.Fatalf("mapOrganizationError() = %v, want no row values", err)
}
if err := mapOrganizationError(&pgconn.PgError{Code: deadlockDetectedCode}); !errors.Is(err, outbound.ErrTransactionConflict) {
t.Fatalf("mapOrganizationError(deadlock) = %v, want ErrTransactionConflict", err)
}
if err := mapOrganizationError(context.Canceled); !errors.Is(err, context.Canceled) {
t.Fatalf("mapOrganizationError(context.Canceled) = %v, want the original error", err)
}
}
func TestOrganizationRepositoriesRejectInvalidInputBeforeQuerying(t *testing.T) {
// A repository without queries proves that no statement runs.
organizations := organizationRepository{}
memberships := membershipRepository{}
ctx := t.Context()
if err := organizations.CreateWithOwner(ctx, domain.Organization{}, domain.Membership{}); !errors.Is(err, domain.ErrInvalidOrganization) {
t.Fatalf("CreateWithOwner(zero organization) error = %v, want ErrInvalidOrganization", err)
}
if err := memberships.Insert(ctx, domain.Membership{}); !errors.Is(err, domain.ErrInvalidMembership) {
t.Fatalf("Insert(zero membership) error = %v, want ErrInvalidMembership", err)
}
if _, err := organizations.UpdateProfile(ctx, uuid.New(), domain.Organization{}); !errors.Is(err, domain.ErrInvalidOrganization) {
t.Fatalf("UpdateProfile(zero organization) error = %v, want ErrInvalidOrganization", err)
}
if _, err := organizations.ListForUser(ctx, outbound.OrganizationListQuery{}); !errors.Is(err, domain.ErrInvalidMembership) {
t.Fatalf("ListForUser(zero query) error = %v, want ErrInvalidMembership", err)
}
}
func TestManagerRoleNamesFollowTheDomainRule(t *testing.T) {
if got := managerRoleNames(); len(got) != 1 || got[0] != string(domain.OrganizationRoleOwner) {
t.Fatalf("managerRoleNames() = %v, want only the owner", got)
}
}
@@ -140,6 +140,40 @@ type MailRequest struct {
CreatedAt pgtype.Timestamptz
}
type Membership struct {
ID pgtype.UUID
OrganizationID pgtype.UUID
UserID pgtype.UUID
Role string
State string
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
type Organization struct {
ID pgtype.UUID
Name string
Description pgtype.Text
Sphere pgtype.Text
ContactWebsite pgtype.Text
ContactEmail pgtype.Text
ContactPhone pgtype.Text
ContactTelegram pgtype.Text
VerificationLevel string
VerificationBasis string
VerificationChangedAt pgtype.Timestamptz
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
type OrganizationRepresentative struct {
OrganizationID pgtype.UUID
Ordinal int16
Name string
JobTitle string
}
type OutboxEvent struct {
Position pgtype.Int8
EventID pgtype.UUID
@@ -0,0 +1,505 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: organizations.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const deleteOrganizationRepresentatives = `-- name: DeleteOrganizationRepresentatives :exec
DELETE FROM organization_representatives
WHERE organization_id = $1
`
func (q *Queries) DeleteOrganizationRepresentatives(ctx context.Context, organizationID pgtype.UUID) error {
_, err := q.db.Exec(ctx, deleteOrganizationRepresentatives, organizationID)
return err
}
const getMembership = `-- name: GetMembership :one
SELECT
id,
organization_id,
user_id,
role,
state,
created_at,
updated_at
FROM memberships
WHERE
organization_id = $1
AND user_id = $2
`
type GetMembershipParams struct {
OrganizationID pgtype.UUID
UserID pgtype.UUID
}
// Reads the membership of one account in one organization, in any state.
func (q *Queries) GetMembership(ctx context.Context, arg GetMembershipParams) (Membership, error) {
row := q.db.QueryRow(ctx, getMembership, arg.OrganizationID, arg.UserID)
var i Membership
err := row.Scan(
&i.ID,
&i.OrganizationID,
&i.UserID,
&i.Role,
&i.State,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const getOrganizationForMember = `-- name: GetOrganizationForMember :one
SELECT
organization.id,
organization.name,
organization.description,
organization.sphere,
organization.contact_website,
organization.contact_email,
organization.contact_phone,
organization.contact_telegram,
organization.verification_level,
organization.verification_basis,
organization.verification_changed_at,
organization.version,
organization.created_at,
organization.updated_at,
coalesce((
SELECT
jsonb_agg(
jsonb_build_object('name', representative.name, 'job_title', representative.job_title)
ORDER BY representative.ordinal
)
FROM organization_representatives AS representative
WHERE representative.organization_id = organization.id
), '[]'::jsonb)::text AS representatives,
membership.id AS membership_id,
membership.role AS membership_role,
membership.state AS membership_state,
membership.created_at AS membership_created_at,
membership.updated_at AS membership_updated_at
FROM organizations AS organization
INNER JOIN memberships AS membership ON organization.id = membership.organization_id
WHERE
organization.id = $1
AND membership.user_id = $2
AND membership.state = 'active'
`
type GetOrganizationForMemberParams struct {
OrganizationID pgtype.UUID
UserID pgtype.UUID
}
type GetOrganizationForMemberRow struct {
ID pgtype.UUID
Name string
Description pgtype.Text
Sphere pgtype.Text
ContactWebsite pgtype.Text
ContactEmail pgtype.Text
ContactPhone pgtype.Text
ContactTelegram pgtype.Text
VerificationLevel string
VerificationBasis string
VerificationChangedAt pgtype.Timestamptz
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
Representatives string
MembershipID pgtype.UUID
MembershipRole string
MembershipState string
MembershipCreatedAt pgtype.Timestamptz
MembershipUpdatedAt pgtype.Timestamptz
}
// Reads an organization together with the membership of one account in it
// and its representatives in list order, as one statement, so the profile and
// the list come from one snapshot. Only an active membership matches, so an
// unknown organization, an account that is no member, and a suspended,
// removed, or left member all return no row and cannot be told apart.
func (q *Queries) GetOrganizationForMember(ctx context.Context, arg GetOrganizationForMemberParams) (GetOrganizationForMemberRow, error) {
row := q.db.QueryRow(ctx, getOrganizationForMember, arg.OrganizationID, arg.UserID)
var i GetOrganizationForMemberRow
err := row.Scan(
&i.ID,
&i.Name,
&i.Description,
&i.Sphere,
&i.ContactWebsite,
&i.ContactEmail,
&i.ContactPhone,
&i.ContactTelegram,
&i.VerificationLevel,
&i.VerificationBasis,
&i.VerificationChangedAt,
&i.Version,
&i.CreatedAt,
&i.UpdatedAt,
&i.Representatives,
&i.MembershipID,
&i.MembershipRole,
&i.MembershipState,
&i.MembershipCreatedAt,
&i.MembershipUpdatedAt,
)
return i, err
}
const insertMembership = `-- name: InsertMembership :exec
INSERT INTO memberships (
id,
organization_id,
user_id,
role,
state,
created_at,
updated_at
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7
)
`
type InsertMembershipParams struct {
ID pgtype.UUID
OrganizationID pgtype.UUID
UserID pgtype.UUID
Role string
State string
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
func (q *Queries) InsertMembership(ctx context.Context, arg InsertMembershipParams) error {
_, err := q.db.Exec(ctx, insertMembership,
arg.ID,
arg.OrganizationID,
arg.UserID,
arg.Role,
arg.State,
arg.CreatedAt,
arg.UpdatedAt,
)
return err
}
const insertOrganization = `-- name: InsertOrganization :exec
INSERT INTO organizations (
id,
name,
description,
sphere,
contact_website,
contact_email,
contact_phone,
contact_telegram,
verification_level,
verification_basis,
verification_changed_at,
version,
created_at,
updated_at
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8,
$9,
$10,
$11,
$12,
$13,
$14
)
`
type InsertOrganizationParams struct {
ID pgtype.UUID
Name string
Description pgtype.Text
Sphere pgtype.Text
ContactWebsite pgtype.Text
ContactEmail pgtype.Text
ContactPhone pgtype.Text
ContactTelegram pgtype.Text
VerificationLevel string
VerificationBasis string
VerificationChangedAt pgtype.Timestamptz
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
// Stores a new organization with the verification level that the domain
// gave it. The deferred constraint organizations_owner_required fails the
// transaction at commit unless an active owner membership was inserted in
// it too.
func (q *Queries) InsertOrganization(ctx context.Context, arg InsertOrganizationParams) error {
_, err := q.db.Exec(ctx, insertOrganization,
arg.ID,
arg.Name,
arg.Description,
arg.Sphere,
arg.ContactWebsite,
arg.ContactEmail,
arg.ContactPhone,
arg.ContactTelegram,
arg.VerificationLevel,
arg.VerificationBasis,
arg.VerificationChangedAt,
arg.Version,
arg.CreatedAt,
arg.UpdatedAt,
)
return err
}
const insertOrganizationRepresentative = `-- name: InsertOrganizationRepresentative :exec
INSERT INTO organization_representatives (
organization_id,
ordinal,
name,
job_title
) VALUES (
$1,
$2,
$3,
$4
)
`
type InsertOrganizationRepresentativeParams struct {
OrganizationID pgtype.UUID
Ordinal int16
Name string
JobTitle string
}
// Stores one representative at its position in the list. The adapter calls it
// once per representative after it deleted the previous list, in the same
// transaction.
func (q *Queries) InsertOrganizationRepresentative(ctx context.Context, arg InsertOrganizationRepresentativeParams) error {
_, err := q.db.Exec(ctx, insertOrganizationRepresentative,
arg.OrganizationID,
arg.Ordinal,
arg.Name,
arg.JobTitle,
)
return err
}
const listOrganizationsForUser = `-- name: ListOrganizationsForUser :many
SELECT
organization.id,
organization.name,
organization.verification_level,
membership.id AS membership_id,
membership.role AS membership_role,
membership.state AS membership_state,
membership.created_at AS membership_created_at,
membership.updated_at AS membership_updated_at
FROM memberships AS membership
INNER JOIN organizations AS organization ON membership.organization_id = organization.id
WHERE
membership.user_id = $1
AND membership.state = 'active'
AND (
$2::timestamptz IS NULL
OR (membership.created_at, membership.organization_id) < (
$2::timestamptz,
$3::uuid
)
)
ORDER BY membership.created_at DESC, membership.organization_id DESC
LIMIT $4
`
type ListOrganizationsForUserParams struct {
UserID pgtype.UUID
AfterJoinedAt pgtype.Timestamptz
AfterOrganizationID pgtype.UUID
RowLimit int32
}
type ListOrganizationsForUserRow struct {
ID pgtype.UUID
Name string
VerificationLevel string
MembershipID pgtype.UUID
MembershipRole string
MembershipState string
MembershipCreatedAt pgtype.Timestamptz
MembershipUpdatedAt pgtype.Timestamptz
}
// Lists the organizations where an account has an active membership,
// newest membership first. The page continues after the (membership
// creation time, organization ID) position of the last item of the
// previous page. Only the active memberships of the given account match.
func (q *Queries) ListOrganizationsForUser(ctx context.Context, arg ListOrganizationsForUserParams) ([]ListOrganizationsForUserRow, error) {
rows, err := q.db.Query(ctx, listOrganizationsForUser,
arg.UserID,
arg.AfterJoinedAt,
arg.AfterOrganizationID,
arg.RowLimit,
)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListOrganizationsForUserRow
for rows.Next() {
var i ListOrganizationsForUserRow
if err := rows.Scan(
&i.ID,
&i.Name,
&i.VerificationLevel,
&i.MembershipID,
&i.MembershipRole,
&i.MembershipState,
&i.MembershipCreatedAt,
&i.MembershipUpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const updateOrganizationProfile = `-- name: UpdateOrganizationProfile :one
WITH target AS (
SELECT id FROM organizations
WHERE
id = $9
AND version = $10
FOR UPDATE
),
actor AS (
SELECT memberships.id FROM memberships
INNER JOIN target ON memberships.organization_id = target.id
WHERE
memberships.user_id = $11
AND memberships.state = 'active'
AND memberships.role = any($12::text [])
FOR SHARE OF memberships
)
UPDATE organizations
SET
name = $1,
description = $2,
sphere = $3,
contact_website = $4,
contact_email = $5,
contact_phone = $6,
contact_telegram = $7,
updated_at = $8,
version = organizations.version + 1
FROM actor
WHERE
organizations.id = $9
AND organizations.version = $10
RETURNING
organizations.id,
organizations.name,
organizations.description,
organizations.sphere,
organizations.contact_website,
organizations.contact_email,
organizations.contact_phone,
organizations.contact_telegram,
organizations.verification_level,
organizations.verification_basis,
organizations.verification_changed_at,
organizations.version,
organizations.created_at,
organizations.updated_at
`
type UpdateOrganizationProfileParams struct {
Name string
Description pgtype.Text
Sphere pgtype.Text
ContactWebsite pgtype.Text
ContactEmail pgtype.Text
ContactPhone pgtype.Text
ContactTelegram pgtype.Text
UpdatedAt pgtype.Timestamptz
ID pgtype.UUID
ExpectedVersion int64
ActorID pgtype.UUID
ManagerRoles []string
}
// Changes the profile of an organization over the version the caller read
// and advances the version in the same statement. It names no verification
// column, so a profile update cannot move the trust level. The change
// applies only for an account whose active membership has one of the
// manager roles, checked in the statement itself so that a membership that
// ended after the caller's read still stops the write. The statement locks
// the organization row first and then the actor's membership row FOR SHARE,
// so a revocation that commits while the statement waits is seen again
// (EvalPlanQual) and stops the write; the order organizations, then
// memberships, is the lock order of every writer (member management must
// follow it). No row returns for a stale version, an account that is no
// active manager, or an unknown organization; the adapter reads the
// membership to tell them apart.
func (q *Queries) UpdateOrganizationProfile(ctx context.Context, arg UpdateOrganizationProfileParams) (Organization, error) {
row := q.db.QueryRow(ctx, updateOrganizationProfile,
arg.Name,
arg.Description,
arg.Sphere,
arg.ContactWebsite,
arg.ContactEmail,
arg.ContactPhone,
arg.ContactTelegram,
arg.UpdatedAt,
arg.ID,
arg.ExpectedVersion,
arg.ActorID,
arg.ManagerRoles,
)
var i Organization
err := row.Scan(
&i.ID,
&i.Name,
&i.Description,
&i.Sphere,
&i.ContactWebsite,
&i.ContactEmail,
&i.ContactPhone,
&i.ContactTelegram,
&i.VerificationLevel,
&i.VerificationBasis,
&i.VerificationChangedAt,
&i.Version,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
@@ -49,6 +49,7 @@ type Querier interface {
// matches no row.
ConsumeEmailToken(ctx context.Context, arg ConsumeEmailTokenParams) (EmailToken, error)
DeleteMailRequest(ctx context.Context, id pgtype.UUID) (int64, error)
DeleteOrganizationRepresentatives(ctx context.Context, organizationID pgtype.UUID) error
// Deletes one batch of accounts that stayed unverified since before cutoff,
// oldest first, with their tokens, sessions, mail requests, mail deliveries
// (and through the deliveries their attempts), and consent records. The
@@ -112,6 +113,14 @@ type Querier interface {
GetLatestPolicyVersion(ctx context.Context, policyKey string) (PolicyVersion, error)
// Reads the usage of the day and the month window without locking.
GetMailQuotaUsage(ctx context.Context, arg GetMailQuotaUsageParams) ([]GetMailQuotaUsageRow, error)
// Reads the membership of one account in one organization, in any state.
GetMembership(ctx context.Context, arg GetMembershipParams) (Membership, error)
// Reads an organization together with the membership of one account in it
// and its representatives in list order, as one statement, so the profile and
// the list come from one snapshot. Only an active membership matches, so an
// unknown organization, an account that is no member, and a suspended,
// removed, or left member all return no row and cannot be told apart.
GetOrganizationForMember(ctx context.Context, arg GetOrganizationForMemberParams) (GetOrganizationForMemberRow, error)
// Reads the relay backlog for metrics without locking. Both subqueries use
// the partial index on unpublished positions, so the cost follows the backlog
// size, not the table size. The age comes from the database clock, the same
@@ -153,6 +162,16 @@ type Querier interface {
InsertEmailToken(ctx context.Context, arg InsertEmailTokenParams) error
InsertMailQuotaReservation(ctx context.Context, arg InsertMailQuotaReservationParams) error
InsertMailRequest(ctx context.Context, arg InsertMailRequestParams) error
InsertMembership(ctx context.Context, arg InsertMembershipParams) error
// Stores a new organization with the verification level that the domain
// gave it. The deferred constraint organizations_owner_required fails the
// transaction at commit unless an active owner membership was inserted in
// it too.
InsertOrganization(ctx context.Context, arg InsertOrganizationParams) error
// Stores one representative at its position in the list. The adapter calls it
// once per representative after it deleted the previous list, in the same
// transaction.
InsertOrganizationRepresentative(ctx context.Context, arg InsertOrganizationRepresentativeParams) error
InsertOutboxEvent(ctx context.Context, arg InsertOutboxEventParams) error
// Stores a version and returns the stored row with the publication time and
// effective time set by the stamp trigger. A taken ID or version number
@@ -189,6 +208,11 @@ type Querier interface {
ListConsentRecords(ctx context.Context, arg ListConsentRecordsParams) ([]ListConsentRecordsRow, error)
ListCurrentContactConsentRecords(ctx context.Context, arg ListCurrentContactConsentRecordsParams) ([]ListCurrentContactConsentRecordsRow, error)
ListDeliveryAttempts(ctx context.Context, deliveryID pgtype.UUID) ([]DeliveryAttempt, error)
// Lists the organizations where an account has an active membership,
// newest membership first. The page continues after the (membership
// creation time, organization ID) position of the last item of the
// previous page. Only the active memberships of the given account match.
ListOrganizationsForUser(ctx context.Context, arg ListOrganizationsForUserParams) ([]ListOrganizationsForUserRow, error)
// Lists the other accounts of a provider that have usage in a month, so
// startup can warn about a renamed EMAIL_ACCOUNT.
ListOtherMailQuotaAccounts(ctx context.Context, arg ListOtherMailQuotaAccountsParams) ([]string, error)
@@ -304,6 +328,20 @@ type Querier interface {
// the stored version still equals expected_version and returns 0 rows
// otherwise. The trigger refuses a provider change after an attempt.
UpdateDeliveryState(ctx context.Context, arg UpdateDeliveryStateParams) (int64, error)
// Changes the profile of an organization over the version the caller read
// and advances the version in the same statement. It names no verification
// column, so a profile update cannot move the trust level. The change
// applies only for an account whose active membership has one of the
// manager roles, checked in the statement itself so that a membership that
// ended after the caller's read still stops the write. The statement locks
// the organization row first and then the actor's membership row FOR SHARE,
// so a revocation that commits while the statement waits is seen again
// (EvalPlanQual) and stops the write; the order organizations, then
// memberships, is the lock order of every writer (member management must
// follow it). No row returns for a stale version, an account that is no
// active manager, or an unknown organization; the adapter reads the
// membership to tell them apart.
UpdateOrganizationProfile(ctx context.Context, arg UpdateOrganizationProfileParams) (Organization, error)
// Replaces the registration of an unverified account and advances the
// registration version in the same statement, so no caller can choose it.
// The version check rejects a writer that read an older row; a verified