feat: add assessment, privacy and support flows

This commit is contained in:
TakuyaYagam1 committed 2026-10-08 08:08:25 +03:00
1 parent ee3738ee73
commit e4f24fa202
339 files changed
+56454 -1126

No files matched your search

@@ -0,0 +1,248 @@
package outbound
import (
"context"
"errors"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
var (
// ErrAssessmentAttemptNotFound covers both an unknown attempt and one
// owned by another candidate.
ErrAssessmentAttemptNotFound = errors.New("assessment attempt not found")
// ErrAssessmentAttemptConflict reports an active-attempt, quota, retry, or
// availability constraint that prevented attempt creation.
ErrAssessmentAttemptConflict = errors.New("assessment attempt conflicts with current state")
// ErrAssessmentAttemptIdempotencyConflict reports reuse of one idempotency
// key for a different canonical request body.
ErrAssessmentAttemptIdempotencyConflict = errors.New("assessment attempt idempotency key was reused")
// ErrAssessmentAttemptVersionConflict reports an attempt changed after the
// caller read it.
ErrAssessmentAttemptVersionConflict = errors.New("assessment attempt version changed")
// ErrAssessmentAttemptResultNotFound reports a completed attempt with no
// persisted immutable decision snapshot.
ErrAssessmentAttemptResultNotFound = errors.New("assessment attempt result not found")
)
// AssessmentAttemptIdempotencyScope is the server HMAC of the operation,
// client key, and authenticated actor. Raw keys never reach the repository.
type AssessmentAttemptIdempotencyScope [IdempotencyDigestSize]byte
// AssessmentAttemptRequestFingerprint is the server HMAC of the canonical
// request body. It cannot be used as an offline check of a submitted answer.
type AssessmentAttemptRequestFingerprint [IdempotencyDigestSize]byte
// AssessmentAttemptCreateOutcome is the immutable public result retained for
// the idempotency window. A created response contains its typed allowlisted
// projection; a conflict contains only a stable problem code.
type AssessmentAttemptCreateOutcome struct {
StatusCode int16
Response domain.AssessmentAttemptPublicSnapshot
ProblemCode string
}
// AssessmentAttemptCreateResult marks whether the outcome came from the
// immutable idempotency snapshot rather than a new command execution.
type AssessmentAttemptCreateResult struct {
Outcome AssessmentAttemptCreateOutcome
Replayed bool
}
// AssessmentAttemptSessionResult is the original HTTP 200 public projection
// for a session command, including an unchanged terminal attempt.
type AssessmentAttemptSessionResult struct {
Response domain.AssessmentAttemptPublicSnapshot
Replayed bool
}
// AssessmentAttemptCommandOutcome is an immutable answer or finalize
// response retained for the idempotency window.
type AssessmentAttemptCommandOutcome struct {
StatusCode int16
Response domain.AssessmentAttemptPublicSnapshot
ProblemCode string
PendingItemIDs []uuid.UUID
}
// AssessmentAttemptCommandResult marks whether the outcome is a replay.
type AssessmentAttemptCommandResult struct {
Outcome AssessmentAttemptCommandOutcome
Replayed bool
}
// AssessmentActiveAttemptSummary is the only active-attempt data needed by
// availability preflight. It intentionally excludes frozen task content.
type AssessmentActiveAttemptSummary struct {
ID domain.AssessmentAttemptID
ExpiresAt time.Time
}
// AssessmentRootAvailabilitySummary contains lifecycle timestamps for one
// root and the latest attempt in its correction chain. It is a private
// candidate-scoped read model and contains no answers or task content.
type AssessmentRootAvailabilitySummary struct {
RootTargetGrade domain.GradeCode
RootCreatedAt time.Time
RootUpdatedAt time.Time
RootExpiresAt time.Time
RootState domain.AssessmentAttemptState
RootOutcome domain.AssessmentAttemptOutcome
RootChainDeadline time.Time
LatestTargetGrade domain.GradeCode
LatestUpdatedAt time.Time
LatestExpiresAt time.Time
LatestState domain.AssessmentAttemptState
LatestOutcome domain.AssessmentAttemptOutcome
LatestChainDeadline time.Time
LatestPlatformError string
}
// AssessmentRootQuotaSnapshot is the current rolling-window count and the
// earliest instant a new root slot opens, if the quota is currently full.
type AssessmentRootQuotaSnapshot struct {
Count int32
AvailableAt *time.Time
}
// AssessmentAttemptRepositories exposes the repository bound to a UnitOfWork
// transaction.
type AssessmentAttemptRepositories interface {
AssessmentAttempts() AssessmentAttemptRepository
}
// AssessmentAttemptRepository persists complete attempt snapshots, frozen
// item instances, and immutable idempotent outcomes. Implementations bind
// every method to the surrounding unit of work and preserve candidate
// ownership in their queries.
type AssessmentAttemptRepository interface {
// Create atomically inserts an attempt and its frozen items. The caller
// holds the actor+specialization transaction lock and stores the result
// snapshot before the unit of work commits.
Create(ctx context.Context, attempt domain.AssessmentAttempt) error
// LockScope serializes creation and quota checks for one candidate and
// specialization. A nil specialization is the separate training scope.
LockScope(ctx context.Context, userID uuid.UUID, specialization *domain.SpecializationCode) error
// GetActiveForSpecialization returns the one active real attempt, if any.
// The partial unique index remains the final concurrency guard.
GetActiveForSpecialization(ctx context.Context, userID uuid.UUID, specialization domain.SpecializationCode) (domain.AssessmentAttempt, bool, error)
// GetActiveTraining returns the one active training attempt, if any.
// Training remains outside real assessment quotas and categories.
GetActiveTraining(ctx context.Context, userID uuid.UUID) (domain.AssessmentAttempt, bool, error)
// GetLatestRootForSpecialization returns the newest root attempt, optionally
// restricted to one target grade, for retry and promotion intervals.
GetLatestRootForSpecialization(
ctx context.Context,
userID uuid.UUID,
specialization domain.SpecializationCode,
grade *domain.GradeCode,
) (domain.AssessmentAttempt, bool, error)
// CountRootAttemptsSince counts root attempts for the supplied candidate
// and optional specialization at or after since. Corrective and training
// attempts never consume root quota.
CountRootAttemptsSince(ctx context.Context, userID uuid.UUID, specialization *domain.SpecializationCode, since time.Time) (int32, error)
// GetAvailabilityActiveAttempt reads the current real attempt without a
// row lock or lifecycle update.
GetAvailabilityActiveAttempt(ctx context.Context, userID uuid.UUID, specialization domain.SpecializationCode) (AssessmentActiveAttemptSummary, bool, error)
// ListAvailabilityRootSummaries returns recent eligible root attempts and
// their latest correction-chain headers without locking or loading items.
ListAvailabilityRootSummaries(ctx context.Context, userID uuid.UUID, specialization domain.SpecializationCode, since time.Time) ([]AssessmentRootAvailabilitySummary, error)
// GetRootQuotaSnapshot returns a candidate-wide root quota view for one
// policy window. availableAt is nil unless a new root is currently blocked.
GetRootQuotaSnapshot(ctx context.Context, userID uuid.UUID, since, asOf time.Time, window time.Duration, maxAttempts int32) (AssessmentRootQuotaSnapshot, error)
// ListDisclosedFamilyKeys returns families actually shown by root or
// corrective attempts since the non-repeat boundary; frozen future items
// are excluded.
ListDisclosedFamilyKeys(ctx context.Context, userID uuid.UUID, since time.Time) ([]domain.AssessmentFamilyKey, error)
// ListCorrectionChain returns the root and all its corrections in creation
// order, with their frozen items, for domain eligibility validation.
ListCorrectionChain(ctx context.Context, userID uuid.UUID, specialization domain.SpecializationCode, rootID domain.AssessmentAttemptID) ([]domain.AssessmentAttempt, error)
// SaveCreateOutcome records the original 201 or 409 response under the
// already-reserved idempotency scope. The generic IdempotencyRecord and
// this outcome commit in the same transaction and share its 24-hour expiry.
SaveCreateOutcome(ctx context.Context, scope AssessmentAttemptIdempotencyScope, outcome AssessmentAttemptCreateOutcome) error
// DeleteExpiredOutcome replaces a typed outcome only after generic Reserve
// created a new idempotency window for the same scope.
DeleteExpiredOutcome(ctx context.Context, scope AssessmentAttemptIdempotencyScope) error
// GetCreateOutcome returns the immutable 201 or 409 response snapshot for a
// live key. Missing data for a live generic idempotency record is an
// integrity error, not a cache miss.
GetCreateOutcome(ctx context.Context, scope AssessmentAttemptIdempotencyScope) (AssessmentAttemptCreateOutcome, error)
// GetForCandidate is owner-scoped. An unknown or foreign attempt returns
// ErrAssessmentAttemptNotFound and never changes session or attempt state.
GetForCandidate(ctx context.Context, userID uuid.UUID, attemptID domain.AssessmentAttemptID) (domain.AssessmentAttempt, error)
// GetKindForCandidate reads the immutable kind without acquiring an attempt
// row lock. Session commands use it before checking C3, then lock the row.
GetKindForCandidate(ctx context.Context, userID uuid.UUID, attemptID domain.AssessmentAttemptID) (domain.AssessmentAttemptKind, error)
// GetForCandidateForUpdate obtains the owner-scoped write lock for a command.
// Callers must take any required consent lock before this row lock.
GetForCandidateForUpdate(ctx context.Context, userID uuid.UUID, attemptID domain.AssessmentAttemptID) (domain.AssessmentAttempt, error)
// StartOrResumeSession performs the version check and session transition
// atomically. It returns changed=false for an active-session repeat or a
// terminal attempt; a matching key's original 200 is stored separately.
StartOrResumeSession(
ctx context.Context,
userID uuid.UUID,
attemptID domain.AssessmentAttemptID,
expectedVersion int64,
at time.Time,
) (domain.AssessmentAttempt, bool, error)
// SaveAnswer atomically makes one unanswered frozen item immutable and
// advances its owner-scoped attempt transition from current to next.
SaveAnswer(ctx context.Context, current, next domain.AssessmentAttempt, itemID uuid.UUID) error
// SaveTransition atomically stores a non-answer lifecycle transition after
// a command has locked the attempt row.
SaveTransition(ctx context.Context, current, next domain.AssessmentAttempt) error
// SaveResult stores one typed immutable result in the same transaction as
// the completed attempt transition.
SaveResult(ctx context.Context, userID uuid.UUID, result domain.AssessmentAttemptResultSnapshot) error
// GetResult returns the immutable owner-scoped result snapshot.
GetResult(ctx context.Context, userID uuid.UUID, attemptID domain.AssessmentAttemptID) (domain.AssessmentAttemptResultSnapshot, error)
// SaveSessionOutcome records the original 200 public projection for the
// already-reserved idempotency scope. It shares the transaction and expiry
// of the generic idempotency record.
SaveSessionOutcome(ctx context.Context, scope AssessmentAttemptIdempotencyScope, response domain.AssessmentAttemptPublicSnapshot) error
// GetSessionOutcome returns the original 200 public projection for a live
// key, even if the stored attempt has since changed.
GetSessionOutcome(ctx context.Context, scope AssessmentAttemptIdempotencyScope) (domain.AssessmentAttemptPublicSnapshot, error)
// SaveAnswerOutcome stores a successful answer response or deterministic
// not-found/state-conflict problem for its idempotency scope.
SaveAnswerOutcome(ctx context.Context, scope AssessmentAttemptIdempotencyScope, outcome AssessmentAttemptCommandOutcome) error
// GetAnswerOutcome returns the original typed answer outcome for a live key.
GetAnswerOutcome(ctx context.Context, scope AssessmentAttemptIdempotencyScope) (AssessmentAttemptCommandOutcome, error)
// SaveFinalizeOutcome stores a successful finalize response or deterministic
// not-found/state-conflict problem for its idempotency scope.
SaveFinalizeOutcome(ctx context.Context, scope AssessmentAttemptIdempotencyScope, outcome AssessmentAttemptCommandOutcome) error
// GetFinalizeOutcome returns the original typed finalize outcome for a live key.
GetFinalizeOutcome(ctx context.Context, scope AssessmentAttemptIdempotencyScope) (AssessmentAttemptCommandOutcome, error)
}
@@ -2,9 +2,12 @@ package outbound
import (
"context"
"crypto/sha256"
"errors"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
@@ -51,6 +54,13 @@ var (
// ErrAssessmentCatalogBindingImmutable reports an attempt to edit or remove
// an immutable reviewed catalog binding.
ErrAssessmentCatalogBindingImmutable = errors.New("assessment catalog binding is immutable")
// ErrAssessmentSelectionUnavailable reports that no current reviewed
// category exactly matches the requested public selection.
ErrAssessmentSelectionUnavailable = errors.New("assessment selection is unavailable")
// ErrAssessmentSelectionAmbiguous reports more than one current category
// matching the same public selection; the server never chooses arbitrarily.
ErrAssessmentSelectionAmbiguous = errors.New("assessment selection is ambiguous")
)
// MaxAssessmentFamilyPageSize is the largest page that ListFamilies returns.
@@ -64,6 +74,42 @@ type AssessmentFamilyCursor struct {
Version int32
}
// AssessmentBankSelection is the exact reviewed category manifest used to
// build one real attempt. Families are the entries from the pinned manifest,
// not an inferred snapshot of current rows.
type AssessmentBankSelection struct {
Opening domain.AssessmentCategoryOpening
ProductPolicyVersionID domain.PolicyVersionID
ProductPolicyVersion int32
ManifestSHA [sha256.Size]byte
Families []domain.AssessmentFamily
}
// AssessmentTrainingBankSelection is an explicitly reviewed, non-qualification
// family set pinned to one product policy version.
type AssessmentTrainingBankSelection struct {
BindingID uuid.UUID
Category domain.AssessmentCategory
ProductPolicyVersionID domain.PolicyVersionID
ProductPolicyVersion int32
ManifestSHA [sha256.Size]byte
Families []domain.AssessmentFamily
}
// AssessmentAvailabilitySelection is one current, reviewed specialization,
// grade, and language binding with the family keys from its verified live
// published manifest. It exposes no task content.
type AssessmentAvailabilitySelection struct {
OpeningID uuid.UUID
Category domain.AssessmentCategory
ProductPolicyVersionID domain.PolicyVersionID
ProductPolicyVersion int32
Specialization domain.SpecializationCode
Grade domain.GradeCode
TaskLanguages []domain.TaskLanguageCode
FamilyKeys []domain.AssessmentFamilyKey
}
// AssessmentBankRepositories exposes the assessment bank. UnitOfWork binds it
// to one transaction; an adapter may also provide it outside a transaction,
// where every call is its own statement. A returned family passed
@@ -139,6 +185,12 @@ type AssessmentBankRepository interface {
// coverage, or published-family manifest changed are omitted.
ListCurrentSpecializationAvailability(ctx context.Context) ([]domain.SpecializationAvailability, error)
// ListCurrentAssessmentAvailabilitySelections returns current, reviewed
// selection metadata pinned to the effective product policy at asOf. The
// implementation validates each live published-family manifest and does
// not take category locks or load task content.
ListCurrentAssessmentAvailabilitySelections(ctx context.Context, asOf time.Time) ([]AssessmentAvailabilitySelection, error)
// DatabaseTime returns the database clock. It stamps the effective time
// of a policy version, so the version in force now is judged against it
// and not against the application clock.
@@ -147,4 +199,22 @@ type AssessmentBankRepository interface {
// GetCurrentCategoryOpening returns the newest opening of the category,
// or ErrAssessmentCategoryNotOpen.
GetCurrentCategoryOpening(ctx context.Context, category domain.AssessmentCategory) (domain.AssessmentCategoryOpening, error)
// ResolveCurrentSelection finds exactly one current catalog binding for
// the public request, locks its category, and rechecks the opening, product
// policy, live manifest, and exact family versions under that lock.
ResolveCurrentSelection(
ctx context.Context,
specialization domain.SpecializationCode,
grade domain.GradeCode,
language *domain.TaskLanguageCode,
) (AssessmentBankSelection, error)
// ResolveCurrentTrainingSelection returns exactly one reviewed training
// binding whose policy pin and published family manifest remain current.
ResolveCurrentTrainingSelection(
ctx context.Context,
productPolicyID domain.PolicyVersionID,
productPolicyVersion int32,
) (AssessmentTrainingBankSelection, error)
}
@@ -0,0 +1,26 @@
package outbound
import (
"context"
"errors"
"time"
"lincodex/backend/internal/domain"
)
var ErrAssessmentSignalOutcomeNotFound = errors.New("assessment signal outcome not found")
type AssessmentSignalRepositories interface {
AssessmentSignals() AssessmentSignalRepository
}
// AssessmentSignalRepository persists event metadata and the immutable
// candidate receipt in the current unit of work.
type AssessmentSignalRepository interface {
CountRecentOutcomes(ctx context.Context, attemptID domain.AssessmentAttemptID, since time.Time) (int64, time.Time, error)
CountAttemptEvents(ctx context.Context, attemptID domain.AssessmentAttemptID) (int64, error)
SaveBatch(ctx context.Context, batch domain.AssessmentSignalBatch) error
SaveOutcome(ctx context.Context, scope AssessmentAttemptIdempotencyScope, attemptID domain.AssessmentAttemptID, receipt domain.AssessmentSignalReceipt) error
DeleteExpiredOutcome(ctx context.Context, scope AssessmentAttemptIdempotencyScope) error
GetOutcome(ctx context.Context, scope AssessmentAttemptIdempotencyScope) (domain.AssessmentSignalReceipt, error)
}
@@ -151,6 +151,13 @@ type ConsentLedger interface {
// CurrentContact.
Current(ctx context.Context, subjectID uuid.UUID, purpose domain.ConsentPurpose) (domain.ConsentRecord, error)
// LockCurrentForUse returns and share-locks the current C3 record for the
// subject. A caller that authorizes a real automated assessment must use it
// inside the same transaction that creates or mutates that assessment. The
// lock serializes the operation with C3 revocation until commit. Missing C3
// returns ErrConsentNotFound; other purposes return domain.ErrInvalidConsent.
LockCurrentForUse(ctx context.Context, subjectID uuid.UUID, purpose domain.ConsentPurpose) (domain.ConsentRecord, error)
// LockRegistration returns and locks the active registration C1 for one
// registration version, or ErrConsentNotFound. Email confirmation calls it
// inside the same transaction after consuming the token and applying the
+47
View File
@@ -3,6 +3,7 @@ package outbound
import (
"context"
"errors"
"time"
"github.com/google/uuid"
@@ -21,12 +22,21 @@ var (
// surrounding transaction remains safe to roll back and the API maps the
// conflict to its current 412 contract.
ErrNeedVersionConflict = errors.New("organization need changed concurrently")
// ErrNeedCreationResultNotFound reports a missing immutable response for a
// live idempotency record.
ErrNeedCreationResultNotFound = errors.New("organization need creation result not found")
)
// MaxNeedPageSize is the largest organization-scoped page in the contract.
const MaxNeedPageSize = 100
// NeedRepositories exposes tenant-scoped need storage bound to one
// UnitOfWork transaction.
type NeedRepositories interface {
Needs() NeedRepository
NeedLists() NeedListRepository
NeedCreationResults() NeedCreationResultRepository
}
// NeedRepository stores the current organization need and its immutable
@@ -48,3 +58,40 @@ type NeedRepository interface {
// rolls back both writes if either write fails.
Save(ctx context.Context, organizationID, needID uuid.UUID, expectedVersion int64, next domain.Need) error
}
// NeedListRepository reads one bounded, organization-scoped page of needs.
type NeedListRepository interface {
List(ctx context.Context, query NeedListQuery) (NeedPage, error)
}
// NeedCreationResultRepository stores the immutable public result produced by
// a successful idempotent create command. The scope references the generic
// idempotency record, so it is removed when that record is purged.
type NeedCreationResultRepository interface {
SaveCreationResult(ctx context.Context, scope [IdempotencyDigestSize]byte, snapshot domain.NeedResponseSnapshot) error
GetCreationResult(ctx context.Context, scope [IdempotencyDigestSize]byte) (domain.NeedResponseSnapshot, error)
}
// NeedListQuery selects one page within a single organization.
type NeedListQuery struct {
OrganizationID uuid.UUID
After *NeedListPosition
Limit int32
}
// NeedListPosition is the stable newest-first ordering key for pagination.
type NeedListPosition struct {
CreatedAt time.Time
NeedID uuid.UUID
}
// NeedPage contains one organization-scoped page of needs.
type NeedPage struct {
Items []domain.Need
HasMore bool
}
// NeedCreationPosition returns the pagination key for one need.
func NeedCreationPosition(need domain.Need) NeedListPosition {
return NeedListPosition{CreatedAt: need.CreatedAt(), NeedID: need.ID()}
}
@@ -87,6 +87,14 @@ type OrganizationRepository interface {
// suspended, removed, or left.
GetForMember(ctx context.Context, organizationID, userID uuid.UUID) (domain.Organization, domain.Membership, error)
// LockActiveMembership locks the organization row first, then the active
// membership row, through the surrounding transaction. Writers that act on
// owner access use it to serialize against membership revocation and keep
// the same organization-then-membership lock order as profile updates. It
// returns ErrOrganizationNotFound for an unknown organization or an
// account without an active membership.
LockActiveMembership(ctx context.Context, organizationID, userID uuid.UUID) (domain.Membership, error)
// ListForUser returns one page of the organizations where the account has
// an active membership, newest membership first.
ListForUser(ctx context.Context, query OrganizationListQuery) (OrganizationPage, error)
@@ -0,0 +1,21 @@
package outbound
import (
"context"
"errors"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
var ErrPrivacyCohortUnavailable = errors.New("anonymous candidate cohort unavailable")
// PrivacyCohortRepository reads the candidates eligible for one
// organization-scoped anonymous projection. The caller must first authorize
// an active organization membership. The adapter must select from
// candidate_effective_publications and exclude the reading organization's
// hidden candidates in the same SQL statement.
type PrivacyCohortRepository interface {
ListVisibleCandidateViewSources(ctx context.Context, organizationID uuid.UUID) ([]domain.CandidateViewSource, error)
}
@@ -0,0 +1,110 @@
package outbound
import (
"context"
"errors"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
var (
ErrCandidatePrivacySettingsNotFound = errors.New("candidate privacy settings not found")
ErrCandidatePrivacyOrganizationNotVisible = errors.New("organization is not visible to candidate")
ErrCandidateHiddenOrganizationLimit = errors.New("candidate hidden organization limit reached")
)
const MaxPrivacyPageSize = 100
// CandidatePrivacySettings is the candidate-owned visibility snapshot from
// one repository read.
type CandidatePrivacySettings struct {
Publication domain.Publication
SearchStatus domain.SearchStatus
HiddenCount int64
AsOf time.Time
}
// CandidateVisibleOrganization contains only the public organization details
// that a candidate may already read.
type CandidateVisibleOrganization struct {
ID uuid.UUID
Name string
}
// HiddenOrganizationRecord is one owner-visible hiding and its current public
// organization name.
type HiddenOrganizationRecord struct {
OrganizationID uuid.UUID
OrganizationName string
HiddenAt time.Time
}
type HiddenOrganizationListQuery struct {
UserID uuid.UUID
After *HiddenOrganizationPosition
Limit int32
}
type HiddenOrganizationPosition struct {
HiddenAt time.Time
OrganizationID uuid.UUID
}
type HiddenOrganizationPage struct {
Items []HiddenOrganizationRecord
HasMore bool
}
type CandidatePrivacyEventRecord struct {
ID uuid.UUID
Kind domain.PrivacyEventKind
OccurredAt time.Time
Fields *domain.CardFieldSet
ConsentRecordID uuid.UUID
OrganizationID uuid.UUID
OrganizationName string
}
type CandidatePrivacyEventListQuery struct {
UserID uuid.UUID
After *CandidatePrivacyEventPosition
Limit int32
}
type CandidatePrivacyEventPosition struct {
OccurredAt time.Time
ID uuid.UUID
}
type CandidatePrivacyEventPage struct {
Items []CandidatePrivacyEventRecord
HasMore bool
}
// PrivacySettingsRepository reads and changes only a candidate's visibility
// settings. Mutation methods are transaction-bound through UnitOfWork.
type PrivacySettingsRepository interface {
ReadSettings(ctx context.Context, userID uuid.UUID) (CandidatePrivacySettings, error)
LockCurrentC2ForPublication(ctx context.Context, userID uuid.UUID) (uuid.UUID, error)
SavePublication(ctx context.Context, publication domain.Publication, expectedVersion int64) error
SaveSearchStatus(ctx context.Context, status domain.SearchStatus, expectedVersion int64, at time.Time) error
CountHiddenOrganizations(ctx context.Context, userID uuid.UUID) (int64, error)
GetHiddenOrganization(ctx context.Context, userID, organizationID uuid.UUID) (HiddenOrganizationRecord, error)
CandidateCanSeeOrganization(ctx context.Context, userID, organizationID uuid.UUID) (CandidateVisibleOrganization, error)
HideOrganization(ctx context.Context, hidden domain.HiddenOrganization) (created bool, err error)
UnhideOrganization(ctx context.Context, userID, organizationID uuid.UUID) (deleted bool, err error)
ListHiddenOrganizations(ctx context.Context, query HiddenOrganizationListQuery) (HiddenOrganizationPage, error)
RecordPrivacyEvent(ctx context.Context, event domain.PrivacyEvent) error
ListPrivacyEvents(ctx context.Context, query CandidatePrivacyEventListQuery) (CandidatePrivacyEventPage, error)
}
func HiddenOrganizationPositionOf(record HiddenOrganizationRecord) HiddenOrganizationPosition {
return HiddenOrganizationPosition{HiddenAt: record.HiddenAt, OrganizationID: record.OrganizationID}
}
func CandidatePrivacyEventPositionOf(record CandidatePrivacyEventRecord) CandidatePrivacyEventPosition {
return CandidatePrivacyEventPosition{OccurredAt: record.OccurredAt, ID: record.ID}
}
@@ -0,0 +1,107 @@
package outbound
import (
"context"
"errors"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
var (
ErrCandidateCardAccessNotFound = errors.New("candidate card access not found")
ErrCandidateC2Unavailable = errors.New("candidate C2 publication is unavailable")
ErrContactAccessClosed = errors.New("contact access is closed")
)
const MaxCandidateCardAccessPageSize = 100
// PrivacyViewRepository adds the transaction-bound locks, owner preview, and
// access audit operations needed by candidate-card reads. Employer reads must
// lock candidate state in this order: account, current C2, publication.
type PrivacyViewRepository interface {
PrivacyCohortRepository
ContactAccessRepository
// LockCandidateAccountForView conflicts with the account lock used by the
// hidden-organization limit trigger. It keeps a hide from committing while
// a card read is authorized.
LockCandidateAccountForView(ctx context.Context, candidateID uuid.UUID) error
// LockCurrentC2ForView returns and share-locks the newest active C2 record.
// Revocation either completes before this call and is observed as missing,
// or waits until the read transaction commits.
LockCurrentC2ForView(ctx context.Context, candidateID uuid.UUID) (uuid.UUID, error)
// LockVisiblePublicationForView share-locks the publication and its C2 row
// only while the candidate remains published, backed by c2RecordID, and
// not hidden from organizationID.
LockVisiblePublicationForView(ctx context.Context, organizationID, candidateID, c2RecordID uuid.UUID) (bool, error)
// LockPublicationForPreview locks the candidate's currently effective own
// publication without applying any employer hiding or cohort context.
LockPublicationForPreview(ctx context.Context, candidateID uuid.UUID) (bool, error)
// ReadCandidateViewSourceForPreview reads the current private projection
// inputs after the caller locks the effective C2 and publication.
ReadCandidateViewSourceForPreview(ctx context.Context, candidateID uuid.UUID) (domain.CandidateViewSource, error)
// RecordCandidateCardAccess appends the access audit in the same transaction
// as the quota reservation and visibility check.
RecordCandidateCardAccess(ctx context.Context, access domain.CandidateCardAccess) error
// ListCandidateCardAccess returns one owner-scoped page, newest first.
ListCandidateCardAccess(ctx context.Context, query CandidateCardAccessListQuery) (CandidateCardAccessListPage, error)
}
// ContactAccessRepository is the transaction-bound final read boundary for
// contact values. The implementation must lock the current invitation grant
// and its matching C4 through the caller's transaction, then return only the
// allowlisted fields. A workflow status is never evidence of a grant.
type ContactAccessRepository interface {
CurrentFields(ctx context.Context, organizationID, candidateID uuid.UUID) (domain.ContactFieldSet, error)
// CloseForVisibility synchronously closes current grants for the candidate
// and, when organizationID is nonzero, only that organization. It must run
// in the same transaction as the visibility change. A later publication or
// unhide never reopens a closed grant.
CloseForVisibility(ctx context.Context, candidateID, organizationID uuid.UUID, at time.Time) error
}
// ClosedContactAccessRepository is the production default until the separate
// invitation-grant persistence is implemented.
type ClosedContactAccessRepository struct{}
func (ClosedContactAccessRepository) CurrentFields(context.Context, uuid.UUID, uuid.UUID) (domain.ContactFieldSet, error) {
return domain.ContactFieldSet{}, ErrContactAccessClosed
}
func (ClosedContactAccessRepository) CloseForVisibility(context.Context, uuid.UUID, uuid.UUID, time.Time) error {
return nil
}
// CandidateCardAccessListQuery selects one candidate-owned history page.
type CandidateCardAccessListQuery struct {
CandidateID uuid.UUID
After *CandidateCardAccessPosition
Limit int32
}
// CandidateCardAccessPosition is the descending access history key.
type CandidateCardAccessPosition struct {
OccurredAt time.Time
ID uuid.UUID
}
// CandidateCardAccessListPage is one page of the candidate's access history.
type CandidateCardAccessListPage struct {
Items []domain.CandidateCardAccess
OrganizationNames map[uuid.UUID]string
HasMore bool
}
// CandidateCardAccessPositionOf creates the continuation key for an event.
func CandidateCardAccessPositionOf(access domain.CandidateCardAccess) CandidateCardAccessPosition {
return CandidateCardAccessPosition{OccurredAt: access.OccurredAt(), ID: access.ID()}
}
@@ -0,0 +1,159 @@
package outbound
import (
"context"
"errors"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
var (
// ErrSupportCaseNotFound covers both an unknown case and one owned by
// another account.
ErrSupportCaseNotFound = errors.New("support case not found")
// ErrSupportCaseCreateOutcomeNotFound reports a live idempotency record
// without its immutable create result. It is an integrity error, not a
// public 404 response.
ErrSupportCaseCreateOutcomeNotFound = errors.New("support case create outcome not found")
// ErrSupportCaseConflict reports an appeal or another case that conflicts
// with a still-current business rule. The repository leaves the
// transaction usable so the caller can persist the immutable 409 outcome.
ErrSupportCaseConflict = errors.New("support case conflicts with existing state")
)
// MaxSupportCasePageSize matches the largest list page in the API contract.
const MaxSupportCasePageSize = 100
// SupportCaseRepositories groups the ports that a create transaction must
// bind to one unit of work. The caller also uses the existing idempotency
// repository in that same transaction.
type SupportCaseRepositories interface {
SupportCases() SupportCaseRepository
SupportCaseCreateOutcomes() SupportCaseCreateOutcomeRepository
SupportCaseRequestLimits() SupportCaseRequestLimitRepository
SupportCaseRubrics() SupportCaseRubricRepository
}
// SupportCaseRepository stores owner-private snapshots and their public
// history. Implementations persist only the typed object reference, not a
// copy of the referenced object, and every read names the owning account.
type SupportCaseRepository interface {
// NextNumber allocates a globally unique, never-reused display number for
// the UTC year containing createdAt. The number is for display; case paths
// use the UUID identifier.
NextNumber(ctx context.Context, createdAt time.Time) (domain.SupportCaseNumber, error)
// Create inserts the case and its complete initial public history in the
// surrounding transaction. A failed create leaves neither committed.
Create(ctx context.Context, supportCase domain.SupportCase) error
// GetOwned returns the full case only when ownerID matches. Unknown and
// foreign IDs both return ErrSupportCaseNotFound.
GetOwned(ctx context.Context, ownerID uuid.UUID, caseID domain.SupportCaseID) (domain.SupportCase, error)
// ListOwned returns one page of summaries for ownerID, newest first by
// CreatedAt and then ID. It never returns descriptions or event history.
ListOwned(ctx context.Context, query SupportCaseListQuery) (SupportCaseListPage, error)
}
// SupportCaseCreateOutcomeRepository persists the original response for a
// live generic idempotency scope. The stored case snapshot is immutable even
// if the case later receives replies or changes status.
type SupportCaseCreateOutcomeRepository interface {
// DeleteCreateOutcome removes the expired result for a scope that the
// generic idempotency repository has just accepted as new. It must run in
// the same transaction as the replacement command.
DeleteCreateOutcome(ctx context.Context, scope [IdempotencyDigestSize]byte) error
// SaveCreateOutcome stores a 201, 404, or domain state_conflict 409 result
// in the surrounding transaction. Rejected validation, CSRF, rate-limit,
// idempotency-in-progress, and key-reuse responses are not stored. The
// scope is the HMAC digest from Idempotency-Key handling; raw keys and
// request content never reach this port.
SaveCreateOutcome(
ctx context.Context,
scope [IdempotencyDigestSize]byte,
outcome domain.SupportCaseCreateOutcome,
createdAt time.Time,
) error
// GetCreateOutcome returns the original result for a live idempotency
// scope, or ErrSupportCaseCreateOutcomeNotFound if the record is incomplete.
GetCreateOutcome(ctx context.Context, scope [IdempotencyDigestSize]byte) (domain.SupportCaseCreateOutcome, error)
}
// SupportCaseRequestLimitRepository enforces the per-account rolling request
// budget. It is called after authentication, request validation, and account
// scenario checks but before idempotency lookup or object resolution, so an
// accepted replay and requests ending in 404 or 409 consume the same budget.
// Implementations retain accepted request events for at least
// domain.MaxSupportRequestWindow, even when the current product policy uses a
// shorter window, so a later policy version can widen the window safely.
// The use case must commit this counter for domain-level 400 and idempotency
// 422 results that occur after this check, while leaving their create outcome
// unstored; it returns those expected results as data and maps them to HTTP
// only after the unit of work commits.
type SupportCaseRequestLimitRepository interface {
// LockOwner serializes the account's request-budget check before the
// application timestamp is captured. The lock lasts until the enclosing
// unit of work commits or rolls back. It returns the latest committed
// request timestamp, or zero when the account has no request history, so a
// temporarily regressing application clock cannot move the effective
// window behind an event already counted.
LockOwner(ctx context.Context, ownerID uuid.UUID) (time.Time, error)
// Consume records one qualifying request when the preceding rolling
// window has fewer than maxRequests. The caller must acquire LockOwner
// before supplying at. It returns Allowed=false and a
// positive RetryAfter when the budget is exhausted. Rejected over-limit
// requests do not increment the counter. Count only events with
// requested_at > at-window and requested_at <= at; calculate RetryAfter
// from the oldest event included in that count.
Consume(
ctx context.Context,
ownerID uuid.UUID,
at time.Time,
maxRequests int32,
window time.Duration,
) (SupportCaseRequestLimitResult, error)
}
// SupportCaseRequestLimitResult describes whether this request consumed a
// slot in the account's rolling request budget.
type SupportCaseRequestLimitResult struct {
Allowed bool
RetryAfter time.Duration
}
// SupportCaseListQuery selects one owner-scoped page.
type SupportCaseListQuery struct {
OwnerID uuid.UUID
// After continues after the last item from the preceding page; nil reads
// the newest cases.
After *SupportCaseListPosition
// Limit is from 1 to MaxSupportCasePageSize.
Limit int32
}
// SupportCaseListPosition is the descending order key for one list item.
type SupportCaseListPosition struct {
CreatedAt time.Time
ID domain.SupportCaseID
}
// SupportCaseListPage is one page of summaries. HasMore is true when another
// page follows and the caller can continue from the last item's position.
type SupportCaseListPage struct {
Items []domain.SupportCaseSummary
HasMore bool
}
// SupportCasePositionOf returns the cursor position of an item from a page.
func SupportCasePositionOf(item domain.SupportCaseSummary) SupportCaseListPosition {
return SupportCaseListPosition{CreatedAt: item.CreatedAt, ID: item.ID}
}
@@ -0,0 +1,29 @@
package outbound
import (
"context"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
)
// SupportCaseRubric pins a manual request to the same grading-policy version
// and reviewed category opening used by automated assessment.
type SupportCaseRubric struct {
Version int32
OpeningID uuid.UUID
PolicyVersionID domain.PolicyVersionID
}
// SupportCaseRubricRepository resolves a rubric for manual assessment cases.
// A case has no task-language field, so implementations match all current
// reviewed catalog bindings for its exact specialization and grade. They
// return nil when no unique current opening matches.
type SupportCaseRubricRepository interface {
ResolveCurrent(
ctx context.Context,
specialization domain.SpecializationCode,
grade domain.GradeCode,
) (*SupportCaseRubric, error)
}
@@ -45,6 +45,13 @@ type Transactor interface {
WithinTransaction(ctx context.Context, fn func(ctx context.Context, unit UnitOfWork) error) error
}
// ReadOnlySnapshotTransactor runs one read operation against a consistent,
// read-only database snapshot. It is separate from Transactor so write
// usecases and their implementations do not silently change isolation.
type ReadOnlySnapshotTransactor interface {
WithinReadOnlySnapshot(ctx context.Context, fn func(ctx context.Context, unit UnitOfWork) error) error
}
// UnitOfWork exposes repositories bound to one transaction. Product
// repositories are added here as their usecases appear.
type UnitOfWork interface {
@@ -52,12 +59,18 @@ type UnitOfWork interface {
ConsentRepositories
CandidateProfileRepositories
CandidateQuestionnaireRepositories
PrivacyCohort() PrivacyCohortRepository
PrivacyView() PrivacyViewRepository
PrivacySettings() PrivacySettingsRepository
AccountDeletionRequests() AccountDeletionRequests
ConsentRevocationEffects() ConsentRevocationEffects
OrganizationRepositories
NeedRepositories
CompanyQuotas() CompanyQuotaRepository
AssessmentBankRepositories
AssessmentAttemptRepositories
AssessmentSignalRepositories
SupportCaseRepositories
Policies() PolicyRepository
Deliveries() DeliveryRepository
MailRequests() MailRequestRepository