feat(platform): add the notification inbox and deterministic match search

This commit is contained in:
shira committed 2026-10-09 13:14:46 +03:00
1 parent 5edff21d2d
commit 0b11021b16
169 files changed
+17083 -443

No files matched your search

@@ -0,0 +1,113 @@
// Package policypublish implements the local operator command that adds the
// demo matching section to the product policy. Until an administrative policy
// editor exists, this is how a stand gets the coefficients that the match
// search needs: startup seeds only the first demo version.
package policypublish
import (
"context"
"errors"
"flag"
"fmt"
"io"
"strings"
"time"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/policy"
)
const usage = "usage: policy-publish matching --actor operator:<handle>"
// Command is a parsed, validated request.
type Command struct {
Author domain.PolicyAuthor
}
// Extender publishes the demo matching section.
type Extender interface {
EnsureDemoMatchingSection(ctx context.Context, author domain.PolicyAuthor) (policy.MatchingResult, error)
}
// Parse validates every argument before Run reads configuration or connects.
func Parse(args []string) (Command, error) {
if len(args) == 0 || args[0] != "matching" {
return Command{}, errors.New(usage)
}
flags := flag.NewFlagSet("policy-publish matching", flag.ContinueOnError)
flags.SetOutput(io.Discard)
actor := flags.String("actor", "", "operator handle")
if err := flags.Parse(args[1:]); err != nil || flags.NArg() != 0 {
return Command{}, errors.New(usage)
}
value := strings.TrimSpace(*actor)
author, err := domain.ParsePolicyAuthor(value)
if err != nil || !strings.HasPrefix(value, "operator:") {
return Command{}, errors.New("actor must be operator:<handle>")
}
return Command{Author: author}, nil
}
// Run parses the command, loads only DATABASE_URL from the supplied
// environment, and publishes. It does not load dotenv files.
func Run(ctx context.Context, args []string, lookup config.LookupEnv, output io.Writer, clock func() time.Time) error {
command, err := Parse(args)
if err != nil {
return err
}
if lookup == nil || output == nil || clock == nil {
return errors.New("policy publication command dependencies are required")
}
databaseURL := config.DatabaseURLFromEnv(lookup)
if databaseURL == "" {
return errors.New("DATABASE_URL is not set")
}
pool, err := postgres.NewPool(ctx, databaseURL)
if err != nil {
return errors.New("database configuration is invalid")
}
defer pool.Close()
if err := pool.Ping(ctx); err != nil {
return errors.New("database is unavailable")
}
return Execute(ctx, command, policy.NewPublisher(postgres.NewPolicyStore(pool).Policies(), clock), output)
}
// Execute publishes the section and prints the version number only.
func Execute(ctx context.Context, command Command, extender Extender, output io.Writer) error {
if extender == nil || output == nil {
return errors.New("policy publication command dependencies are required")
}
result, err := extender.EnsureDemoMatchingSection(ctx, command.Author)
if err != nil {
return safeOperationError(err)
}
status := "already present"
if result.Created {
status = "published"
}
if _, err := fmt.Fprintf(output,
"%s: product policy version %d carries the demo matching section\n"+
"note: demonstration values, not calibrated; they apply to new searches at once and change no stored result\n",
status, result.Version.Version(),
); err != nil {
return errors.New("could not write the result")
}
return nil
}
func safeOperationError(err error) error {
switch {
case errors.Is(err, policy.ErrNotDemoPolicy):
return errors.New("the latest product policy is not a demonstration version; publish the matching section with the calibrated policy instead")
case errors.Is(err, policy.ErrPolicyChanged):
return errors.New("the product policy changed while publishing; run the command again")
case errors.Is(err, outbound.ErrPolicyVersionNotFound):
return errors.New("the product policy has no version yet; start the service once so that it seeds the demo policy")
default:
return errors.New("policy publication failed")
}
}
@@ -0,0 +1,64 @@
package policypublish
import (
"bytes"
"context"
"errors"
"strings"
"testing"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/policy"
)
type extenderFake struct {
result policy.MatchingResult
err error
author domain.PolicyAuthor
}
func (extender *extenderFake) EnsureDemoMatchingSection(_ context.Context, author domain.PolicyAuthor) (policy.MatchingResult, error) {
extender.author = author
return extender.result, extender.err
}
func TestParseRequiresTheMatchingTrackAndAnOperatorHandle(t *testing.T) {
command, err := Parse([]string{"matching", "--actor", "operator:night"})
if err != nil || command.Author != "operator:night" {
t.Fatalf("Parse(valid) = %+v, %v", command, err)
}
for _, args := range [][]string{
nil, {"list"}, {"matching"}, {"matching", "--actor", "alice"}, {"matching", "--actor", "system:demo-seed"},
{"matching", "--actor", "operator:night", "extra"},
} {
if _, err := Parse(args); err == nil {
t.Errorf("Parse(%v) accepted invalid arguments", args)
}
}
}
func TestExecutePrintsOnlyTheVersionAndMapsFailuresToSafeMessages(t *testing.T) {
var output bytes.Buffer
extender := &extenderFake{}
if err := Execute(context.Background(), Command{Author: "operator:night"}, extender, &output); err != nil {
t.Fatalf("Execute() error = %v", err)
}
if !strings.HasPrefix(output.String(), "already present: product policy version 0") || extender.author != "operator:night" {
t.Fatalf("output = %q, author %q", output.String(), extender.author)
}
for _, test := range []struct {
err error
want string
}{
{policy.ErrNotDemoPolicy, "not a demonstration version"},
{outbound.ErrPolicyVersionNotFound, "no version yet"},
{policy.ErrPolicyChanged, "run the command again"},
{errors.New("pq: password authentication failed for user x"), "policy publication failed"},
} {
err := Execute(context.Background(), Command{Author: "operator:night"}, &extenderFake{err: test.err}, &bytes.Buffer{})
if err == nil || !strings.Contains(err.Error(), test.want) || strings.Contains(err.Error(), "password") {
t.Errorf("Execute(%v) error = %v, want a safe message containing %q", test.err, err, test.want)
}
}
}
@@ -19,6 +19,7 @@ import (
var regexMap = map[string]ogenregex.Regexp{
"\\S": ogenregex.MustCompile("\\S"),
"^(/([^~/]|~[01])*)*$": ogenregex.MustCompile("^(/([^~/]|~[01])*)*$"),
"^/[A-Za-z0-9/_-]{0,255}$": ogenregex.MustCompile("^/[A-Za-z0-9/_-]{0,255}$"),
"^@[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}$"),
"^[0-9]{4}-(0[1-9]|1[0-2])$": ogenregex.MustCompile("^[0-9]{4}-(0[1-9]|1[0-2])$"),
@@ -9263,6 +9263,225 @@ func (s *Server) handleListMyInvitationsRequest(args [0]string, argsEscaped bool
}
}
// handleListMyNotificationsRequest handles ListMyNotifications operation.
//
// Requires the session cookie of a candidate account with a confirmed email. The recipient comes from
// the session, never from a request parameter, so the response holds only the caller's own items.
// Returns a page, newest delivery first with the identifier as the tie-breaker, with cursor
// pagination. The response is `Cache-Control: no-store`.
//
// The inbox is the in-platform delivery state of a notification. An item exists as soon as the event
// reached the platform, whether or not any email was sent, and an email that failed or was never sent
// does not block it. The inbox stores a reference to the event, not its text: the `content` of every
// item is resolved from the current source for this recipient on this read. When the source is gone or
// the recipient may not see it now (for example the candidate hid the organization), the item stays in
// the list with `content` null, and no earlier text is shown. An event that is delivered twice is one
// item.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer
// account answers 403 forbidden. A malformed `limit` or `cursor`, or a cursor of another account,
// answers 400 validation_failed.
//
// GET /api/v1/me/notifications
func (s *Server) handleListMyNotificationsRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("ListMyNotifications"),
semconv.HTTPRequestMethodKey.String("GET"),
semconv.HTTPRouteKey.String("/api/v1/me/notifications"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), ListMyNotificationsOperation,
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: ListMyNotificationsOperation,
ID: "ListMyNotifications",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, ListMyNotificationsOperation, 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 := decodeListMyNotificationsParams(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 ListMyNotificationsRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: ListMyNotificationsOperation,
OperationSummary: "List the inbox of the current candidate.",
OperationID: "ListMyNotifications",
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 = ListMyNotificationsParams
Response = ListMyNotificationsRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
unpackListMyNotificationsParams,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.ListMyNotifications(ctx, params)
return response, err
},
)
} else {
response, err = s.h.ListMyNotifications(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 := encodeListMyNotificationsResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleListMyOrganizationsRequest handles ListMyOrganizations operation.
//
// Requires the session cookie of an employer account. The account comes from the session, never from a
@@ -10366,6 +10585,229 @@ func (s *Server) handleListOrganizationNeedsRequest(args [1]string, argsEscaped
}
}
// handleListOrganizationNotificationsRequest handles ListOrganizationNotifications operation.
//
// Requires the session cookie of an employer account with a confirmed email and an active membership
// in `org_id`, whatever its role. The recipient comes from the session and the organization from the
// path and the membership that the server holds, never from the request. Returns only the items
// addressed to the caller in this organization, newest delivery first with the identifier as the
// tie-breaker, with cursor pagination. An item of the same account in another organization, and an
// item of another member, are never listed. The response is `Cache-Control: no-store`.
//
// Items follow the rules of ListMyNotifications: the inbox stores a reference to the event, an email
// never blocks an item, and the `content` of every item is resolved from the current source for this
// recipient on this read. An employer sees content only while the membership is active.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate
// account answers 403 forbidden, and an employer account with an unconfirmed email answers 403
// email_not_verified; an account without an active membership in the organization and an unknown
// organization both answer 404 not_found, so organizations cannot be enumerated. A malformed `org_id`,
// `limit`, or `cursor`, or a cursor of another account or organization, answers 400 validation_failed.
//
// GET /api/v1/organizations/{org_id}/notifications
func (s *Server) handleListOrganizationNotificationsRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("ListOrganizationNotifications"),
semconv.HTTPRequestMethodKey.String("GET"),
semconv.HTTPRouteKey.String("/api/v1/organizations/{org_id}/notifications"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), ListOrganizationNotificationsOperation,
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: ListOrganizationNotificationsOperation,
ID: "ListOrganizationNotifications",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, ListOrganizationNotificationsOperation, 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 := decodeListOrganizationNotificationsParams(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 ListOrganizationNotificationsRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: ListOrganizationNotificationsOperation,
OperationSummary: "List the inbox of the current employer in one organization.",
OperationID: "ListOrganizationNotifications",
Body: nil,
RawBody: rawBody,
Params: middleware.Parameters{
{
Name: "org_id",
In: "path",
}: params.OrgID,
{
Name: "limit",
In: "query",
}: params.Limit,
{
Name: "cursor",
In: "query",
}: params.Cursor,
},
Raw: r,
}
type (
Request = struct{}
Params = ListOrganizationNotificationsParams
Response = ListOrganizationNotificationsRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
unpackListOrganizationNotificationsParams,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.ListOrganizationNotifications(ctx, params)
return response, err
},
)
} else {
response, err = s.h.ListOrganizationNotifications(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 := encodeListOrganizationNotificationsResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleLoginRequest handles Login operation.
//
// Public operation that starts a server session. The server verifies the password with Argon2id; for
@@ -10745,6 +11187,477 @@ func (s *Server) handleLogoutRequest(args [0]string, argsEscaped bool, w http.Re
}
}
// handleMarkMyNotificationReadRequest handles MarkMyNotificationRead operation.
//
// Requires the session cookie of a candidate account with a confirmed email, the CSRF token of that
// session in X-CSRF-Token, and an allowed Origin. The recipient comes from the session. The request
// has no body.
//
// The command is idempotent by its effect: the first mark stores the read time and every repeat
// returns that first time, so it needs no Idempotency-Key. It never reads the source and returns no
// content, so marking an item whose content is no longer available still works. It changes no other
// item.
//
// The general rate limit can answer 429 with Retry-After before any check.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a missing or
// wrong CSRF token or a disallowed Origin answers 403 csrf_check_failed; an employer account answers
// 403 forbidden; an item of another account and an unknown identifier both answer 404 not_found, so
// identifiers cannot be enumerated. A `notification_id` that is not a UUID answers 400
// validation_failed with the path pointer.
//
// POST /api/v1/me/notifications/{notification_id}/read
func (s *Server) handleMarkMyNotificationReadRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("MarkMyNotificationRead"),
semconv.HTTPRequestMethodKey.String("POST"),
semconv.HTTPRouteKey.String("/api/v1/me/notifications/{notification_id}/read"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), MarkMyNotificationReadOperation,
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: MarkMyNotificationReadOperation,
ID: "MarkMyNotificationRead",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, MarkMyNotificationReadOperation, 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, MarkMyNotificationReadOperation, 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 := decodeMarkMyNotificationReadParams(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 MarkMyNotificationReadRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: MarkMyNotificationReadOperation,
OperationSummary: "Mark an item of the inbox of the current candidate as read.",
OperationID: "MarkMyNotificationRead",
Body: nil,
RawBody: rawBody,
Params: middleware.Parameters{
{
Name: "notification_id",
In: "path",
}: params.NotificationID,
},
Raw: r,
}
type (
Request = struct{}
Params = MarkMyNotificationReadParams
Response = MarkMyNotificationReadRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
unpackMarkMyNotificationReadParams,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.MarkMyNotificationRead(ctx, params)
return response, err
},
)
} else {
response, err = s.h.MarkMyNotificationRead(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 := encodeMarkMyNotificationReadResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleMarkOrganizationNotificationReadRequest handles MarkOrganizationNotificationRead operation.
//
// Requires the session cookie of an employer account with a confirmed email and an active membership
// in `org_id`, whatever its role, the CSRF token of that session in X-CSRF-Token, and an allowed
// Origin. The recipient comes from the session and the organization from the path and the server-side
// membership. The request has no body.
//
// The command is idempotent by its effect and returns no content, like MarkMyNotificationRead. The
// item must belong to the caller in this organization.
//
// The general rate limit can answer 429 with Retry-After before any check.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a missing or
// wrong CSRF token or a disallowed Origin answers 403 csrf_check_failed; a candidate account answers
// 403 forbidden, and an employer account with an unconfirmed email answers 403 email_not_verified; an
// account without an active membership in the organization, an unknown organization, an item of
// another account, an item of another organization, and an unknown identifier all answer 404
// not_found. A malformed `org_id` or `notification_id` answers 400 validation_failed with the path
// pointer.
//
// POST /api/v1/organizations/{org_id}/notifications/{notification_id}/read
func (s *Server) handleMarkOrganizationNotificationReadRequest(args [2]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
statusWriter := &codeRecorder{ResponseWriter: w}
w = statusWriter
otelAttrs := []attribute.KeyValue{
otelogen.OperationID("MarkOrganizationNotificationRead"),
semconv.HTTPRequestMethodKey.String("POST"),
semconv.HTTPRouteKey.String("/api/v1/organizations/{org_id}/notifications/{notification_id}/read"),
}
// Add attributes from config.
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
// Start a span for this request.
ctx, span := s.cfg.Tracer.Start(r.Context(), MarkOrganizationNotificationReadOperation,
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: MarkOrganizationNotificationReadOperation,
ID: "MarkOrganizationNotificationRead",
}
)
{
type bitset = [1]uint8
var satisfied bitset
{
sctx, ok, err := s.securitySessionCookie(ctx, MarkOrganizationNotificationReadOperation, 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, MarkOrganizationNotificationReadOperation, 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 := decodeMarkOrganizationNotificationReadParams(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 MarkOrganizationNotificationReadRes
if m := s.cfg.Middleware; m != nil {
mreq := middleware.Request{
Context: ctx,
OperationName: MarkOrganizationNotificationReadOperation,
OperationSummary: "Mark an item of the inbox of the current employer in one organization as read.",
OperationID: "MarkOrganizationNotificationRead",
Body: nil,
RawBody: rawBody,
Params: middleware.Parameters{
{
Name: "org_id",
In: "path",
}: params.OrgID,
{
Name: "notification_id",
In: "path",
}: params.NotificationID,
},
Raw: r,
}
type (
Request = struct{}
Params = MarkOrganizationNotificationReadParams
Response = MarkOrganizationNotificationReadRes
)
response, err = middleware.HookMiddleware[
Request,
Params,
Response,
](
m,
mreq,
unpackMarkOrganizationNotificationReadParams,
func(ctx context.Context, request Request, params Params) (response Response, err error) {
response, err = s.h.MarkOrganizationNotificationRead(ctx, params)
return response, err
},
)
} else {
response, err = s.h.MarkOrganizationNotificationRead(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 := encodeMarkOrganizationNotificationReadResponse(response, w, span); err != nil {
defer recordError("EncodeResponse", err)
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
s.cfg.ErrorHandler(ctx, w, r, err)
}
return
}
}
// handleRaiseOrganizationInvitationSalaryRequest handles RaiseOrganizationInvitationSalary operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
@@ -12840,6 +13753,15 @@ func (s *Server) handleSaveMyQuestionnaireRequest(args [0]string, argsEscaped bo
// empty bank filter searches all otherwise eligible specializations, returning each specialization
// separately.
//
// A search reveals card content, so it is charged like card reads. The whole visible bank is ranked,
// but each group returns at most the versioned per-group limit and no total is returned. In the order
// `main`, `near`, `unconfirmed`, each newly revealed candidate is counted as a distinct card view of
// the organization (a candidate it already viewed inside the window costs nothing again, so repeating
// the search or opening the card afterwards does not charge twice) and appears in the candidate's
// access history with the fields actually returned. When the allowance ends, the entries already
// counted are returned and `truncated` is true; the flag is also true when a group exceeded its limit,
// and it carries no count. No new error is returned for an exhausted allowance.
//
// Every entry is one candidate specialization. A confirmed result in Backend never confirms Networks
// for the same candidate. The `main`, `near`, and `unconfirmed` arrays are separate groups. A
// confirmed category with required-skill coverage below 0.25 belongs to `near`; other confirmed
@@ -12855,7 +13777,10 @@ func (s *Server) handleSaveMyQuestionnaireRequest(args [0]string, argsEscaped bo
// Evidence explanations use bounded codes, not free text. When ML is unavailable, semantic similarity
// uses the neutral 0.5 specified by FR09 and `unknown_flags` names `ml_unavailable`. For fewer than 30
// comparable real candidates, the search uses neutral T = 0.5, returns no percentile value, and names
// `cohort_below_30`.
// `cohort_below_30`. When the comparable real cohort of a category reaches the minimum, the percentile
// is still not computed (the organization-safe projection carries no theta), T stays the neutral 0.5,
// the percentile stays null, and `unknown_flags` names `percentile_not_computed`; the search does not
// fail.
//
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account
// answers 403 forbidden; an unknown organization or account without active membership answers 404
@@ -157,6 +157,10 @@ type ListMyInvitationsRes interface {
listMyInvitationsRes()
}
type ListMyNotificationsRes interface {
listMyNotificationsRes()
}
type ListMyOrganizationsRes interface {
listMyOrganizationsRes()
}
@@ -177,6 +181,10 @@ type ListOrganizationNeedsRes interface {
listOrganizationNeedsRes()
}
type ListOrganizationNotificationsRes interface {
listOrganizationNotificationsRes()
}
type LoginRes interface {
loginRes()
}
@@ -185,6 +193,14 @@ type LogoutRes interface {
logoutRes()
}
type MarkMyNotificationReadRes interface {
markMyNotificationReadRes()
}
type MarkOrganizationNotificationReadRes interface {
markOrganizationNotificationReadRes()
}
type RaiseOrganizationInvitationSalaryRes interface {
raiseOrganizationInvitationSalaryRes()
}
File diff suppressed because it is too large. Load diff
@@ -47,13 +47,17 @@ const (
ListMyEvidenceOperation OperationName = "ListMyEvidence"
ListMyHiddenOrganizationsOperation OperationName = "ListMyHiddenOrganizations"
ListMyInvitationsOperation OperationName = "ListMyInvitations"
ListMyNotificationsOperation OperationName = "ListMyNotifications"
ListMyOrganizationsOperation OperationName = "ListMyOrganizations"
ListMyPrivacyHistoryOperation OperationName = "ListMyPrivacyHistory"
ListMySupportCasesOperation OperationName = "ListMySupportCases"
ListOrganizationInvitationsOperation OperationName = "ListOrganizationInvitations"
ListOrganizationNeedsOperation OperationName = "ListOrganizationNeeds"
ListOrganizationNotificationsOperation OperationName = "ListOrganizationNotifications"
LoginOperation OperationName = "Login"
LogoutOperation OperationName = "Logout"
MarkMyNotificationReadOperation OperationName = "MarkMyNotificationRead"
MarkOrganizationNotificationReadOperation OperationName = "MarkOrganizationNotificationRead"
RaiseOrganizationInvitationSalaryOperation OperationName = "RaiseOrganizationInvitationSalary"
RecordMyAssessmentAttemptSignalsOperation OperationName = "RecordMyAssessmentAttemptSignals"
RegisterAccountOperation OperationName = "RegisterAccount"
@@ -3696,6 +3696,182 @@ func decodeListMyInvitationsParams(args [0]string, argsEscaped bool, r *http.Req
return params, nil
}
// ListMyNotificationsParams is parameters of ListMyNotifications operation.
type ListMyNotificationsParams 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 unpackListMyNotificationsParams(packed middleware.Parameters) (params ListMyNotificationsParams) {
{
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 decodeListMyNotificationsParams(args [0]string, argsEscaped bool, r *http.Request) (params ListMyNotificationsParams, _ 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
}
// 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
@@ -4690,6 +4866,432 @@ func decodeListOrganizationNeedsParams(args [1]string, argsEscaped bool, r *http
return params, nil
}
// ListOrganizationNotificationsParams is parameters of ListOrganizationNotifications operation.
type ListOrganizationNotificationsParams 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
// 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 unpackListOrganizationNotificationsParams(packed middleware.Parameters) (params ListOrganizationNotificationsParams) {
{
key := middleware.ParameterKey{
Name: "org_id",
In: "path",
}
params.OrgID = packed[key].(uuid.UUID)
}
{
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 decodeListOrganizationNotificationsParams(args [1]string, argsEscaped bool, r *http.Request) (params ListOrganizationNotificationsParams, _ error) {
q := uri.NewQueryDecoder(r.URL.Query())
// 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,
}
}
// 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
}
// MarkMyNotificationReadParams is parameters of MarkMyNotificationRead operation.
type MarkMyNotificationReadParams struct {
// Identifier of an item of the inbox of the current account in the cabinet that the path names. An
// item of another account, an item of another organization context, and an unknown identifier all
// answer 404 not_found, so identifiers cannot be enumerated.
NotificationID uuid.UUID
}
func unpackMarkMyNotificationReadParams(packed middleware.Parameters) (params MarkMyNotificationReadParams) {
{
key := middleware.ParameterKey{
Name: "notification_id",
In: "path",
}
params.NotificationID = packed[key].(uuid.UUID)
}
return params
}
func decodeMarkMyNotificationReadParams(args [1]string, argsEscaped bool, r *http.Request) (params MarkMyNotificationReadParams, _ error) {
// Decode path: notification_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: "notification_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.NotificationID = c
return nil
}(); err != nil {
return err
}
} else {
return validate.ErrFieldRequired
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "notification_id",
In: "path",
Err: err,
}
}
return params, nil
}
// MarkOrganizationNotificationReadParams is parameters of MarkOrganizationNotificationRead operation.
type MarkOrganizationNotificationReadParams 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
// Identifier of an item of the inbox of the current account in the cabinet that the path names. An
// item of another account, an item of another organization context, and an unknown identifier all
// answer 404 not_found, so identifiers cannot be enumerated.
NotificationID uuid.UUID
}
func unpackMarkOrganizationNotificationReadParams(packed middleware.Parameters) (params MarkOrganizationNotificationReadParams) {
{
key := middleware.ParameterKey{
Name: "org_id",
In: "path",
}
params.OrgID = packed[key].(uuid.UUID)
}
{
key := middleware.ParameterKey{
Name: "notification_id",
In: "path",
}
params.NotificationID = packed[key].(uuid.UUID)
}
return params
}
func decodeMarkOrganizationNotificationReadParams(args [2]string, argsEscaped bool, r *http.Request) (params MarkOrganizationNotificationReadParams, _ 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,
}
}
// Decode path: notification_id.
if err := func() error {
param := args[1]
if argsEscaped {
unescaped, err := url.PathUnescape(args[1])
if err != nil {
return errors.Wrap(err, "unescape path")
}
param = unescaped
}
if len(param) > 0 {
d := uri.NewPathDecoder(uri.PathDecoderConfig{
Param: "notification_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.NotificationID = c
return nil
}(); err != nil {
return err
}
} else {
return validate.ErrFieldRequired
}
return nil
}(); err != nil {
return params, &ogenerrors.DecodeParamError{
Name: "notification_id",
In: "path",
Err: err,
}
}
return params, nil
}
// RaiseOrganizationInvitationSalaryParams is parameters of RaiseOrganizationInvitationSalary operation.
type RaiseOrganizationInvitationSalaryParams struct {
// Identifier of an organization. Access comes only from an active membership of the session account in
@@ -3461,6 +3461,77 @@ func encodeListMyInvitationsResponse(response ListMyInvitationsRes, w http.Respo
}
}
func encodeListMyNotificationsResponse(response ListMyNotificationsRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *NotificationListHeaders:
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 *ListMyNotificationsBadRequest:
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 *ListMyNotificationsUnauthorized:
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 *ListMyNotificationsForbidden:
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 encodeListMyOrganizationsResponse(response ListMyOrganizationsRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *MyOrganizationListHeaders:
@@ -3828,6 +3899,89 @@ func encodeListOrganizationNeedsResponse(response ListOrganizationNeedsRes, w ht
}
}
func encodeListOrganizationNotificationsResponse(response ListOrganizationNotificationsRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *NotificationListHeaders:
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 *ListOrganizationNotificationsBadRequest:
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 *ListOrganizationNotificationsUnauthorized:
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 *ListOrganizationNotificationsForbidden:
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 *ListOrganizationNotificationsNotFound:
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 encodeLoginResponse(response LoginRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *SessionHeaders:
@@ -4014,6 +4168,236 @@ func encodeLogoutResponse(response LogoutRes, w http.ResponseWriter, span trace.
}
}
func encodeMarkMyNotificationReadResponse(response MarkMyNotificationReadRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *NotificationReadReceiptHeaders:
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 *MarkMyNotificationReadBadRequest:
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 *MarkMyNotificationReadUnauthorized:
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 *MarkMyNotificationReadForbidden:
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 *MarkMyNotificationReadNotFound:
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 *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 encodeMarkOrganizationNotificationReadResponse(response MarkOrganizationNotificationReadRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *NotificationReadReceiptHeaders:
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 *MarkOrganizationNotificationReadBadRequest:
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 *MarkOrganizationNotificationReadUnauthorized:
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 *MarkOrganizationNotificationReadForbidden:
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 *MarkOrganizationNotificationReadNotFound:
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 *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 encodeRaiseOrganizationInvitationSalaryResponse(response RaiseOrganizationInvitationSalaryRes, w http.ResponseWriter, span trace.Span) error {
switch response := response.(type) {
case *OrganizationInvitationHeaders:
@@ -11,43 +11,43 @@ import (
)
var (
rn74AllowedHeaders = map[string]string{
rn83AllowedHeaders = map[string]string{
"POST": "Content-Type",
}
rn9AllowedHeaders = map[string]string{
"POST": "Content-Type,Origin",
}
rn70AllowedHeaders = map[string]string{
rn79AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key",
}
rn66AllowedHeaders = map[string]string{
rn69AllowedHeaders = map[string]string{
"POST": "Content-Type",
}
rn27AllowedHeaders = map[string]string{
"DELETE": "X-Csrf-Token",
}
rn72AllowedHeaders = map[string]string{
rn81AllowedHeaders = map[string]string{
"POST": "X-Csrf-Token",
}
rn11AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn85AllowedHeaders = map[string]string{
rn94AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn22AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn84AllowedHeaders = map[string]string{
rn93AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn69AllowedHeaders = map[string]string{
rn78AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn5AllowedHeaders = map[string]string{
"PUT": "Content-Type,X-Csrf-Token",
}
rn76AllowedHeaders = map[string]string{
rn85AllowedHeaders = map[string]string{
"DELETE": "X-Csrf-Token",
}
rn53AllowedHeaders = map[string]string{
@@ -63,17 +63,20 @@ var (
rn19AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn86AllowedHeaders = map[string]string{
rn95AllowedHeaders = map[string]string{
"POST": "X-Csrf-Token",
}
rn72AllowedHeaders = map[string]string{
"POST": "X-Csrf-Token",
}
rn56AllowedHeaders = map[string]string{
"DELETE": "X-Csrf-Token",
"PUT": "X-Csrf-Token",
}
rn81AllowedHeaders = map[string]string{
rn90AllowedHeaders = map[string]string{
"PUT": "Content-Type,X-Csrf-Token",
}
rn82AllowedHeaders = map[string]string{
rn91AllowedHeaders = map[string]string{
"PUT": "Content-Type,X-Csrf-Token",
}
rn38AllowedHeaders = map[string]string{
@@ -97,16 +100,16 @@ var (
rn46AllowedHeaders = map[string]string{
"PATCH": "Content-Type,X-Csrf-Token",
}
rn68AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn79AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn87AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn77AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn88AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn96AllowedHeaders = map[string]string{
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
}
rn86AllowedHeaders = map[string]string{
"POST": "Content-Type,X-Csrf-Token",
}
rn18AllowedHeaders = map[string]string{
@@ -115,6 +118,9 @@ var (
rn49AllowedHeaders = map[string]string{
"PATCH": "Content-Type,X-Csrf-Token",
}
rn75AllowedHeaders = map[string]string{
"POST": "X-Csrf-Token",
}
)
func (s *Server) cutPrefix(path string) (string, bool) {
@@ -269,7 +275,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn74AllowedHeaders,
allowedHeaders: rn83AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -346,7 +352,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn70AllowedHeaders,
allowedHeaders: rn79AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -370,7 +376,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn66AllowedHeaders,
allowedHeaders: rn69AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -450,7 +456,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn72AllowedHeaders,
allowedHeaders: rn81AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -572,7 +578,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn85AllowedHeaders,
allowedHeaders: rn94AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -665,7 +671,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn84AllowedHeaders,
allowedHeaders: rn93AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -692,7 +698,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn69AllowedHeaders,
allowedHeaders: rn78AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -903,7 +909,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "DELETE",
allowedHeaders: rn76AllowedHeaders,
allowedHeaders: rn85AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1145,7 +1151,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn86AllowedHeaders,
allowedHeaders: rn95AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1160,6 +1166,82 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
case 'n': // Prefix: "notifications"
if l := len("notifications"); len(elem) >= l && elem[0:l] == "notifications" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
switch r.Method {
case "GET":
s.handleListMyNotificationsRequest([0]string{}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET",
allowedHeaders: nil,
acceptPost: "",
acceptPatch: "",
})
}
return
}
switch elem[0] {
case '/': // Prefix: "/"
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
elem = elem[l:]
} else {
break
}
// Param: "notification_id"
// Match until "/"
idx := strings.IndexByte(elem, '/')
if idx < 0 {
idx = len(elem)
}
args[0] = elem[:idx]
elem = elem[idx:]
if len(elem) == 0 {
break
}
switch elem[0] {
case '/': // Prefix: "/read"
if l := len("/read"); len(elem) >= l && elem[0:l] == "/read" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "POST":
s.handleMarkMyNotificationReadRequest([1]string{
args[0],
}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn72AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
}
return
}
}
}
case 'o': // Prefix: "organizations"
if l := len("organizations"); len(elem) >= l && elem[0:l] == "organizations" {
@@ -1416,7 +1498,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "PUT",
allowedHeaders: rn81AllowedHeaders,
allowedHeaders: rn90AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1443,7 +1525,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "PUT",
allowedHeaders: rn82AllowedHeaders,
allowedHeaders: rn91AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
@@ -1861,7 +1943,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn68AllowedHeaders,
allowedHeaders: rn77AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -1889,7 +1971,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn79AllowedHeaders,
allowedHeaders: rn88AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -1919,7 +2001,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn87AllowedHeaders,
allowedHeaders: rn96AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -1952,7 +2034,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn77AllowedHeaders,
allowedHeaders: rn86AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
@@ -1961,77 +2043,170 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
case 'n': // Prefix: "needs"
case 'n': // Prefix: "n"
if l := len("needs"); len(elem) >= l && elem[0:l] == "needs" {
if l := len("n"); len(elem) >= l && elem[0:l] == "n" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
switch r.Method {
case "GET":
s.handleListOrganizationNeedsRequest([1]string{
args[0],
}, elemIsEscaped, w, r)
case "POST":
s.handleCreateOrganizationNeedRequest([1]string{
args[0],
}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET,POST",
allowedHeaders: rn18AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
}
return
break
}
switch elem[0] {
case '/': // Prefix: "/"
case 'e': // Prefix: "eeds"
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
if l := len("eeds"); len(elem) >= l && elem[0:l] == "eeds" {
elem = elem[l:]
} else {
break
}
// Param: "need_id"
// Leaf parameter, slashes are prohibited
idx := strings.IndexByte(elem, '/')
if idx >= 0 {
break
}
args[1] = elem
elem = ""
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "GET":
s.handleGetOrganizationNeedRequest([2]string{
s.handleListOrganizationNeedsRequest([1]string{
args[0],
args[1],
}, elemIsEscaped, w, r)
case "PATCH":
s.handleUpdateOrganizationNeedRequest([2]string{
case "POST":
s.handleCreateOrganizationNeedRequest([1]string{
args[0],
args[1],
}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET,PATCH",
allowedHeaders: rn49AllowedHeaders,
acceptPost: "",
acceptPatch: "application/json",
allowedMethods: "GET,POST",
allowedHeaders: rn18AllowedHeaders,
acceptPost: "application/json",
acceptPatch: "",
})
}
return
}
switch elem[0] {
case '/': // Prefix: "/"
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
elem = elem[l:]
} else {
break
}
// Param: "need_id"
// Leaf parameter, slashes are prohibited
idx := strings.IndexByte(elem, '/')
if idx >= 0 {
break
}
args[1] = elem
elem = ""
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "GET":
s.handleGetOrganizationNeedRequest([2]string{
args[0],
args[1],
}, elemIsEscaped, w, r)
case "PATCH":
s.handleUpdateOrganizationNeedRequest([2]string{
args[0],
args[1],
}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET,PATCH",
allowedHeaders: rn49AllowedHeaders,
acceptPost: "",
acceptPatch: "application/json",
})
}
return
}
}
case 'o': // Prefix: "otifications"
if l := len("otifications"); len(elem) >= l && elem[0:l] == "otifications" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
switch r.Method {
case "GET":
s.handleListOrganizationNotificationsRequest([1]string{
args[0],
}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "GET",
allowedHeaders: nil,
acceptPost: "",
acceptPatch: "",
})
}
return
}
switch elem[0] {
case '/': // Prefix: "/"
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
elem = elem[l:]
} else {
break
}
// Param: "notification_id"
// Match until "/"
idx := strings.IndexByte(elem, '/')
if idx < 0 {
idx = len(elem)
}
args[1] = elem[:idx]
elem = elem[idx:]
if len(elem) == 0 {
break
}
switch elem[0] {
case '/': // Prefix: "/read"
if l := len("/read"); len(elem) >= l && elem[0:l] == "/read" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch r.Method {
case "POST":
s.handleMarkOrganizationNotificationReadRequest([2]string{
args[0],
args[1],
}, elemIsEscaped, w, r)
default:
s.notAllowed(w, r, notAllowedParams{
allowedMethods: "POST",
allowedHeaders: rn75AllowedHeaders,
acceptPost: "",
acceptPatch: "",
})
}
return
}
}
}
}
@@ -3147,6 +3322,80 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
}
case 'n': // Prefix: "notifications"
if l := len("notifications"); len(elem) >= l && elem[0:l] == "notifications" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
switch method {
case "GET":
r.name = ListMyNotificationsOperation
r.summary = "List the inbox of the current candidate."
r.operationID = "ListMyNotifications"
r.operationGroup = ""
r.pathPattern = "/api/v1/me/notifications"
r.args = args
r.count = 0
return r, true
default:
return
}
}
switch elem[0] {
case '/': // Prefix: "/"
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
elem = elem[l:]
} else {
break
}
// Param: "notification_id"
// Match until "/"
idx := strings.IndexByte(elem, '/')
if idx < 0 {
idx = len(elem)
}
args[0] = elem[:idx]
elem = elem[idx:]
if len(elem) == 0 {
break
}
switch elem[0] {
case '/': // Prefix: "/read"
if l := len("/read"); len(elem) >= l && elem[0:l] == "/read" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch method {
case "POST":
r.name = MarkMyNotificationReadOperation
r.summary = "Mark an item of the inbox of the current candidate as read."
r.operationID = "MarkMyNotificationRead"
r.operationGroup = ""
r.pathPattern = "/api/v1/me/notifications/{notification_id}/read"
r.args = args
r.count = 1
return r, true
default:
return
}
}
}
}
case 'o': // Prefix: "organizations"
if l := len("organizations"); len(elem) >= l && elem[0:l] == "organizations" {
@@ -3957,81 +4206,169 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
}
}
case 'n': // Prefix: "needs"
case 'n': // Prefix: "n"
if l := len("needs"); len(elem) >= l && elem[0:l] == "needs" {
if l := len("n"); len(elem) >= l && elem[0:l] == "n" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
switch method {
case "GET":
r.name = ListOrganizationNeedsOperation
r.summary = "List the needs of an organization."
r.operationID = "ListOrganizationNeeds"
r.operationGroup = ""
r.pathPattern = "/api/v1/organizations/{org_id}/needs"
r.args = args
r.count = 1
return r, true
case "POST":
r.name = CreateOrganizationNeedOperation
r.summary = "Create a need of an organization from a form, a text, or both."
r.operationID = "CreateOrganizationNeed"
r.operationGroup = ""
r.pathPattern = "/api/v1/organizations/{org_id}/needs"
r.args = args
r.count = 1
return r, true
default:
return
}
break
}
switch elem[0] {
case '/': // Prefix: "/"
case 'e': // Prefix: "eeds"
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
if l := len("eeds"); len(elem) >= l && elem[0:l] == "eeds" {
elem = elem[l:]
} else {
break
}
// Param: "need_id"
// Leaf parameter, slashes are prohibited
idx := strings.IndexByte(elem, '/')
if idx >= 0 {
break
}
args[1] = elem
elem = ""
if len(elem) == 0 {
// Leaf node.
switch method {
case "GET":
r.name = GetOrganizationNeedOperation
r.summary = "Read the current version of a need of an organization."
r.operationID = "GetOrganizationNeed"
r.name = ListOrganizationNeedsOperation
r.summary = "List the needs of an organization."
r.operationID = "ListOrganizationNeeds"
r.operationGroup = ""
r.pathPattern = "/api/v1/organizations/{org_id}/needs/{need_id}"
r.pathPattern = "/api/v1/organizations/{org_id}/needs"
r.args = args
r.count = 2
r.count = 1
return r, true
case "PATCH":
r.name = UpdateOrganizationNeedOperation
r.summary = "Confirm, change, or delete requirements of a need."
r.operationID = "UpdateOrganizationNeed"
case "POST":
r.name = CreateOrganizationNeedOperation
r.summary = "Create a need of an organization from a form, a text, or both."
r.operationID = "CreateOrganizationNeed"
r.operationGroup = ""
r.pathPattern = "/api/v1/organizations/{org_id}/needs/{need_id}"
r.pathPattern = "/api/v1/organizations/{org_id}/needs"
r.args = args
r.count = 2
r.count = 1
return r, true
default:
return
}
}
switch elem[0] {
case '/': // Prefix: "/"
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
elem = elem[l:]
} else {
break
}
// Param: "need_id"
// Leaf parameter, slashes are prohibited
idx := strings.IndexByte(elem, '/')
if idx >= 0 {
break
}
args[1] = elem
elem = ""
if len(elem) == 0 {
// Leaf node.
switch method {
case "GET":
r.name = GetOrganizationNeedOperation
r.summary = "Read the current version of a need of an organization."
r.operationID = "GetOrganizationNeed"
r.operationGroup = ""
r.pathPattern = "/api/v1/organizations/{org_id}/needs/{need_id}"
r.args = args
r.count = 2
return r, true
case "PATCH":
r.name = UpdateOrganizationNeedOperation
r.summary = "Confirm, change, or delete requirements of a need."
r.operationID = "UpdateOrganizationNeed"
r.operationGroup = ""
r.pathPattern = "/api/v1/organizations/{org_id}/needs/{need_id}"
r.args = args
r.count = 2
return r, true
default:
return
}
}
}
case 'o': // Prefix: "otifications"
if l := len("otifications"); len(elem) >= l && elem[0:l] == "otifications" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
switch method {
case "GET":
r.name = ListOrganizationNotificationsOperation
r.summary = "List the inbox of the current employer in one organization."
r.operationID = "ListOrganizationNotifications"
r.operationGroup = ""
r.pathPattern = "/api/v1/organizations/{org_id}/notifications"
r.args = args
r.count = 1
return r, true
default:
return
}
}
switch elem[0] {
case '/': // Prefix: "/"
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
elem = elem[l:]
} else {
break
}
// Param: "notification_id"
// Match until "/"
idx := strings.IndexByte(elem, '/')
if idx < 0 {
idx = len(elem)
}
args[1] = elem[:idx]
elem = elem[idx:]
if len(elem) == 0 {
break
}
switch elem[0] {
case '/': // Prefix: "/read"
if l := len("/read"); len(elem) >= l && elem[0:l] == "/read" {
elem = elem[l:]
} else {
break
}
if len(elem) == 0 {
// Leaf node.
switch method {
case "POST":
r.name = MarkOrganizationNotificationReadOperation
r.summary = "Mark an item of the inbox of the current employer in one organization as read."
r.operationID = "MarkOrganizationNotificationRead"
r.operationGroup = ""
r.pathPattern = "/api/v1/organizations/{org_id}/notifications/{notification_id}/read"
r.args = args
r.count = 2
return r, true
default:
return
}
}
}
}
}
@@ -12625,6 +12625,18 @@ type ListMyInvitationsUnauthorized Problem
func (*ListMyInvitationsUnauthorized) listMyInvitationsRes() {}
type ListMyNotificationsBadRequest Problem
func (*ListMyNotificationsBadRequest) listMyNotificationsRes() {}
type ListMyNotificationsForbidden Problem
func (*ListMyNotificationsForbidden) listMyNotificationsRes() {}
type ListMyNotificationsUnauthorized Problem
func (*ListMyNotificationsUnauthorized) listMyNotificationsRes() {}
type ListMyOrganizationsBadRequest Problem
func (*ListMyOrganizationsBadRequest) listMyOrganizationsRes() {}
@@ -12689,6 +12701,22 @@ type ListOrganizationNeedsUnauthorized Problem
func (*ListOrganizationNeedsUnauthorized) listOrganizationNeedsRes() {}
type ListOrganizationNotificationsBadRequest Problem
func (*ListOrganizationNotificationsBadRequest) listOrganizationNotificationsRes() {}
type ListOrganizationNotificationsForbidden Problem
func (*ListOrganizationNotificationsForbidden) listOrganizationNotificationsRes() {}
type ListOrganizationNotificationsNotFound Problem
func (*ListOrganizationNotificationsNotFound) listOrganizationNotificationsRes() {}
type ListOrganizationNotificationsUnauthorized Problem
func (*ListOrganizationNotificationsUnauthorized) listOrganizationNotificationsRes() {}
type LoginBadRequest Problem
func (*LoginBadRequest) loginRes() {}
@@ -12747,6 +12775,38 @@ func (s *LogoutNoContent) SetSetCookie(val string) {
func (*LogoutNoContent) logoutRes() {}
type MarkMyNotificationReadBadRequest Problem
func (*MarkMyNotificationReadBadRequest) markMyNotificationReadRes() {}
type MarkMyNotificationReadForbidden Problem
func (*MarkMyNotificationReadForbidden) markMyNotificationReadRes() {}
type MarkMyNotificationReadNotFound Problem
func (*MarkMyNotificationReadNotFound) markMyNotificationReadRes() {}
type MarkMyNotificationReadUnauthorized Problem
func (*MarkMyNotificationReadUnauthorized) markMyNotificationReadRes() {}
type MarkOrganizationNotificationReadBadRequest Problem
func (*MarkOrganizationNotificationReadBadRequest) markOrganizationNotificationReadRes() {}
type MarkOrganizationNotificationReadForbidden Problem
func (*MarkOrganizationNotificationReadForbidden) markOrganizationNotificationReadRes() {}
type MarkOrganizationNotificationReadNotFound Problem
func (*MarkOrganizationNotificationReadNotFound) markOrganizationNotificationReadRes() {}
type MarkOrganizationNotificationReadUnauthorized Problem
func (*MarkOrganizationNotificationReadUnauthorized) markOrganizationNotificationReadRes() {}
// Conditions echoed as a complete snapshot; null means no filter.
// Ref: #/components/schemas/MatchAppliedConditions
type MatchAppliedConditions struct {
@@ -13864,6 +13924,11 @@ func NewMatchSearchByBankMatchSearchRequest(v MatchSearchByBank) MatchSearchRequ
type MatchSearchResponse struct {
Source MatchSearchSource `json:"source"`
Groups MatchSearchGroups `json:"groups"`
// True when the groups are not the whole ranked result: a group exceeded the versioned per-group
// limit, or the organization's card-view allowance ended while the entries were being revealed. The
// entries returned are in rank order and already counted as card views. It carries no total, so it
// does not reveal how many candidates match.
Truncated bool `json:"truncated"`
}
// GetSource returns the value of Source.
@@ -13876,6 +13941,11 @@ func (s *MatchSearchResponse) GetGroups() MatchSearchGroups {
return s.Groups
}
// GetTruncated returns the value of Truncated.
func (s *MatchSearchResponse) GetTruncated() bool {
return s.Truncated
}
// SetSource sets the value of Source.
func (s *MatchSearchResponse) SetSource(val MatchSearchSource) {
s.Source = val
@@ -13886,6 +13956,11 @@ func (s *MatchSearchResponse) SetGroups(val MatchSearchGroups) {
s.Groups = val
}
// SetTruncated sets the value of Truncated.
func (s *MatchSearchResponse) SetTruncated(val bool) {
s.Truncated = val
}
// MatchSearchResponseHeaders wraps MatchSearchResponse with response headers.
type MatchSearchResponseHeaders struct {
CacheControl CacheControlNoStore
@@ -14392,7 +14467,10 @@ func (s *MatchUnknownFlag) SetReason(val MatchUnknownReason) {
type MatchUnknownFlags []MatchUnknownFlag
// Bounded explanation for an unknown component, not a hiding reason.
// Bounded explanation for an unknown component, not a hiding reason. `cohort_below_30` is reported
// only while the comparable real cohort of the category is smaller than the versioned minimum; once
// the cohort reaches the minimum but the percentile is still not computed, the reason is
// `percentile_not_computed`. In both cases T is the neutral 0.5.
// Ref: #/components/schemas/MatchUnknownReason
type MatchUnknownReason string
@@ -14404,6 +14482,7 @@ const (
MatchUnknownReasonNeedFieldUnconfirmed MatchUnknownReason = "need_field_unconfirmed"
MatchUnknownReasonNoFreshnessHistory MatchUnknownReason = "no_freshness_history"
MatchUnknownReasonNoResponseHistory MatchUnknownReason = "no_response_history"
MatchUnknownReasonPercentileNotComputed MatchUnknownReason = "percentile_not_computed"
)
// AllValues returns all MatchUnknownReason values.
@@ -14416,6 +14495,7 @@ func (MatchUnknownReason) AllValues() []MatchUnknownReason {
MatchUnknownReasonNeedFieldUnconfirmed,
MatchUnknownReasonNoFreshnessHistory,
MatchUnknownReasonNoResponseHistory,
MatchUnknownReasonPercentileNotComputed,
}
}
@@ -14436,6 +14516,8 @@ func (s MatchUnknownReason) MarshalText() ([]byte, error) {
return []byte(s), nil
case MatchUnknownReasonNoResponseHistory:
return []byte(s), nil
case MatchUnknownReasonPercentileNotComputed:
return []byte(s), nil
default:
return nil, errors.Errorf("invalid value: %q", s)
}
@@ -14465,6 +14547,9 @@ func (s *MatchUnknownReason) UnmarshalText(data []byte) error {
case MatchUnknownReasonNoResponseHistory:
*s = MatchUnknownReasonNoResponseHistory
return nil
case MatchUnknownReasonPercentileNotComputed:
*s = MatchUnknownReasonPercentileNotComputed
return nil
default:
return errors.Errorf("invalid value: %q", data)
}
@@ -18830,6 +18915,51 @@ func (o NilNeedVersionLabel) Or(d NeedVersionLabel) NeedVersionLabel {
return d
}
// NewNilNotificationContent returns new NilNotificationContent with value set to v.
func NewNilNotificationContent(v NotificationContent) NilNotificationContent {
return NilNotificationContent{
Value: v,
}
}
// NilNotificationContent is nullable NotificationContent.
type NilNotificationContent struct {
Value NotificationContent
Null bool
}
// SetTo sets value to v.
func (o *NilNotificationContent) SetTo(v NotificationContent) {
o.Null = false
o.Value = v
}
// IsNull returns true if value is Null.
func (o NilNotificationContent) IsNull() bool { return o.Null }
// SetToNull sets value to null.
func (o *NilNotificationContent) SetToNull() {
o.Null = true
var v NotificationContent
o.Value = v
}
// Get returns value and boolean that denotes whether value was set.
func (o NilNotificationContent) Get() (v NotificationContent, ok bool) {
if o.Null {
return v, false
}
return o.Value, true
}
// Or returns value if set, or given parameter if does not.
func (o NilNotificationContent) Or(d NotificationContent) NotificationContent {
if v, ok := o.Get(); ok {
return v
}
return d
}
// NewNilOrganizationDescription returns new NilOrganizationDescription with value set to v.
func NewNilOrganizationDescription(v OrganizationDescription) NilOrganizationDescription {
return NilOrganizationDescription{
@@ -20495,6 +20625,301 @@ func (o NilWorkContext) Or(d WorkContext) WorkContext {
return d
}
// One item of the inbox of the current account. Its identity, kind, organization, delivery time, and
// read state are stored; its content is resolved from the current source on every read.
// Ref: #/components/schemas/Notification
type Notification struct {
// Identifier of the item. It equals the identifier of the event that produced it, so a repeated
// delivery of the same event is the same item.
ID uuid.UUID `json:"id"`
Kind NotificationKind `json:"kind"`
// The organization context of the item: the organization that sent it to a candidate, or the
// organization whose cabinet holds it for an employer. The identifier is not a right to read the
// organization.
OrganizationID uuid.UUID `json:"organization_id"`
DeliveredAt Timestamp `json:"delivered_at"`
// When the recipient first marked the item read, or null while it is unread. A repeated mark keeps the
// first time.
ReadAt NilTimestamp `json:"read_at"`
// The current content, or null when the source is gone or the recipient may not see it now. A client
// then shows a generic line such as "The content is no longer available" and never an old copy. The
// item stays in the list and can be marked read.
Content NilNotificationContent `json:"content"`
}
// GetID returns the value of ID.
func (s *Notification) GetID() uuid.UUID {
return s.ID
}
// GetKind returns the value of Kind.
func (s *Notification) GetKind() NotificationKind {
return s.Kind
}
// GetOrganizationID returns the value of OrganizationID.
func (s *Notification) GetOrganizationID() uuid.UUID {
return s.OrganizationID
}
// GetDeliveredAt returns the value of DeliveredAt.
func (s *Notification) GetDeliveredAt() Timestamp {
return s.DeliveredAt
}
// GetReadAt returns the value of ReadAt.
func (s *Notification) GetReadAt() NilTimestamp {
return s.ReadAt
}
// GetContent returns the value of Content.
func (s *Notification) GetContent() NilNotificationContent {
return s.Content
}
// SetID sets the value of ID.
func (s *Notification) SetID(val uuid.UUID) {
s.ID = val
}
// SetKind sets the value of Kind.
func (s *Notification) SetKind(val NotificationKind) {
s.Kind = val
}
// SetOrganizationID sets the value of OrganizationID.
func (s *Notification) SetOrganizationID(val uuid.UUID) {
s.OrganizationID = val
}
// SetDeliveredAt sets the value of DeliveredAt.
func (s *Notification) SetDeliveredAt(val Timestamp) {
s.DeliveredAt = val
}
// SetReadAt sets the value of ReadAt.
func (s *Notification) SetReadAt(val NilTimestamp) {
s.ReadAt = val
}
// SetContent sets the value of Content.
func (s *Notification) SetContent(val NilNotificationContent) {
s.Content = val
}
// The text of a notification as the current source shows it to the recipient now. It is computed on
// every read and never stored, so a hiding, a revoked membership, or a withdrawn source removes it
// from the next read. It holds no contact, no score, and no result of an assessment.
// Ref: #/components/schemas/NotificationContent
type NotificationContent struct {
// Short heading in Russian.
Title string `json:"title"`
// One or two sentences in Russian. Plain text, never markup.
Summary string `json:"summary"`
// Same-origin absolute path of the screen that the notification opens, or null when there is none. It
// has no origin, query, fragment, or escape; a client opens it only as a path of its own router.
LinkPath NilString `json:"link_path"`
}
// GetTitle returns the value of Title.
func (s *NotificationContent) GetTitle() string {
return s.Title
}
// GetSummary returns the value of Summary.
func (s *NotificationContent) GetSummary() string {
return s.Summary
}
// GetLinkPath returns the value of LinkPath.
func (s *NotificationContent) GetLinkPath() NilString {
return s.LinkPath
}
// SetTitle sets the value of Title.
func (s *NotificationContent) SetTitle(val string) {
s.Title = val
}
// SetSummary sets the value of Summary.
func (s *NotificationContent) SetSummary(val string) {
s.Summary = val
}
// SetLinkPath sets the value of LinkPath.
func (s *NotificationContent) SetLinkPath(val NilString) {
s.LinkPath = val
}
// Which event put the notification into the inbox. The inbox stores a reference to the event, never
// its text.
//
// - invitation_delivered: an invitation reached the candidate's inbox. This is the in-platform
// delivery state of the invitation: it does not depend on any email, and a failed or missing email
// never blocks it. The invitation operations are planned; no invitation produces a notification
// yet.
// - synthetic: a synthetic notice that exercises the inbox path (the event, the read-time visibility
// check, the list, and the read state). It has no product meaning, needs no action, and is never
// produced by a user action.
//
// Adding a value is a contract change; a client shows an unknown kind with the generic text of an item
// without content.
// Ref: #/components/schemas/NotificationKind
type NotificationKind string
const (
NotificationKindInvitationDelivered NotificationKind = "invitation_delivered"
NotificationKindSynthetic NotificationKind = "synthetic"
)
// AllValues returns all NotificationKind values.
func (NotificationKind) AllValues() []NotificationKind {
return []NotificationKind{
NotificationKindInvitationDelivered,
NotificationKindSynthetic,
}
}
// MarshalText implements encoding.TextMarshaler.
func (s NotificationKind) MarshalText() ([]byte, error) {
switch s {
case NotificationKindInvitationDelivered:
return []byte(s), nil
case NotificationKindSynthetic:
return []byte(s), nil
default:
return nil, errors.Errorf("invalid value: %q", s)
}
}
// UnmarshalText implements encoding.TextUnmarshaler.
func (s *NotificationKind) UnmarshalText(data []byte) error {
switch NotificationKind(data) {
case NotificationKindInvitationDelivered:
*s = NotificationKindInvitationDelivered
return nil
case NotificationKindSynthetic:
*s = NotificationKindSynthetic
return nil
default:
return errors.Errorf("invalid value: %q", data)
}
}
// One page of the inbox, newest delivery first.
// Ref: #/components/schemas/NotificationList
type NotificationList struct {
// Items of the page.
Items []Notification `json:"items"`
Page PageInfo `json:"page"`
}
// GetItems returns the value of Items.
func (s *NotificationList) GetItems() []Notification {
return s.Items
}
// GetPage returns the value of Page.
func (s *NotificationList) GetPage() PageInfo {
return s.Page
}
// SetItems sets the value of Items.
func (s *NotificationList) SetItems(val []Notification) {
s.Items = val
}
// SetPage sets the value of Page.
func (s *NotificationList) SetPage(val PageInfo) {
s.Page = val
}
// NotificationListHeaders wraps NotificationList with response headers.
type NotificationListHeaders struct {
CacheControl CacheControlNoStore
Response NotificationList
}
// GetCacheControl returns the value of CacheControl.
func (s *NotificationListHeaders) GetCacheControl() CacheControlNoStore {
return s.CacheControl
}
// GetResponse returns the value of Response.
func (s *NotificationListHeaders) GetResponse() NotificationList {
return s.Response
}
// SetCacheControl sets the value of CacheControl.
func (s *NotificationListHeaders) SetCacheControl(val CacheControlNoStore) {
s.CacheControl = val
}
// SetResponse sets the value of Response.
func (s *NotificationListHeaders) SetResponse(val NotificationList) {
s.Response = val
}
func (*NotificationListHeaders) listMyNotificationsRes() {}
func (*NotificationListHeaders) listOrganizationNotificationsRes() {}
// The read state of one item after a mark. It carries no content, so marking never reads the source.
// Ref: #/components/schemas/NotificationReadReceipt
type NotificationReadReceipt struct {
// Identifier of the marked item.
ID uuid.UUID `json:"id"`
ReadAt Timestamp `json:"read_at"`
}
// GetID returns the value of ID.
func (s *NotificationReadReceipt) GetID() uuid.UUID {
return s.ID
}
// GetReadAt returns the value of ReadAt.
func (s *NotificationReadReceipt) GetReadAt() Timestamp {
return s.ReadAt
}
// SetID sets the value of ID.
func (s *NotificationReadReceipt) SetID(val uuid.UUID) {
s.ID = val
}
// SetReadAt sets the value of ReadAt.
func (s *NotificationReadReceipt) SetReadAt(val Timestamp) {
s.ReadAt = val
}
// NotificationReadReceiptHeaders wraps NotificationReadReceipt with response headers.
type NotificationReadReceiptHeaders struct {
CacheControl CacheControlNoStore
Response NotificationReadReceipt
}
// GetCacheControl returns the value of CacheControl.
func (s *NotificationReadReceiptHeaders) GetCacheControl() CacheControlNoStore {
return s.CacheControl
}
// GetResponse returns the value of Response.
func (s *NotificationReadReceiptHeaders) GetResponse() NotificationReadReceipt {
return s.Response
}
// SetCacheControl sets the value of CacheControl.
func (s *NotificationReadReceiptHeaders) SetCacheControl(val CacheControlNoStore) {
s.CacheControl = val
}
// SetResponse sets the value of Response.
func (s *NotificationReadReceiptHeaders) SetResponse(val NotificationReadReceipt) {
s.Response = val
}
func (*NotificationReadReceiptHeaders) markMyNotificationReadRes() {}
func (*NotificationReadReceiptHeaders) markOrganizationNotificationReadRes() {}
// Numeric answer in the unit of the item. Two answers are equal when their decoded values are
// numerically equal, so 254 and 254.0 are the same answer.
// Ref: #/components/schemas/NumberAnswer
@@ -30507,6 +30932,8 @@ func (*TooManyRequestsHeaders) getOrganizationCandidateCardRes() {}
func (*TooManyRequestsHeaders) getOrganizationCandidateEvidenceRes() {}
func (*TooManyRequestsHeaders) hideOrganizationRes() {}
func (*TooManyRequestsHeaders) loginRes() {}
func (*TooManyRequestsHeaders) markMyNotificationReadRes() {}
func (*TooManyRequestsHeaders) markOrganizationNotificationReadRes() {}
func (*TooManyRequestsHeaders) raiseOrganizationInvitationSalaryRes() {}
func (*TooManyRequestsHeaders) recordMyAssessmentAttemptSignalsRes() {}
func (*TooManyRequestsHeaders) registerAccountRes() {}
@@ -93,12 +93,16 @@ var operationRolesSessionCookie = map[string][]string{
ListMyEvidenceOperation: []string{},
ListMyHiddenOrganizationsOperation: []string{},
ListMyInvitationsOperation: []string{},
ListMyNotificationsOperation: []string{},
ListMyOrganizationsOperation: []string{},
ListMyPrivacyHistoryOperation: []string{},
ListMySupportCasesOperation: []string{},
ListOrganizationInvitationsOperation: []string{},
ListOrganizationNeedsOperation: []string{},
ListOrganizationNotificationsOperation: []string{},
LogoutOperation: []string{},
MarkMyNotificationReadOperation: []string{},
MarkOrganizationNotificationReadOperation: []string{},
RaiseOrganizationInvitationSalaryOperation: []string{},
RecordMyAssessmentAttemptSignalsOperation: []string{},
RequestMyAccountDeletionOperation: []string{},
@@ -156,6 +160,8 @@ var operationRolesSessionCsrf = map[string][]string{
GrantMyConsentOperation: []string{},
HideOrganizationOperation: []string{},
LogoutOperation: []string{},
MarkMyNotificationReadOperation: []string{},
MarkOrganizationNotificationReadOperation: []string{},
RaiseOrganizationInvitationSalaryOperation: []string{},
RecordMyAssessmentAttemptSignalsOperation: []string{},
RequestMyAccountDeletionOperation: []string{},
@@ -1173,6 +1173,27 @@ type Handler interface {
//
// GET /api/v1/me/invitations
ListMyInvitations(ctx context.Context, params ListMyInvitationsParams) (ListMyInvitationsRes, error)
// ListMyNotifications implements ListMyNotifications operation.
//
// Requires the session cookie of a candidate account with a confirmed email. The recipient comes from
// the session, never from a request parameter, so the response holds only the caller's own items.
// Returns a page, newest delivery first with the identifier as the tie-breaker, with cursor
// pagination. The response is `Cache-Control: no-store`.
//
// The inbox is the in-platform delivery state of a notification. An item exists as soon as the event
// reached the platform, whether or not any email was sent, and an email that failed or was never sent
// does not block it. The inbox stores a reference to the event, not its text: the `content` of every
// item is resolved from the current source for this recipient on this read. When the source is gone or
// the recipient may not see it now (for example the candidate hid the organization), the item stays in
// the list with `content` null, and no earlier text is shown. An event that is delivered twice is one
// item.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer
// account answers 403 forbidden. A malformed `limit` or `cursor`, or a cursor of another account,
// answers 400 validation_failed.
//
// GET /api/v1/me/notifications
ListMyNotifications(ctx context.Context, params ListMyNotificationsParams) (ListMyNotificationsRes, error)
// ListMyOrganizations implements ListMyOrganizations operation.
//
// Requires the session cookie of an employer account. The account comes from the session, never from a
@@ -1278,6 +1299,27 @@ type Handler interface {
//
// GET /api/v1/organizations/{org_id}/needs
ListOrganizationNeeds(ctx context.Context, params ListOrganizationNeedsParams) (ListOrganizationNeedsRes, error)
// ListOrganizationNotifications implements ListOrganizationNotifications operation.
//
// Requires the session cookie of an employer account with a confirmed email and an active membership
// in `org_id`, whatever its role. The recipient comes from the session and the organization from the
// path and the membership that the server holds, never from the request. Returns only the items
// addressed to the caller in this organization, newest delivery first with the identifier as the
// tie-breaker, with cursor pagination. An item of the same account in another organization, and an
// item of another member, are never listed. The response is `Cache-Control: no-store`.
//
// Items follow the rules of ListMyNotifications: the inbox stores a reference to the event, an email
// never blocks an item, and the `content` of every item is resolved from the current source for this
// recipient on this read. An employer sees content only while the membership is active.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate
// account answers 403 forbidden, and an employer account with an unconfirmed email answers 403
// email_not_verified; an account without an active membership in the organization and an unknown
// organization both answer 404 not_found, so organizations cannot be enumerated. A malformed `org_id`,
// `limit`, or `cursor`, or a cursor of another account or organization, answers 400 validation_failed.
//
// GET /api/v1/organizations/{org_id}/notifications
ListOrganizationNotifications(ctx context.Context, params ListOrganizationNotificationsParams) (ListOrganizationNotificationsRes, error)
// Login implements Login operation.
//
// Public operation that starts a server session. The server verifies the password with Argon2id; for
@@ -1312,6 +1354,49 @@ type Handler interface {
//
// DELETE /api/v1/identity/sessions/current
Logout(ctx context.Context) (LogoutRes, error)
// MarkMyNotificationRead implements MarkMyNotificationRead operation.
//
// Requires the session cookie of a candidate account with a confirmed email, the CSRF token of that
// session in X-CSRF-Token, and an allowed Origin. The recipient comes from the session. The request
// has no body.
//
// The command is idempotent by its effect: the first mark stores the read time and every repeat
// returns that first time, so it needs no Idempotency-Key. It never reads the source and returns no
// content, so marking an item whose content is no longer available still works. It changes no other
// item.
//
// The general rate limit can answer 429 with Retry-After before any check.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a missing or
// wrong CSRF token or a disallowed Origin answers 403 csrf_check_failed; an employer account answers
// 403 forbidden; an item of another account and an unknown identifier both answer 404 not_found, so
// identifiers cannot be enumerated. A `notification_id` that is not a UUID answers 400
// validation_failed with the path pointer.
//
// POST /api/v1/me/notifications/{notification_id}/read
MarkMyNotificationRead(ctx context.Context, params MarkMyNotificationReadParams) (MarkMyNotificationReadRes, error)
// MarkOrganizationNotificationRead implements MarkOrganizationNotificationRead operation.
//
// Requires the session cookie of an employer account with a confirmed email and an active membership
// in `org_id`, whatever its role, the CSRF token of that session in X-CSRF-Token, and an allowed
// Origin. The recipient comes from the session and the organization from the path and the server-side
// membership. The request has no body.
//
// The command is idempotent by its effect and returns no content, like MarkMyNotificationRead. The
// item must belong to the caller in this organization.
//
// The general rate limit can answer 429 with Retry-After before any check.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a missing or
// wrong CSRF token or a disallowed Origin answers 403 csrf_check_failed; a candidate account answers
// 403 forbidden, and an employer account with an unconfirmed email answers 403 email_not_verified; an
// account without an active membership in the organization, an unknown organization, an item of
// another account, an item of another organization, and an unknown identifier all answer 404
// not_found. A malformed `org_id` or `notification_id` answers 400 validation_failed with the path
// pointer.
//
// POST /api/v1/organizations/{org_id}/notifications/{notification_id}/read
MarkOrganizationNotificationRead(ctx context.Context, params MarkOrganizationNotificationReadParams) (MarkOrganizationNotificationReadRes, error)
// RaiseOrganizationInvitationSalary implements RaiseOrganizationInvitationSalary operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
@@ -1585,6 +1670,15 @@ type Handler interface {
// empty bank filter searches all otherwise eligible specializations, returning each specialization
// separately.
//
// A search reveals card content, so it is charged like card reads. The whole visible bank is ranked,
// but each group returns at most the versioned per-group limit and no total is returned. In the order
// `main`, `near`, `unconfirmed`, each newly revealed candidate is counted as a distinct card view of
// the organization (a candidate it already viewed inside the window costs nothing again, so repeating
// the search or opening the card afterwards does not charge twice) and appears in the candidate's
// access history with the fields actually returned. When the allowance ends, the entries already
// counted are returned and `truncated` is true; the flag is also true when a group exceeded its limit,
// and it carries no count. No new error is returned for an exhausted allowance.
//
// Every entry is one candidate specialization. A confirmed result in Backend never confirms Networks
// for the same candidate. The `main`, `near`, and `unconfirmed` arrays are separate groups. A
// confirmed category with required-skill coverage below 0.25 belongs to `near`; other confirmed
@@ -1600,7 +1694,10 @@ type Handler interface {
// Evidence explanations use bounded codes, not free text. When ML is unavailable, semantic similarity
// uses the neutral 0.5 specified by FR09 and `unknown_flags` names `ml_unavailable`. For fewer than 30
// comparable real candidates, the search uses neutral T = 0.5, returns no percentile value, and names
// `cohort_below_30`.
// `cohort_below_30`. When the comparable real cohort of a category reaches the minimum, the percentile
// is still not computed (the organization-safe projection carries no theta), T stays the neutral 0.5,
// the percentile stays null, and `unknown_flags` names `percentile_not_computed`; the search does not
// fail.
//
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account
// answers 403 forbidden; an unknown organization or account without active membership answers 404
@@ -1301,6 +1301,30 @@ func (UnimplementedHandler) ListMyInvitations(ctx context.Context, params ListMy
return r, ht.ErrNotImplemented
}
// ListMyNotifications implements ListMyNotifications operation.
//
// Requires the session cookie of a candidate account with a confirmed email. The recipient comes from
// the session, never from a request parameter, so the response holds only the caller's own items.
// Returns a page, newest delivery first with the identifier as the tie-breaker, with cursor
// pagination. The response is `Cache-Control: no-store`.
//
// The inbox is the in-platform delivery state of a notification. An item exists as soon as the event
// reached the platform, whether or not any email was sent, and an email that failed or was never sent
// does not block it. The inbox stores a reference to the event, not its text: the `content` of every
// item is resolved from the current source for this recipient on this read. When the source is gone or
// the recipient may not see it now (for example the candidate hid the organization), the item stays in
// the list with `content` null, and no earlier text is shown. An event that is delivered twice is one
// item.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer
// account answers 403 forbidden. A malformed `limit` or `cursor`, or a cursor of another account,
// answers 400 validation_failed.
//
// GET /api/v1/me/notifications
func (UnimplementedHandler) ListMyNotifications(ctx context.Context, params ListMyNotificationsParams) (r ListMyNotificationsRes, _ error) {
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
@@ -1421,6 +1445,30 @@ func (UnimplementedHandler) ListOrganizationNeeds(ctx context.Context, params Li
return r, ht.ErrNotImplemented
}
// ListOrganizationNotifications implements ListOrganizationNotifications operation.
//
// Requires the session cookie of an employer account with a confirmed email and an active membership
// in `org_id`, whatever its role. The recipient comes from the session and the organization from the
// path and the membership that the server holds, never from the request. Returns only the items
// addressed to the caller in this organization, newest delivery first with the identifier as the
// tie-breaker, with cursor pagination. An item of the same account in another organization, and an
// item of another member, are never listed. The response is `Cache-Control: no-store`.
//
// Items follow the rules of ListMyNotifications: the inbox stores a reference to the event, an email
// never blocks an item, and the `content` of every item is resolved from the current source for this
// recipient on this read. An employer sees content only while the membership is active.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate
// account answers 403 forbidden, and an employer account with an unconfirmed email answers 403
// email_not_verified; an account without an active membership in the organization and an unknown
// organization both answer 404 not_found, so organizations cannot be enumerated. A malformed `org_id`,
// `limit`, or `cursor`, or a cursor of another account or organization, answers 400 validation_failed.
//
// GET /api/v1/organizations/{org_id}/notifications
func (UnimplementedHandler) ListOrganizationNotifications(ctx context.Context, params ListOrganizationNotificationsParams) (r ListOrganizationNotificationsRes, _ error) {
return r, ht.ErrNotImplemented
}
// Login implements Login operation.
//
// Public operation that starts a server session. The server verifies the password with Argon2id; for
@@ -1461,6 +1509,55 @@ func (UnimplementedHandler) Logout(ctx context.Context) (r LogoutRes, _ error) {
return r, ht.ErrNotImplemented
}
// MarkMyNotificationRead implements MarkMyNotificationRead operation.
//
// Requires the session cookie of a candidate account with a confirmed email, the CSRF token of that
// session in X-CSRF-Token, and an allowed Origin. The recipient comes from the session. The request
// has no body.
//
// The command is idempotent by its effect: the first mark stores the read time and every repeat
// returns that first time, so it needs no Idempotency-Key. It never reads the source and returns no
// content, so marking an item whose content is no longer available still works. It changes no other
// item.
//
// The general rate limit can answer 429 with Retry-After before any check.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a missing or
// wrong CSRF token or a disallowed Origin answers 403 csrf_check_failed; an employer account answers
// 403 forbidden; an item of another account and an unknown identifier both answer 404 not_found, so
// identifiers cannot be enumerated. A `notification_id` that is not a UUID answers 400
// validation_failed with the path pointer.
//
// POST /api/v1/me/notifications/{notification_id}/read
func (UnimplementedHandler) MarkMyNotificationRead(ctx context.Context, params MarkMyNotificationReadParams) (r MarkMyNotificationReadRes, _ error) {
return r, ht.ErrNotImplemented
}
// MarkOrganizationNotificationRead implements MarkOrganizationNotificationRead operation.
//
// Requires the session cookie of an employer account with a confirmed email and an active membership
// in `org_id`, whatever its role, the CSRF token of that session in X-CSRF-Token, and an allowed
// Origin. The recipient comes from the session and the organization from the path and the server-side
// membership. The request has no body.
//
// The command is idempotent by its effect and returns no content, like MarkMyNotificationRead. The
// item must belong to the caller in this organization.
//
// The general rate limit can answer 429 with Retry-After before any check.
//
// Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a missing or
// wrong CSRF token or a disallowed Origin answers 403 csrf_check_failed; a candidate account answers
// 403 forbidden, and an employer account with an unconfirmed email answers 403 email_not_verified; an
// account without an active membership in the organization, an unknown organization, an item of
// another account, an item of another organization, and an unknown identifier all answer 404
// not_found. A malformed `org_id` or `notification_id` answers 400 validation_failed with the path
// pointer.
//
// POST /api/v1/organizations/{org_id}/notifications/{notification_id}/read
func (UnimplementedHandler) MarkOrganizationNotificationRead(ctx context.Context, params MarkOrganizationNotificationReadParams) (r MarkOrganizationNotificationReadRes, _ error) {
return r, ht.ErrNotImplemented
}
// RaiseOrganizationInvitationSalary implements RaiseOrganizationInvitationSalary operation.
//
// Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF
@@ -1761,6 +1858,15 @@ func (UnimplementedHandler) SaveMyQuestionnaire(ctx context.Context, req *Candid
// empty bank filter searches all otherwise eligible specializations, returning each specialization
// separately.
//
// A search reveals card content, so it is charged like card reads. The whole visible bank is ranked,
// but each group returns at most the versioned per-group limit and no total is returned. In the order
// `main`, `near`, `unconfirmed`, each newly revealed candidate is counted as a distinct card view of
// the organization (a candidate it already viewed inside the window costs nothing again, so repeating
// the search or opening the card afterwards does not charge twice) and appears in the candidate's
// access history with the fields actually returned. When the allowance ends, the entries already
// counted are returned and `truncated` is true; the flag is also true when a group exceeded its limit,
// and it carries no count. No new error is returned for an exhausted allowance.
//
// Every entry is one candidate specialization. A confirmed result in Backend never confirms Networks
// for the same candidate. The `main`, `near`, and `unconfirmed` arrays are separate groups. A
// confirmed category with required-skill coverage below 0.25 belongs to `near`; other confirmed
@@ -1776,7 +1882,10 @@ func (UnimplementedHandler) SaveMyQuestionnaire(ctx context.Context, req *Candid
// Evidence explanations use bounded codes, not free text. When ML is unavailable, semantic similarity
// uses the neutral 0.5 specified by FR09 and `unknown_flags` names `ml_unavailable`. For fewer than 30
// comparable real candidates, the search uses neutral T = 0.5, returns no percentile value, and names
// `cohort_below_30`.
// `cohort_below_30`. When the comparable real cohort of a category reaches the minimum, the percentile
// is still not computed (the organization-safe projection carries no theta), T stays the neutral 0.5,
// the percentile stays null, and `unknown_flags` names `percentile_not_computed`; the search does not
// fail.
//
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account
// answers 403 forbidden; an unknown organization or account without active membership answers 404
@@ -11427,6 +11427,30 @@ func (s *ListMyInvitationsUnauthorized) Validate() error {
return nil
}
func (s *ListMyNotificationsBadRequest) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *ListMyNotificationsForbidden) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *ListMyNotificationsUnauthorized) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *ListMyOrganizationsBadRequest) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
@@ -11555,6 +11579,38 @@ func (s *ListOrganizationNeedsUnauthorized) Validate() error {
return nil
}
func (s *ListOrganizationNotificationsBadRequest) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *ListOrganizationNotificationsForbidden) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *ListOrganizationNotificationsNotFound) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *ListOrganizationNotificationsUnauthorized) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *LoginBadRequest) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
@@ -11668,6 +11724,70 @@ func (s *LogoutNoContent) Validate() error {
return nil
}
func (s *MarkMyNotificationReadBadRequest) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *MarkMyNotificationReadForbidden) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *MarkMyNotificationReadNotFound) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *MarkMyNotificationReadUnauthorized) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *MarkOrganizationNotificationReadBadRequest) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *MarkOrganizationNotificationReadForbidden) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *MarkOrganizationNotificationReadNotFound) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *MarkOrganizationNotificationReadUnauthorized) Validate() error {
alias := (*Problem)(s)
if err := alias.Validate(); err != nil {
return err
}
return nil
}
func (s *MatchAppliedConditions) Validate() error {
if s == nil {
return validate.ErrNilPointer
@@ -13378,6 +13498,8 @@ func (s MatchUnknownReason) Validate() error {
return nil
case "no_response_history":
return nil
case "percentile_not_computed":
return nil
default:
return errors.Errorf("invalid value: %v", s)
}
@@ -16179,6 +16301,262 @@ func (s NewPassword) Validate() error {
return nil
}
func (s *Notification) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.Kind.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "kind",
Error: err,
})
}
if err := func() error {
if value, ok := s.Content.Get(); ok {
if err := func() error {
if err := value.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
return err
}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "content",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s *NotificationContent) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := (validate.String{
MinLength: 1,
MinLengthSet: true,
MaxLength: 120,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: nil,
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(s.Title)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "title",
Error: err,
})
}
if err := func() error {
if err := (validate.String{
MinLength: 1,
MinLengthSet: true,
MaxLength: 500,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: nil,
MinNumeric: 0,
MinNumericSet: false,
MaxNumeric: 0,
MaxNumericSet: false,
}).Validate(string(s.Summary)); err != nil {
return errors.Wrap(err, "string")
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "summary",
Error: err,
})
}
if err := func() error {
if value, ok := s.LinkPath.Get(); ok {
if err := func() error {
if err := (validate.String{
MinLength: 0,
MinLengthSet: false,
MaxLength: 256,
MaxLengthSet: true,
Email: false,
Hostname: false,
Regex: regexMap["^/[A-Za-z0-9/_-]{0,255}$"],
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 {
failures = append(failures, validate.FieldError{
Name: "link_path",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s NotificationKind) Validate() error {
switch s {
case "invitation_delivered":
return nil
case "synthetic":
return nil
default:
return errors.Errorf("invalid value: %v", s)
}
}
func (s *NotificationList) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if s.Items == nil {
return errors.New("nil is invalid value")
}
if err := (validate.Array{
MinLength: 0,
MinLengthSet: false,
MaxLength: 100,
MaxLengthSet: true,
}).ValidateLength(len(s.Items)); err != nil {
return errors.Wrap(err, "array")
}
var failures []validate.FieldError
for i, elem := range s.Items {
if err := func() error {
if err := elem.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: fmt.Sprintf("[%d]", i),
Error: err,
})
}
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "items",
Error: err,
})
}
if err := func() error {
if err := s.Page.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "page",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s *NotificationListHeaders) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.CacheControl.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "CacheControl",
Error: err,
})
}
if err := func() error {
if err := s.Response.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "Response",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s *NotificationReadReceiptHeaders) Validate() error {
if s == nil {
return validate.ErrNilPointer
}
var failures []validate.FieldError
if err := func() error {
if err := s.CacheControl.Validate(); err != nil {
return err
}
return nil
}(); err != nil {
failures = append(failures, validate.FieldError{
Name: "CacheControl",
Error: err,
})
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}
func (s *NumberAnswer) Validate() error {
if s == nil {
return validate.ErrNilPointer
@@ -36,9 +36,9 @@ var ownerCompanyOperations = map[apiadapter.OperationName]struct{}{
apiadapter.GetOrganizationInvitationContactsOperation: {},
apiadapter.WithdrawOrganizationInvitationOperation: {},
apiadapter.RaiseOrganizationInvitationSalaryOperation: {},
// The match search contract requires an active owner membership. The
// operation has no handler yet; classifying it here keeps it closed to
// every other role when the handler arrives.
// The match search requires an active owner membership: the minimal
// milestone grants a membership by itself no tenant right, and the usecase
// repeats the owner check inside its transaction.
apiadapter.SearchOrganizationMatchesOperation: {},
}
@@ -53,6 +53,9 @@ func TestCompanyContextMiddlewareFailsClosedAndExcludesOtherScopes(t *testing.T)
// the owner-only capability does not apply to that operation.
apiadapter.GetOrganizationCandidateCardOperation,
apiadapter.GetOrganizationCandidateEvidenceOperation,
// The inbox runs the membership check in the read transaction for any role.
apiadapter.ListOrganizationNotificationsOperation,
apiadapter.MarkOrganizationNotificationReadOperation,
apiadapter.HideOrganizationOperation,
apiadapter.UnhideOrganizationOperation,
apiadapter.RevokeMyOrganizationContactConsentOperation,
@@ -111,6 +114,13 @@ func TestCompanyContextMiddlewareMapsMembershipFailuresToPublicProblems(t *testi
}
}
// organizationNotificationPaths are the inbox operations of one organization,
// which check the membership inside their own transaction.
var organizationNotificationPaths = map[string]string{
"ListOrganizationNotifications": "/api/v1/organizations/{org_id}/notifications",
"MarkOrganizationNotificationRead": "/api/v1/organizations/{org_id}/notifications/{notification_id}/read",
}
func TestCompanyContextOperationInventoryMatchesOpenAPI(t *testing.T) {
const bundlePath = "../../../../../api/core/openapi.bundle.yml"
data, err := os.ReadFile(bundlePath)
@@ -137,6 +147,7 @@ func TestCompanyContextOperationInventoryMatchesOpenAPI(t *testing.T) {
seenExceptions := make(map[string]bool, len(candidateExceptions))
seenCardRead := false
seenEvidenceRead := false
seenNotifications := map[string]bool{}
for path, methods := range document.Paths {
for _, operation := range methods {
if operation.OperationID == "" {
@@ -170,6 +181,13 @@ func TestCompanyContextOperationInventoryMatchesOpenAPI(t *testing.T) {
seenEvidenceRead = true
continue
}
// The inbox of one organization authorizes any active membership and
// the recipient together with the read, inside the read transaction;
// the owner-only capability does not apply.
if notificationPath, ok := organizationNotificationPaths[operation.OperationID]; ok && notificationPath == path {
seenNotifications[operation.OperationID] = true
continue
}
expectedPath, candidateOperation := candidateExceptions[operation.OperationID]
if candidateOperation && expectedPath == path && strings.HasPrefix(path, "/api/v1/me/") {
seenExceptions[operation.OperationID] = true
@@ -194,6 +212,11 @@ func TestCompanyContextOperationInventoryMatchesOpenAPI(t *testing.T) {
if !seenEvidenceRead {
t.Error("transaction-authorized candidate evidence read is absent or moved")
}
for operation := range organizationNotificationPaths {
if !seenNotifications[operation] {
t.Errorf("transaction-authorized inbox operation %s is absent or moved", operation)
}
}
}
type companyContextAuthenticator struct {
@@ -0,0 +1,127 @@
package httpadapter
import (
"slices"
"testing"
"github.com/ogen-go/ogen"
"lincodex/backend/internal/adapter/primary/http/api"
)
// The four inbox operations follow the project conventions: the session
// cookie for a read, the session and the CSRF token for a mark, no-store on
// every success, the shared cursor parameters, the anti-enumeration 404 on
// everything keyed by an identifier, and no new problem code.
func TestNotificationOperationsFollowTheConventions(t *testing.T) {
spec := parsePublicContract(t)
for _, test := range []struct {
id string
path string
reads bool
parameters []string
statuses []string
absent []string
}{
{id: "ListMyNotifications", path: "/api/v1/me/notifications", reads: true,
parameters: []string{"PageLimit", "PageCursor"}, statuses: []string{"400", "401", "403"}, absent: []string{"404"}},
{id: "ListOrganizationNotifications", path: "/api/v1/organizations/{org_id}/notifications", reads: true,
parameters: []string{"OrganizationId", "PageLimit", "PageCursor"}, statuses: []string{"400", "401", "403", "404"}},
{id: "MarkMyNotificationRead", path: "/api/v1/me/notifications/{notification_id}/read",
parameters: []string{"NotificationId"}, statuses: []string{"400", "401", "403", "404", "429"}},
{id: "MarkOrganizationNotificationRead", path: "/api/v1/organizations/{org_id}/notifications/{notification_id}/read",
parameters: []string{"OrganizationId", "NotificationId"}, statuses: []string{"400", "401", "403", "404", "429"}},
} {
t.Run(test.id, func(t *testing.T) {
operation := operationByID(t, spec, test.id)
if spec.Paths[test.path] == nil {
t.Fatalf("the contract has no path %s", test.path)
}
if !slices.Contains(operation.Tags, "notification") {
t.Errorf("%s is not in the notification tag", test.id)
}
if !hasSecurity(operation, "sessionCookie") || hasSecurity(operation, "sessionCsrf") == test.reads {
t.Errorf("%s security = %v, want the session cookie and a CSRF token only for a mark", test.id, operation.Security)
}
for _, status := range append(test.statuses, "default") {
if operation.Responses[status] == nil {
t.Errorf("%s does not declare %s", test.id, status)
}
}
for _, status := range test.absent {
if operation.Responses[status] != nil {
t.Errorf("%s declares %s", test.id, status)
}
}
if success := operation.Responses["200"]; success == nil || success.Headers["Cache-Control"] == nil {
t.Errorf("%s does not mark its 200 response no-store", test.id)
}
if operation.RequestBody != nil {
t.Errorf("%s takes a body: the item and the recipient come from the path and the session", test.id)
}
names := make([]string, 0, len(operation.Parameters))
for _, parameter := range operation.Parameters {
names = append(names, parameterName(parameter))
}
if !slices.Equal(names, test.parameters) {
t.Errorf("%s parameters = %v, want %v", test.id, names, test.parameters)
}
})
}
// An idempotent command by its effect needs no key.
for _, id := range []string{"MarkMyNotificationRead", "MarkOrganizationNotificationRead"} {
for _, parameter := range operationByID(t, spec, id).Parameters {
if parameterName(parameter) == "IdempotencyKey" || parameterName(parameter) == "IfMatch" {
t.Errorf("%s declares %s", id, parameterName(parameter))
}
}
}
codes := enumValues(t, resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/ProblemCode"}))
for _, code := range []string{"validation_failed", "unauthenticated", "forbidden", "csrf_check_failed", "not_found", "rate_limited"} {
if !slices.Contains(codes, code) {
t.Errorf("ProblemCode has no %s", code)
}
}
}
// Every inbox object is closed and fully required, an item carries a
// reference and a state but no text of its own, and the text sits in the one
// nullable content object.
func TestNotificationSchemasAreClosedAndKeepTextInTheContent(t *testing.T) {
spec := parsePublicContract(t)
for _, pair := range []struct {
name string
want []string
}{
{"Notification", []string{"content", "delivered_at", "id", "kind", "organization_id", "read_at"}},
{"NotificationContent", []string{"link_path", "summary", "title"}},
{"NotificationList", []string{"items", "page"}},
{"NotificationReadReceipt", []string{"id", "read_at"}},
} {
schema := spec.Components.Schemas[pair.name]
if schema == nil {
t.Fatalf("the contract has no schema %s", pair.name)
}
if got := propertyNames(schema); !slices.Equal(got, pair.want) {
t.Errorf("%s properties = %v, want %v", pair.name, got, pair.want)
}
if schema.AdditionalProperties.Bool == nil || *schema.AdditionalProperties.Bool {
t.Errorf("%s accepts unknown properties", pair.name)
}
if required := slices.Sorted(slices.Values(schema.Required)); !slices.Equal(required, pair.want) {
t.Errorf("%s requires %v, want every property %v", pair.name, required, pair.want)
}
}
if got := enumValues(t, spec.Components.Schemas["NotificationKind"]); !slices.Equal(got, []string{"invitation_delivered", "synthetic"}) {
t.Errorf("NotificationKind = %v", got)
}
assertNoJSONFields(t, api.Notification{}, []string{
"title", "summary", "body", "text", "email", "name", "contact", "contacts", "recipient_user_id", "user_id", "candidate_id",
})
assertNoJSONFields(t, api.NotificationReadReceipt{}, []string{"content", "title", "summary", "kind", "organization_id"})
for _, property := range spec.Components.Schemas["NotificationList"].Properties {
if property.Name == "items" && (property.Schema.MaxItems == nil || *property.Schema.MaxItems != 100) {
t.Errorf("NotificationList.items maxItems = %v, want the page limit 100", property.Schema.MaxItems)
}
}
}
@@ -30,6 +30,8 @@ type Handler struct {
assessmentSignals *AssessmentSignalHandler
privacy *PrivacyHandler
evidence *EvidenceHandler
matches *MatchHandler
notifications *NotificationHandler
problems *problem.Responder
}
@@ -99,6 +101,17 @@ func WithEvidence(evidence *EvidenceHandler) HandlerOption {
return func(handler *Handler) { handler.evidence = evidence }
}
// WithNotifications serves the inbox of the candidate cabinet and of one
// organization cabinet.
func WithNotifications(notifications *NotificationHandler) HandlerOption {
return func(handler *Handler) { handler.notifications = notifications }
}
// WithMatches serves the deterministic match search of the visible bank.
func WithMatches(matches *MatchHandler) HandlerOption {
return func(handler *Handler) { handler.matches = matches }
}
func NewHandler(health *HealthHandler, problems *problem.Responder, options ...HandlerOption) *Handler {
handler := &Handler{health: health, problems: problems}
for _, option := range options {
@@ -0,0 +1,310 @@
package v1
import (
"context"
"errors"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/adapter/primary/http/problem"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/candidateview"
"lincodex/backend/internal/usecase/matching"
)
// MatchOperations searches and ranks the organization-visible candidate bank.
type MatchOperations interface {
Search(ctx context.Context, request matching.Request) (matching.Result, error)
}
// MatchHandler binds the match search use case to the v1 API.
type MatchHandler struct {
operations MatchOperations
}
func NewMatchHandler(operations MatchOperations) *MatchHandler {
if operations == nil {
panic("v1.NewMatchHandler - operations must not be nil")
}
return &MatchHandler{operations: operations}
}
func (handler *Handler) SearchOrganizationMatches(
ctx context.Context,
request api.MatchSearchRequest,
params api.SearchOrganizationMatchesParams,
) (api.SearchOrganizationMatchesRes, error) {
if handler.matches == nil {
return handler.UnimplementedHandler.SearchOrganizationMatches(ctx, request, params)
}
return handler.matches.SearchOrganizationMatches(ctx, request, params)
}
func (handler *MatchHandler) SearchOrganizationMatches(
ctx context.Context,
request api.MatchSearchRequest,
params api.SearchOrganizationMatchesParams,
) (api.SearchOrganizationMatchesRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.SearchOrganizationMatchesUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
command, err := matchSearchCommand(principal.UserID, params.OrgID, request)
if err != nil {
return nil, err
}
result, err := handler.operations.Search(ctx, command)
if err != nil {
switch {
case errors.Is(err, matching.ErrForbidden), errors.Is(err, candidateview.ErrForbidden),
errors.Is(err, outbound.ErrOrganizationManagerRequired):
return (*api.SearchOrganizationMatchesForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, outbound.ErrOrganizationNotFound), errors.Is(err, matching.ErrNeedNotFound):
return (*api.SearchOrganizationMatchesNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
}
return nil, err
}
return &api.MatchSearchResponseHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: matchSearchResponse(result),
}, nil
}
func matchSearchCommand(actorID, organizationID uuid.UUID, request api.MatchSearchRequest) (matching.Request, error) {
command := matching.Request{ActorID: actorID, OrganizationID: organizationID}
switch {
case request.IsMatchSearchByNeed():
byNeed := request.MatchSearchByNeed
command.Need = &matching.NeedReference{NeedID: byNeed.NeedID, RequirementsVersion: int64(byNeed.RequirementsVersion)}
if byNeed.Filters.Set {
command.Filters = matchFilters(byNeed.Filters.Value)
}
case request.IsMatchSearchByBank():
command.Filters = matchFilters(request.MatchSearchByBank.Filters)
default:
return matching.Request{}, errors.New("v1.matchSearchCommand - request variant is not known")
}
return command, nil
}
func matchFilters(filters api.MatchSearchFilters) matching.Filters {
result := matching.Filters{}
if filters.Specialization.Set {
value := domain.SpecializationCode(filters.Specialization.Value)
result.Specialization = &value
}
if filters.ConfirmedGrade.Set {
value := domain.GradeCode(filters.ConfirmedGrade.Value)
result.ConfirmedGrade = &value
}
if filters.ConfirmedCategory.Set {
category := filters.ConfirmedCategory.Value
result.ConfirmedCategory = &matching.GradeFilter{
Specialization: domain.SpecializationCode(category.Specialization), Grade: domain.GradeCode(category.Grade),
}
}
if filters.ConfirmationStatus.Set {
value := domain.CandidateViewConfirmationStatus(filters.ConfirmationStatus.Value)
result.ConfirmationStatus = &value
}
if filters.DeclaredGrade.Set {
value := domain.GradeCode(filters.DeclaredGrade.Value)
result.DeclaredGrade = &value
}
for _, tag := range filters.Stack {
result.Stack = append(result.Stack, domain.CandidateViewSkillCode(tag))
}
if filters.Conditions.Set {
conditions := &matching.Conditions{}
for _, format := range filters.Conditions.Value.WorkFormats {
conditions.WorkFormats = append(conditions.WorkFormats, domain.QuestionnaireWorkFormat(format))
}
if filters.Conditions.Value.SalaryCompatibility.Set {
value := domain.CandidateViewSalaryCompatibility(filters.Conditions.Value.SalaryCompatibility.Value)
conditions.SalaryCompatibility = &value
}
result.Conditions = conditions
}
return result
}
func matchSearchResponse(result matching.Result) api.MatchSearchResponse {
response := api.MatchSearchResponse{
Source: matchSearchSource(result.Source),
Truncated: result.Truncated,
Groups: api.MatchSearchGroups{
Main: make([]api.MatchConfirmedCandidate, 0, len(result.Main)),
Near: make([]api.MatchConfirmedCandidate, 0, len(result.Near)),
Unconfirmed: make([]api.MatchUnconfirmedCandidate, 0, len(result.Unconfirmed)),
},
}
for _, entry := range result.Main {
response.Groups.Main = append(response.Groups.Main, matchConfirmedCandidate(entry))
}
for _, entry := range result.Near {
response.Groups.Near = append(response.Groups.Near, matchConfirmedCandidate(entry))
}
for _, entry := range result.Unconfirmed {
response.Groups.Unconfirmed = append(response.Groups.Unconfirmed, matchUnconfirmedCandidate(entry))
}
return response
}
func matchSearchSource(source matching.Source) api.MatchSearchSource {
var response api.MatchSearchSource
if source.Need != nil {
response.SetMatchSearchNeedSource(api.MatchSearchNeedSource{
Kind: api.MatchSearchNeedSourceKindNeed, NeedID: source.Need.NeedID,
RequirementsVersion: api.NeedVersion(source.Need.RequirementsVersion),
})
return response
}
response.SetMatchSearchBankSource(api.MatchSearchBankSource{
Kind: api.MatchSearchBankSourceKindBank, Filters: matchAppliedFilters(source.Filters),
})
return response
}
// matchAppliedFilters writes every key, with null for a filter that was not
// asked for, so the result stays tied to its exact basis.
func matchAppliedFilters(filters matching.Filters) api.MatchAppliedFilters {
var applied api.MatchAppliedFilters
applied.Specialization.SetToNull()
applied.ConfirmedGrade.SetToNull()
applied.ConfirmedCategory.SetToNull()
applied.ConfirmationStatus.SetToNull()
applied.DeclaredGrade.SetToNull()
applied.Conditions.SetToNull()
if filters.Specialization != nil {
applied.Specialization.SetTo(api.SpecializationCode(*filters.Specialization))
}
if filters.ConfirmedGrade != nil {
applied.ConfirmedGrade.SetTo(api.GradeCode(*filters.ConfirmedGrade))
}
if filters.ConfirmedCategory != nil {
applied.ConfirmedCategory.SetTo(api.MatchGradeFilter{
Specialization: api.SpecializationCode(filters.ConfirmedCategory.Specialization),
Grade: api.GradeCode(filters.ConfirmedCategory.Grade),
})
}
if filters.ConfirmationStatus != nil {
applied.ConfirmationStatus.SetTo(api.MatchConfirmationStatus(*filters.ConfirmationStatus))
}
if filters.DeclaredGrade != nil {
applied.DeclaredGrade.SetTo(api.GradeCode(*filters.DeclaredGrade))
}
for _, tag := range filters.Stack {
applied.Stack = append(applied.Stack, api.MatchSearchStackTag(tag))
}
if filters.Conditions != nil {
conditions := api.MatchAppliedConditions{}
conditions.SalaryCompatibility.SetToNull()
for _, format := range filters.Conditions.WorkFormats {
conditions.WorkFormats = append(conditions.WorkFormats, api.WorkFormat(format))
}
if filters.Conditions.SalaryCompatibility != nil {
conditions.SalaryCompatibility.SetTo(api.CandidateSalaryCompatibility(*filters.Conditions.SalaryCompatibility))
}
applied.Conditions.SetTo(conditions)
}
return applied
}
func matchConfirmedCandidate(entry matching.Entry) api.MatchConfirmedCandidate {
candidate := api.MatchConfirmedCandidate{
CandidateHandle: api.CandidateHandle(entry.CandidateHandle),
Specialization: api.SpecializationCode(entry.Specialization),
ConfirmationStatus: api.MatchConfirmedCandidateConfirmationStatusConfirmed,
PublicContext: matchPublicContext(entry.PublicContext),
EvidenceSummary: matchEvidenceSummary(entry.EvidenceSummary),
UnknownFlags: matchUnknownFlags(entry.UnknownFlags),
}
candidate.DeclaredGrade = matchDeclaredGrade(entry.DeclaredGrade)
if entry.Category != nil {
candidate.Category = api.MatchCategory{
Specialization: api.SpecializationCode(entry.Category.Specialization), Grade: api.GradeCode(entry.Category.Grade),
}
candidate.Strength = api.MatchStrength(entry.Category.Strength)
}
components := api.MatchConfirmedComponents{
Fit: api.MatchScore(entry.Components.Fit), Coverage: api.MatchScore(entry.Components.Coverage),
Domain: api.MatchScore(entry.Components.Domain), Semantics: api.MatchScore(entry.Components.Semantics),
Competition: api.MatchScore(entry.Components.Competition), Freshness: api.MatchScore(entry.Components.Freshness),
Responsiveness: api.MatchScore(entry.Components.Responsiveness), RankScore: api.MatchScore(entry.Components.RankScore),
}
components.Percentile.SetToNull()
if entry.Components.Percentile != nil {
components.Percentile.SetTo(*entry.Components.Percentile)
}
candidate.Components = components
return candidate
}
func matchUnconfirmedCandidate(entry matching.Entry) api.MatchUnconfirmedCandidate {
return api.MatchUnconfirmedCandidate{
CandidateHandle: api.CandidateHandle(entry.CandidateHandle),
Specialization: api.SpecializationCode(entry.Specialization),
ConfirmationStatus: api.MatchUnconfirmedCandidateConfirmationStatusUnconfirmed,
DeclaredGrade: matchDeclaredGrade(entry.DeclaredGrade),
PublicContext: matchPublicContext(entry.PublicContext),
EvidenceSummary: matchEvidenceSummary(entry.EvidenceSummary),
Components: api.MatchUnconfirmedComponents{Fit: entry.Components.Fit, Coverage: entry.Components.Coverage},
UnknownFlags: matchUnknownFlags(entry.UnknownFlags),
}
}
func matchDeclaredGrade(grade *domain.GradeCode) api.NilGradeCode {
var declared api.NilGradeCode
declared.SetToNull()
if grade != nil {
declared.SetTo(api.GradeCode(*grade))
}
return declared
}
func matchPublicContext(context matching.PublicContext) api.MatchPublicContext {
var response api.MatchPublicContext
response.ExperienceBand.SetToNull()
response.SalaryCompatibility.SetToNull()
if len(context.Stack) > 0 {
response.Stack = make(api.MatchPublicStack, 0, len(context.Stack))
for _, tag := range context.Stack {
response.Stack = append(response.Stack, api.MatchSearchStackTag(tag))
}
}
if context.ExperienceBand != nil {
response.ExperienceBand.SetTo(api.CandidateExperienceBand(*context.ExperienceBand))
}
if len(context.WorkFormats) > 0 {
response.WorkFormats = make([]api.WorkFormat, 0, len(context.WorkFormats))
for _, format := range context.WorkFormats {
response.WorkFormats = append(response.WorkFormats, api.WorkFormat(format))
}
}
if context.SalaryCompatibility != nil {
response.SalaryCompatibility.SetTo(api.CandidateSalaryCompatibility(*context.SalaryCompatibility))
}
return response
}
func matchEvidenceSummary(items []matching.EvidenceItem) api.MatchEvidenceSummary {
summary := make(api.MatchEvidenceSummary, 0, len(items))
for _, item := range items {
summary = append(summary, api.MatchEvidenceSummaryItem{
Code: api.MatchEvidenceCode(item.Code), State: api.MatchEvidenceState(item.State),
})
}
return summary
}
func matchUnknownFlags(flags []matching.UnknownFlag) api.MatchUnknownFlags {
response := make(api.MatchUnknownFlags, 0, len(flags))
for _, flag := range flags {
response = append(response, api.MatchUnknownFlag{
Component: api.MatchUnknownComponent(flag.Component), Reason: api.MatchUnknownReason(flag.Reason),
})
}
return response
}
@@ -0,0 +1,221 @@
package v1
import (
"context"
"encoding/json"
"errors"
"strings"
"testing"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/candidateview"
"lincodex/backend/internal/usecase/matching"
)
type matchOperationsStub struct {
result matching.Result
err error
request matching.Request
}
func (stub *matchOperationsStub) Search(_ context.Context, request matching.Request) (matching.Result, error) {
stub.request = request
return stub.result, stub.err
}
func TestSearchOrganizationMatchesMapsABankRequestAndEchoesTheNormalizedFilters(t *testing.T) {
userID, organizationID := uuid.New(), uuid.New()
stub := &matchOperationsStub{}
handler := NewMatchHandler(stub)
var request api.MatchSearchRequest
request.SetMatchSearchByBank(api.MatchSearchByBank{Filters: api.MatchSearchFilters{
Specialization: api.NewOptSpecializationCode(api.SpecializationCodeBackend),
ConfirmedCategory: api.NewOptMatchGradeFilter(api.MatchGradeFilter{Specialization: api.SpecializationCodeBackend, Grade: api.GradeCodeMiddle}),
Stack: []api.MatchSearchStackTag{api.MatchSearchStackTagPostgresql, api.MatchSearchStackTagGo},
Conditions: api.NewOptMatchSearchConditions(api.MatchSearchConditions{
WorkFormats: []api.WorkFormat{api.WorkFormatRemote},
SalaryCompatibility: api.NewOptCandidateSalaryCompatibility(api.CandidateSalaryCompatibilityCompatible),
}),
}})
stub.result.Truncated = false
stub.result.Source = matching.Source{Filters: matching.Filters{
Specialization: new(domain.SpecializationCode), Stack: []domain.CandidateViewSkillCode{domain.CandidateViewSkillGo},
}}
*stub.result.Source.Filters.Specialization = domain.SpecializationBackend
response, err := handler.SearchOrganizationMatches(privacyHTTPContext(userID, ""), request, api.SearchOrganizationMatchesParams{OrgID: organizationID})
if err != nil {
t.Fatalf("SearchOrganizationMatches() error = %v", err)
}
if stub.request.ActorID != userID || stub.request.OrganizationID != organizationID || stub.request.Need != nil {
t.Fatalf("command scope = %+v, want the session actor and the path organization", stub.request)
}
filters := stub.request.Filters
if filters.Specialization == nil || *filters.Specialization != domain.SpecializationBackend ||
filters.ConfirmedCategory == nil || filters.ConfirmedCategory.Grade != domain.GradeMiddle || filters.ConfirmedGrade != nil ||
filters.ConfirmationStatus != nil || filters.DeclaredGrade != nil || len(filters.Stack) != 2 ||
filters.Conditions == nil || len(filters.Conditions.WorkFormats) != 1 || filters.Conditions.SalaryCompatibility == nil {
t.Fatalf("mapped filters = %+v", filters)
}
body, ok := response.(*api.MatchSearchResponseHeaders)
if !ok || body.CacheControl != api.CacheControlNoStoreNoStore {
t.Fatalf("response = %#v, want a no-store result", response)
}
encoded, err := json.Marshal(body.Response)
if err != nil {
t.Fatalf("encode response: %v", err)
}
want := `{"source":{"kind":"bank","filters":{"specialization":"backend","confirmed_grade":null,"confirmed_category":null,` +
`"confirmation_status":null,"declared_grade":null,"stack":["go"],"conditions":null}},"groups":{"main":[],"near":[],"unconfirmed":[]},"truncated":false}`
if string(encoded) != want {
t.Fatalf("response = %s, want %s", encoded, want)
}
}
func TestSearchOrganizationMatchesMapsANeedRequestAndKeepsUnconfirmedEntriesStrict(t *testing.T) {
userID, organizationID, needID := uuid.New(), uuid.New(), uuid.New()
handle := "cv1_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
junior := domain.GradeJunior
stub := &matchOperationsStub{result: matching.Result{
Source: matching.Source{Need: &matching.NeedReference{NeedID: needID, RequirementsVersion: 3}},
Unconfirmed: []matching.Entry{{
CandidateHandle: handle, Specialization: domain.SpecializationNetworkEngineer, DeclaredGrade: &junior,
Components: matching.Components{Fit: 0.3125, Coverage: 0.25},
UnknownFlags: []matching.UnknownFlag{
{Component: matching.UnknownAssessment, Reason: matching.ReasonNoConfirmationForSpecialization},
},
EvidenceSummary: []matching.EvidenceItem{{Code: matching.EvidenceDeclaredGrade, State: matching.EvidenceStateDeclaredOnly}},
}},
}}
handler := NewMatchHandler(stub)
var request api.MatchSearchRequest
request.SetMatchSearchByNeed(api.MatchSearchByNeed{NeedID: needID, RequirementsVersion: 3})
response, err := handler.SearchOrganizationMatches(privacyHTTPContext(userID, ""), request, api.SearchOrganizationMatchesParams{OrgID: organizationID})
if err != nil {
t.Fatalf("SearchOrganizationMatches() error = %v", err)
}
if stub.request.Need == nil || stub.request.Need.NeedID != needID || stub.request.Need.RequirementsVersion != 3 {
t.Fatalf("need reference = %+v", stub.request.Need)
}
body, ok := response.(*api.MatchSearchResponseHeaders)
if !ok {
t.Fatalf("response = %#v", response)
}
encoded, err := json.Marshal(body.Response.Groups.Unconfirmed)
if err != nil {
t.Fatalf("encode response: %v", err)
}
want := `[{"candidate_handle":"` + handle + `","specialization":"network_engineer","confirmation_status":"unconfirmed","declared_grade":"junior",` +
`"category":null,"strength":null,"public_context":{"stack":null,"experience_band":null,"work_formats":null,"salary_compatibility":null},` +
`"evidence_summary":[{"code":"declared_grade","state":"declared_only"}],"components":{"fit":0.3125,"coverage":0.25},` +
`"unknown_flags":[{"component":"assessment","reason":"no_confirmation_for_specialization"}]}]`
if string(encoded) != want {
t.Fatalf("unconfirmed entries = %s\nwant %s", encoded, want)
}
for _, forbidden := range []string{"percentile", "rank_score", "theta", "freshness"} {
if strings.Contains(string(encoded), forbidden) {
t.Fatalf("an unconfirmed entry exposes %q", forbidden)
}
}
}
func TestSearchOrganizationMatchesMapsAConfirmedEntryWithANullPercentile(t *testing.T) {
handle := "cv1_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
stub := &matchOperationsStub{result: matching.Result{Main: []matching.Entry{{
CandidateHandle: handle, Specialization: domain.SpecializationBackend,
Category: &domain.CandidateViewCategory{Specialization: domain.SpecializationBackend, Grade: domain.GradeMiddle, Strength: domain.CandidateViewStrengthStrong},
Components: matching.Components{
Fit: 0.5, Coverage: 0.5, Domain: 0.5, Semantics: 0.5, Freshness: 0.5, Responsiveness: 0.5, RankScore: 0.45125,
},
}}}}
response, err := NewMatchHandler(stub).SearchOrganizationMatches(privacyHTTPContext(uuid.New(), ""),
func() api.MatchSearchRequest {
var request api.MatchSearchRequest
request.SetMatchSearchByBank(api.MatchSearchByBank{})
return request
}(), api.SearchOrganizationMatchesParams{OrgID: uuid.New()})
if err != nil {
t.Fatalf("SearchOrganizationMatches() error = %v", err)
}
encoded, err := json.Marshal(response.(*api.MatchSearchResponseHeaders).Response.Groups.Main)
if err != nil {
t.Fatalf("encode response: %v", err)
}
for _, want := range []string{
`"confirmation_status":"confirmed"`, `"declared_grade":null`, `"category":{"specialization":"backend","grade":"middle"}`, `"strength":"strong"`,
`"percentile":null`, `"competition":0`, `"rank_score":0.45125`,
} {
if !strings.Contains(string(encoded), want) {
t.Errorf("confirmed entry %s lacks %s", encoded, want)
}
}
}
func TestSearchOrganizationMatchesMapsFailuresToTheContractProblems(t *testing.T) {
userID := uuid.New()
var request api.MatchSearchRequest
request.SetMatchSearchByBank(api.MatchSearchByBank{})
params := api.SearchOrganizationMatchesParams{OrgID: uuid.New()}
stub := &matchOperationsStub{}
handler := NewMatchHandler(stub)
unauthenticated, err := handler.SearchOrganizationMatches(context.Background(), request, params)
if _, ok := unauthenticated.(*api.SearchOrganizationMatchesUnauthorized); err != nil || !ok {
t.Fatalf("no principal = %#v, %v, want 401", unauthenticated, err)
}
for name, test := range map[string]struct {
err error
want string
}{
"not an owner": {matching.ErrForbidden, "forbidden"},
"candidate account": {candidateview.ErrForbidden, "forbidden"},
"membership is not an owner": {outbound.ErrOrganizationManagerRequired, "forbidden"},
"no membership": {outbound.ErrOrganizationNotFound, "not_found"},
"unknown need": {matching.ErrNeedNotFound, "not_found"},
} {
stub.err = test.err
response, err := handler.SearchOrganizationMatches(privacyHTTPContext(userID, ""), request, params)
if err != nil {
t.Errorf("%s: error = %v", name, err)
continue
}
var got string
switch response.(type) {
case *api.SearchOrganizationMatchesForbidden:
got = "forbidden"
case *api.SearchOrganizationMatchesNotFound:
got = "not_found"
}
if got != test.want {
t.Errorf("%s = %T, want %s", name, response, test.want)
}
}
for _, unexpected := range []error{errors.New("storage failed"), matching.ErrPolicyUnavailable} {
stub.err = unexpected
if _, err := handler.SearchOrganizationMatches(privacyHTTPContext(userID, ""), request, params); err == nil {
t.Fatalf("an unexpected failure %v was answered as a client problem", unexpected)
}
}
}
func TestSearchOrganizationMatchesReportsATruncatedResultWithoutACount(t *testing.T) {
stub := &matchOperationsStub{result: matching.Result{Truncated: true}}
var request api.MatchSearchRequest
request.SetMatchSearchByBank(api.MatchSearchByBank{})
response, err := NewMatchHandler(stub).SearchOrganizationMatches(privacyHTTPContext(uuid.New(), ""), request, api.SearchOrganizationMatchesParams{OrgID: uuid.New()})
if err != nil {
t.Fatalf("SearchOrganizationMatches() error = %v", err)
}
encoded, err := json.Marshal(response.(*api.MatchSearchResponseHeaders).Response)
if err != nil {
t.Fatalf("encode response: %v", err)
}
if !strings.Contains(string(encoded), `"truncated":true`) || strings.Contains(string(encoded), "total") || strings.Contains(string(encoded), "count") {
t.Fatalf("response = %s, want the flag and no count", encoded)
}
}
@@ -0,0 +1,78 @@
package v1
import (
"encoding/base64"
"encoding/binary"
"errors"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/port/outbound"
)
const (
notificationCursorVersion = 1
notificationCursorBytes = 61
// maxNotificationCursorYear keeps the decoded time inside the range that
// PostgreSQL stores and that the contract's RFC 3339 timestamps print.
maxNotificationCursorYear = 9999
)
// encodeNotificationCursor binds a page position to the account and the
// organization context of the listing, so a cursor of another account or
// another cabinet fails as malformed instead of continuing a foreign list.
// A nil organization is the candidate cabinet.
func encodeNotificationCursor(recipientID uuid.UUID, organizationID *uuid.UUID, position outbound.NotificationInboxPosition) (string, error) {
at := position.OccurredAt.UTC()
if recipientID == uuid.Nil || position.EventID == uuid.Nil || at.IsZero() || at.Year() > maxNotificationCursorYear {
return "", errors.New("v1.encodeNotificationCursor - a recipient and a valid page position are required")
}
seconds, nanos := at.Unix(), at.Nanosecond()
if seconds < 0 {
return "", errors.New("v1.encodeNotificationCursor - the page position predates the epoch")
}
if nanos < 0 || nanos >= 1_000_000_000 || nanos%1_000 != 0 {
return "", errors.New("v1.encodeNotificationCursor - the page position has no microsecond precision")
}
var value [notificationCursorBytes]byte
value[0] = notificationCursorVersion
copy(value[1:17], recipientID[:])
if organizationID != nil {
copy(value[17:33], organizationID[:])
}
binary.BigEndian.PutUint64(value[33:41], uint64(seconds))
binary.BigEndian.PutUint32(value[41:45], uint32(nanos))
copy(value[45:61], position.EventID[:])
return base64.RawURLEncoding.EncodeToString(value[:]), nil
}
// decodeNotificationCursor reads a cursor made for the same account and
// cabinet by encodeNotificationCursor.
func decodeNotificationCursor(cursor string, recipientID uuid.UUID, organizationID *uuid.UUID) (outbound.NotificationInboxPosition, error) {
const location = "v1.decodeNotificationCursor"
value, err := base64.RawURLEncoding.DecodeString(cursor)
if err != nil || len(value) != notificationCursorBytes || recipientID == uuid.Nil ||
base64.RawURLEncoding.EncodeToString(value) != cursor || value[0] != notificationCursorVersion ||
uuid.UUID(value[1:17]) != recipientID {
return outbound.NotificationInboxPosition{}, errors.New(location + " - the cursor is invalid")
}
var scope uuid.UUID
if organizationID != nil {
scope = *organizationID
}
if uuid.UUID(value[17:33]) != scope {
return outbound.NotificationInboxPosition{}, errors.New(location + " - the cursor belongs to another cabinet")
}
seconds := binary.BigEndian.Uint64(value[33:41])
nanos := binary.BigEndian.Uint32(value[41:45])
eventID := uuid.UUID(value[45:61])
if seconds > uint64(1<<62) || nanos >= 1_000_000_000 || nanos%1_000 != 0 || eventID == uuid.Nil {
return outbound.NotificationInboxPosition{}, errors.New(location + " - the cursor position is invalid")
}
at := time.Unix(int64(seconds), int64(nanos)).UTC()
if at.IsZero() || at.Year() > maxNotificationCursorYear {
return outbound.NotificationInboxPosition{}, errors.New(location + " - the cursor timestamp is invalid")
}
return outbound.NotificationInboxPosition{OccurredAt: at, EventID: eventID}, nil
}
@@ -0,0 +1,277 @@
package v1
import (
"context"
"errors"
"fmt"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/adapter/primary/http/problem"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/notification"
)
const defaultNotificationLimit = 20
// NotificationOperations lists and marks the inbox of the authenticated
// account. The candidate cabinet and the cabinet of one organization share
// the operations; the request names which one.
type NotificationOperations interface {
List(ctx context.Context, request notification.InboxListRequest) (notification.InboxPage, error)
MarkRead(ctx context.Context, request notification.InboxMarkReadRequest) (domain.NotificationInboxEntry, error)
}
// NotificationHandler binds the inbox use cases to the v1 API.
type NotificationHandler struct {
operations NotificationOperations
}
func NewNotificationHandler(operations NotificationOperations) *NotificationHandler {
if operations == nil {
panic("v1.NewNotificationHandler - operations must not be nil")
}
return &NotificationHandler{operations: operations}
}
func (handler *Handler) ListMyNotifications(ctx context.Context, params api.ListMyNotificationsParams) (api.ListMyNotificationsRes, error) {
if handler.notifications == nil {
return handler.UnimplementedHandler.ListMyNotifications(ctx, params)
}
return handler.notifications.ListMyNotifications(ctx, params)
}
func (handler *Handler) MarkMyNotificationRead(ctx context.Context, params api.MarkMyNotificationReadParams) (api.MarkMyNotificationReadRes, error) {
if handler.notifications == nil {
return handler.UnimplementedHandler.MarkMyNotificationRead(ctx, params)
}
return handler.notifications.MarkMyNotificationRead(ctx, params)
}
func (handler *Handler) ListOrganizationNotifications(
ctx context.Context,
params api.ListOrganizationNotificationsParams,
) (api.ListOrganizationNotificationsRes, error) {
if handler.notifications == nil {
return handler.UnimplementedHandler.ListOrganizationNotifications(ctx, params)
}
return handler.notifications.ListOrganizationNotifications(ctx, params)
}
func (handler *Handler) MarkOrganizationNotificationRead(
ctx context.Context,
params api.MarkOrganizationNotificationReadParams,
) (api.MarkOrganizationNotificationReadRes, error) {
if handler.notifications == nil {
return handler.UnimplementedHandler.MarkOrganizationNotificationRead(ctx, params)
}
return handler.notifications.MarkOrganizationNotificationRead(ctx, params)
}
func (handler *NotificationHandler) ListMyNotifications(ctx context.Context, params api.ListMyNotificationsParams) (api.ListMyNotificationsRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.ListMyNotificationsUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
list, pointer := handler.list(ctx, principal.UserID, nil, params.Limit, params.Cursor)
if pointer != "" {
return (*api.ListMyNotificationsBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationQuery, "/"+pointer).Response), nil
}
page, err := list()
switch {
case err == nil:
return page, nil
case errors.Is(err, notification.ErrInboxForbidden):
return (*api.ListMyNotificationsForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
default:
return nil, err
}
}
func (handler *NotificationHandler) ListOrganizationNotifications(
ctx context.Context,
params api.ListOrganizationNotificationsParams,
) (api.ListOrganizationNotificationsRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.ListOrganizationNotificationsUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
organizationID := params.OrgID
list, pointer := handler.list(ctx, principal.UserID, &organizationID, params.Limit, params.Cursor)
if pointer != "" {
return (*api.ListOrganizationNotificationsBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationQuery, "/"+pointer).Response), nil
}
page, err := list()
switch {
case err == nil:
return page, nil
case errors.Is(err, notification.ErrInboxEmailNotVerified):
return (*api.ListOrganizationNotificationsForbidden)(&problem.New(ctx, api.ProblemCodeEmailNotVerified).Response), nil
case errors.Is(err, notification.ErrInboxForbidden):
return (*api.ListOrganizationNotificationsForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, outbound.ErrOrganizationNotFound):
return (*api.ListOrganizationNotificationsNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
default:
return nil, err
}
}
func (handler *NotificationHandler) MarkMyNotificationRead(
ctx context.Context,
params api.MarkMyNotificationReadParams,
) (api.MarkMyNotificationReadRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.MarkMyNotificationReadUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
receipt, err := handler.mark(ctx, principal.UserID, nil, params.NotificationID)
switch {
case err == nil:
return receipt, nil
case errors.Is(err, notification.ErrInboxForbidden):
return (*api.MarkMyNotificationReadForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, outbound.ErrNotificationInboxEntryNotFound):
return (*api.MarkMyNotificationReadNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
default:
return nil, err
}
}
func (handler *NotificationHandler) MarkOrganizationNotificationRead(
ctx context.Context,
params api.MarkOrganizationNotificationReadParams,
) (api.MarkOrganizationNotificationReadRes, error) {
principal, ok := PrincipalFromContext(ctx)
if !ok {
return (*api.MarkOrganizationNotificationReadUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
}
organizationID := params.OrgID
receipt, err := handler.mark(ctx, principal.UserID, &organizationID, params.NotificationID)
switch {
case err == nil:
return receipt, nil
case errors.Is(err, notification.ErrInboxEmailNotVerified):
return (*api.MarkOrganizationNotificationReadForbidden)(&problem.New(ctx, api.ProblemCodeEmailNotVerified).Response), nil
case errors.Is(err, notification.ErrInboxForbidden):
return (*api.MarkOrganizationNotificationReadForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
case errors.Is(err, outbound.ErrOrganizationNotFound), errors.Is(err, outbound.ErrNotificationInboxEntryNotFound):
// A missing membership, an unknown organization, and an item that is
// not the caller's in this organization are one answer.
return (*api.MarkOrganizationNotificationReadNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
default:
return nil, err
}
}
// list validates the page parameters and returns the deferred read, so the
// two list operations share the mapping of a page to the public type. A
// non-empty pointer names the invalid query parameter.
func (handler *NotificationHandler) list(
ctx context.Context,
recipientID uuid.UUID,
organizationID *uuid.UUID,
limitParam api.OptInt32,
cursorParam api.OptString,
) (func() (*api.NotificationListHeaders, error), string) {
limit, set := limitParam.Get()
if !set {
limit = defaultNotificationLimit
}
if limit < 1 || limit > outbound.MaxNotificationInboxPageSize {
return nil, "limit"
}
request := notification.InboxListRequest{RecipientUserID: recipientID, OrganizationID: organizationID, Limit: limit}
if cursor, set := cursorParam.Get(); set {
position, err := decodeNotificationCursor(cursor, recipientID, organizationID)
if err != nil {
return nil, "cursor"
}
request.After = &position
}
return func() (*api.NotificationListHeaders, error) {
const location = "NotificationHandler.list"
page, err := handler.operations.List(ctx, request)
if err != nil {
return nil, err
}
items := make([]api.Notification, 0, len(page.Items))
for _, item := range page.Items {
mapped, err := notificationResponse(item)
if err != nil {
return nil, fmt.Errorf("%s - map item: %w", location, err)
}
items = append(items, mapped)
}
next, err := privacyNextCursor(page.HasMore, len(page.Items), func() (string, error) {
last := outbound.NotificationInboxPositionOf(page.Items[len(page.Items)-1].Entry)
return encodeNotificationCursor(recipientID, organizationID, last)
})
if err != nil {
return nil, fmt.Errorf("%s - encode cursor: %w", location, err)
}
return &api.NotificationListHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: api.NotificationList{Items: items, Page: api.PageInfo{HasMore: page.HasMore, NextCursor: next}},
}, nil
}, ""
}
func (handler *NotificationHandler) mark(
ctx context.Context,
recipientID uuid.UUID,
organizationID *uuid.UUID,
eventID uuid.UUID,
) (*api.NotificationReadReceiptHeaders, error) {
entry, err := handler.operations.MarkRead(ctx, notification.InboxMarkReadRequest{
RecipientUserID: recipientID, OrganizationID: organizationID, EventID: eventID,
})
if err != nil {
return nil, err
}
readAt, isRead := entry.ReadAt()
if !isRead {
return nil, errors.New("NotificationHandler.mark - a marked item has no read time")
}
return &api.NotificationReadReceiptHeaders{
CacheControl: api.CacheControlNoStoreNoStore,
Response: api.NotificationReadReceipt{ID: entry.EventID(), ReadAt: api.Timestamp(readAt)},
}, nil
}
func notificationResponse(item notification.InboxItem) (api.Notification, error) {
kind, ok := notificationKind(item.Entry.EventType())
if !ok {
return api.Notification{}, errors.New("v1.notificationResponse - the stored event type has no public kind")
}
response := api.Notification{
ID: item.Entry.EventID(), Kind: kind, OrganizationID: item.Entry.OrganizationID(),
DeliveredAt: api.Timestamp(item.Entry.OccurredAt()),
}
response.ReadAt.SetToNull()
if readAt, isRead := item.Entry.ReadAt(); isRead {
response.ReadAt.SetTo(api.Timestamp(readAt))
}
response.Content.SetToNull()
if item.Content != nil {
content := api.NotificationContent{Title: item.Content.Title(), Summary: item.Content.Summary()}
content.LinkPath.SetToNull()
if path := item.Content.LinkPath(); path != "" {
content.LinkPath.SetTo(path)
}
response.Content.SetTo(content)
}
return response, nil
}
func notificationKind(eventType domain.NotificationInboxEventType) (api.NotificationKind, bool) {
switch eventType {
case domain.NotificationInboxInvitationDelivered:
return api.NotificationKindInvitationDelivered, true
case domain.NotificationInboxSyntheticDelivered:
return api.NotificationKindSynthetic, true
default:
return "", false
}
}
@@ -0,0 +1,263 @@
package v1
import (
"context"
"errors"
"reflect"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/notification"
)
type notificationOperationsStub struct {
page notification.InboxPage
entry domain.NotificationInboxEntry
err error
listRequest notification.InboxListRequest
markRequest notification.InboxMarkReadRequest
}
func (stub *notificationOperationsStub) List(_ context.Context, request notification.InboxListRequest) (notification.InboxPage, error) {
stub.listRequest = request
return stub.page, stub.err
}
func (stub *notificationOperationsStub) MarkRead(_ context.Context, request notification.InboxMarkReadRequest) (domain.NotificationInboxEntry, error) {
stub.markRequest = request
return stub.entry, stub.err
}
func notificationTestEntry(t *testing.T, recipientID, organizationID uuid.UUID, at time.Time) domain.NotificationInboxEntry {
t.Helper()
entry, err := domain.NewNotificationInboxEntry(domain.NotificationInboxEntryInput{
EventID: uuid.New(), RecipientUserID: recipientID, OrganizationID: organizationID,
EventType: domain.NotificationInboxSyntheticDelivered, SchemaVersion: 1,
SourceType: domain.NotificationInboxSourceOrganization, SourceID: organizationID, OccurredAt: at,
})
if err != nil {
t.Fatalf("NewNotificationInboxEntry() error = %v", err)
}
return entry
}
func TestListMyNotificationsMapsContentAndFallbackAndBindsTheCursor(t *testing.T) {
userID, organizationID := uuid.New(), uuid.New()
at := time.Date(2026, 10, 9, 8, 30, 0, 123000, time.UTC)
withContent := notificationTestEntry(t, userID, organizationID, at)
content, err := notification.NewInboxContent("Тестовое уведомление", "Проверка доставки.", "/candidate/invitations")
if err != nil {
t.Fatalf("NewInboxContent() error = %v", err)
}
withoutContent := notificationTestEntry(t, userID, organizationID, at.Add(-time.Hour))
read, err := withoutContent.MarkRead(at)
if err != nil {
t.Fatalf("MarkRead() error = %v", err)
}
stub := &notificationOperationsStub{page: notification.InboxPage{
Items: []notification.InboxItem{
{Entry: withContent, Content: &content},
{Entry: read, ContentUnavailable: true},
},
HasMore: true,
}}
handler := NewNotificationHandler(stub)
ctx := privacyHTTPContext(userID, "")
response, err := handler.ListMyNotifications(ctx, api.ListMyNotificationsParams{Limit: api.NewOptInt32(2)})
if err != nil {
t.Fatalf("ListMyNotifications() error = %v", err)
}
page, ok := response.(*api.NotificationListHeaders)
if !ok || page.CacheControl != api.CacheControlNoStoreNoStore || len(page.Response.Items) != 2 {
t.Fatalf("ListMyNotifications() = %#v, want a no-store page of two items", response)
}
if stub.listRequest.RecipientUserID != userID || stub.listRequest.OrganizationID != nil || stub.listRequest.Limit != 2 {
t.Fatalf("list request = %+v, want the session account in the candidate cabinet", stub.listRequest)
}
first, second := page.Response.Items[0], page.Response.Items[1]
if first.ID != withContent.EventID() || first.Kind != api.NotificationKindSynthetic || !first.ReadAt.Null {
t.Fatalf("first item = %+v, want an unread synthetic item", first)
}
if first.Content.Null || first.Content.Value.Title != "Тестовое уведомление" || first.Content.Value.LinkPath.Null ||
first.Content.Value.LinkPath.Value != "/candidate/invitations" {
t.Fatalf("first content = %+v, want the resolved text and link", first.Content)
}
if !second.Content.Null || second.ReadAt.Null {
t.Fatalf("second item = %+v, want no content and a read time", second)
}
if !page.Response.Page.HasMore || page.Response.Page.NextCursor.Null {
t.Fatalf("page info = %+v, want a next cursor", page.Response.Page)
}
// The cursor continues only the same account in the same cabinet.
next := page.Response.Page.NextCursor.Value
if _, err := handler.ListMyNotifications(ctx, api.ListMyNotificationsParams{Cursor: api.NewOptString(next)}); err != nil {
t.Fatalf("ListMyNotifications(cursor) error = %v", err)
}
if stub.listRequest.After == nil || stub.listRequest.After.EventID != read.EventID() {
t.Fatalf("continuation = %+v, want the position of the last item", stub.listRequest.After)
}
foreign, err := handler.ListMyNotifications(privacyHTTPContext(uuid.New(), ""), api.ListMyNotificationsParams{Cursor: api.NewOptString(next)})
if err != nil {
t.Fatalf("ListMyNotifications(foreign cursor) error = %v", err)
}
if _, ok := foreign.(*api.ListMyNotificationsBadRequest); !ok {
t.Fatalf("ListMyNotifications(foreign cursor) = %#v, want 400", foreign)
}
// A cursor of the candidate cabinet cannot continue an organization cabinet.
crossed, err := handler.ListOrganizationNotifications(ctx, api.ListOrganizationNotificationsParams{
OrgID: organizationID, Cursor: api.NewOptString(next),
})
if err != nil {
t.Fatalf("ListOrganizationNotifications(candidate cursor) error = %v", err)
}
if _, ok := crossed.(*api.ListOrganizationNotificationsBadRequest); !ok {
t.Fatalf("ListOrganizationNotifications(candidate cursor) = %#v, want 400", crossed)
}
for _, limit := range []int32{0, 101} {
bad, err := handler.ListMyNotifications(ctx, api.ListMyNotificationsParams{Limit: api.NewOptInt32(limit)})
if err != nil {
t.Fatalf("ListMyNotifications(limit %d) error = %v", limit, err)
}
if _, ok := bad.(*api.ListMyNotificationsBadRequest); !ok {
t.Fatalf("ListMyNotifications(limit %d) = %#v, want 400", limit, bad)
}
}
}
func TestNotificationOperationsMapAccessFailuresWithoutRevealingObjects(t *testing.T) {
userID, organizationID, eventID := uuid.New(), uuid.New(), uuid.New()
ctx := privacyHTTPContext(userID, "")
for _, test := range []struct {
name string
err error
list func(*NotificationHandler) (any, error)
mark func(*NotificationHandler) (any, error)
want []any
code api.ProblemCode
}{
{
name: "an account of the other scenario",
err: notification.ErrInboxForbidden,
list: func(h *NotificationHandler) (any, error) {
return h.ListMyNotifications(ctx, api.ListMyNotificationsParams{})
},
mark: func(h *NotificationHandler) (any, error) {
return h.MarkMyNotificationRead(ctx, api.MarkMyNotificationReadParams{NotificationID: eventID})
},
want: []any{(*api.ListMyNotificationsForbidden)(nil), (*api.MarkMyNotificationReadForbidden)(nil)},
},
{
name: "no active membership",
err: outbound.ErrOrganizationNotFound,
list: func(h *NotificationHandler) (any, error) {
return h.ListOrganizationNotifications(ctx, api.ListOrganizationNotificationsParams{OrgID: organizationID})
},
mark: func(h *NotificationHandler) (any, error) {
return h.MarkOrganizationNotificationRead(ctx, api.MarkOrganizationNotificationReadParams{OrgID: organizationID, NotificationID: eventID})
},
want: []any{(*api.ListOrganizationNotificationsNotFound)(nil), (*api.MarkOrganizationNotificationReadNotFound)(nil)},
},
{
name: "an employer whose email is not confirmed",
err: notification.ErrInboxEmailNotVerified,
list: func(h *NotificationHandler) (any, error) {
return h.ListOrganizationNotifications(ctx, api.ListOrganizationNotificationsParams{OrgID: organizationID})
},
mark: func(h *NotificationHandler) (any, error) {
return h.MarkOrganizationNotificationRead(ctx, api.MarkOrganizationNotificationReadParams{OrgID: organizationID, NotificationID: eventID})
},
want: []any{(*api.ListOrganizationNotificationsForbidden)(nil), (*api.MarkOrganizationNotificationReadForbidden)(nil)},
code: api.ProblemCodeEmailNotVerified,
},
{
name: "an item of another account",
err: outbound.ErrNotificationInboxEntryNotFound,
mark: func(h *NotificationHandler) (any, error) {
return h.MarkMyNotificationRead(ctx, api.MarkMyNotificationReadParams{NotificationID: eventID})
},
want: []any{nil, (*api.MarkMyNotificationReadNotFound)(nil)},
},
} {
t.Run(test.name, func(t *testing.T) {
handler := NewNotificationHandler(&notificationOperationsStub{err: test.err})
if test.list != nil {
got, err := test.list(handler)
if err != nil || !sameResponseType(got, test.want[0]) {
t.Fatalf("list = %#v, %v, want %T", got, err, test.want[0])
}
requireProblemCode(t, got, test.code)
}
got, err := test.mark(handler)
if err != nil || !sameResponseType(got, test.want[1]) {
t.Fatalf("mark = %#v, %v, want %T", got, err, test.want[1])
}
requireProblemCode(t, got, test.code)
})
}
handler := NewNotificationHandler(&notificationOperationsStub{err: errors.New("database is down")})
if _, err := handler.ListMyNotifications(ctx, api.ListMyNotificationsParams{}); err == nil {
t.Fatal("ListMyNotifications() hid an unexpected failure")
}
response, err := handler.ListMyNotifications(context.Background(), api.ListMyNotificationsParams{})
if err != nil {
t.Fatalf("ListMyNotifications(no session) error = %v", err)
}
if _, ok := response.(*api.ListMyNotificationsUnauthorized); !ok {
t.Fatalf("ListMyNotifications(no session) = %#v, want 401", response)
}
}
func sameResponseType(got, want any) bool {
return want != nil && reflect.TypeOf(got) == reflect.TypeOf(want)
}
func TestMarkNotificationReadReturnsTheFirstReadTimeOnly(t *testing.T) {
userID, organizationID := uuid.New(), uuid.New()
readAt := time.Date(2026, 10, 9, 8, 45, 0, 0, time.UTC)
entry, err := notificationTestEntry(t, userID, organizationID, readAt.Add(-time.Hour)).MarkRead(readAt)
if err != nil {
t.Fatalf("MarkRead() error = %v", err)
}
stub := &notificationOperationsStub{entry: entry}
handler := NewNotificationHandler(stub)
response, err := handler.MarkOrganizationNotificationRead(privacyHTTPContext(userID, ""),
api.MarkOrganizationNotificationReadParams{OrgID: organizationID, NotificationID: entry.EventID()})
if err != nil {
t.Fatalf("MarkOrganizationNotificationRead() error = %v", err)
}
receipt, ok := response.(*api.NotificationReadReceiptHeaders)
if !ok || receipt.CacheControl != api.CacheControlNoStoreNoStore || receipt.Response.ID != entry.EventID() ||
!time.Time(receipt.Response.ReadAt).Equal(readAt) {
t.Fatalf("MarkOrganizationNotificationRead() = %#v, want the receipt of the first read", response)
}
if stub.markRequest.RecipientUserID != userID || stub.markRequest.OrganizationID == nil || *stub.markRequest.OrganizationID != organizationID {
t.Fatalf("mark request = %+v, want the session account in the path organization", stub.markRequest)
}
}
func requireProblemCode(t *testing.T, response any, want api.ProblemCode) {
t.Helper()
if want == "" {
return
}
var got api.ProblemCode
switch typed := response.(type) {
case *api.ListOrganizationNotificationsForbidden:
got = typed.Code
case *api.MarkOrganizationNotificationReadForbidden:
got = typed.Code
default:
t.Fatalf("response %T carries no problem code", response)
}
if got != want {
t.Fatalf("problem code = %s, want %s", got, want)
}
}