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

@@ -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)
}
}