feat: add assessment, privacy and support flows
This commit is contained in:
1 parent
ee3738ee73
commit
e4f24fa202
339 files changed
+56454
-1126
No files matched your search
@@ -33,6 +33,7 @@ var regexMap = map[string]ogenregex.Regexp{
|
||||
"^\\S(?:.*\\S)?$": ogenregex.MustCompile("^\\S(?:.*\\S)?$"),
|
||||
"^\\S(?:[^\\n\\r]*\\S)?$": ogenregex.MustCompile("^\\S(?:[^\\n\\r]*\\S)?$"),
|
||||
"^__Host-lincodex_session=": ogenregex.MustCompile("^__Host-lincodex_session="),
|
||||
"^cv1_[A-Za-z0-9_-]{43}$": ogenregex.MustCompile("^cv1_[A-Za-z0-9_-]{43}$"),
|
||||
"^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$": ogenregex.MustCompile("^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$"),
|
||||
}
|
||||
var (
|
||||
|
||||
@@ -2503,9 +2503,10 @@ func (s *Server) handleDeclineMyInvitationRequest(args [1]string, argsEscaped bo
|
||||
// transition answers 200 with the stored `completed` attempt; a GET never commits it.
|
||||
//
|
||||
// An attempt in `in_progress` or `practice_pending`, one with a practice verdict `pending`, or one
|
||||
// that ended as `expired` or `insufficient_bank` answers 409 state_conflict. The problem does not list
|
||||
// what is unfinished; the attempt shows it in `state`, `progress`, `current_item`, and `practices`. A
|
||||
// stale `expected_version` answers 412 version_conflict, the repository status for a stale version.
|
||||
// that ended as `expired` or `insufficient_bank` answers 409 state_conflict. When required questions
|
||||
// are unfinished, the problem includes their frozen IDs in `pending_item_ids`; other state conflicts
|
||||
// omit that field. A stale `expected_version` answers 412 version_conflict, the repository status for
|
||||
// a stale version.
|
||||
//
|
||||
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
|
||||
// account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay),
|
||||
@@ -4057,21 +4058,22 @@ func (s *Server) handleGetMyAssessmentResultRequest(args [1]string, argsEscaped
|
||||
|
||||
// handleGetMyCardPreviewRequest handles GetMyCardPreview operation.
|
||||
//
|
||||
// Requires the session cookie of a candidate account. Returns the card exactly as an organization that
|
||||
// the candidate does not hide the profile from would read it now, built from the current profile, the
|
||||
// current publication, and the consent ledger. The response is `Cache-Control: no-store`.
|
||||
// Requires the session cookie of a candidate account. Returns a private preview of the permitted
|
||||
// anonymous-card fields from the current profile, publication, and consent ledger. The response is
|
||||
// `Cache-Control: no-store`.
|
||||
//
|
||||
// The preview is a private read for the candidate: it creates no view, leaves no access record, and is
|
||||
// never shown to an organization. While the profile is closed `card` is null. `card` is
|
||||
// `AnonymousCardContent`, whose schema reaches no private profile schema, no contact, and no
|
||||
// identifier of the candidate: it has no name, email, phone, Telegram name, employer, salary figure,
|
||||
// or account or profile identifier, and each property is null when it is not published or has no
|
||||
// value, so a reader cannot tell the two apart. Only the fields in `fields` are filled, and only with
|
||||
// values that the candidate confirmed: an unconfirmed suggestion and an unknown value never appear. A
|
||||
// free text value that looks like a contact (an email address, a phone number, a URL, a Telegram link,
|
||||
// an @handle) is dropped from the card, so the preview shows exactly what an organization would read.
|
||||
// The self-assessed grade is not a category and never appears; categories come only from assessment
|
||||
// results.
|
||||
// The preview creates no view or access record and is never shown to an organization. While the
|
||||
// profile is closed `card` is null. Its pseudonym uses a separate preview context and is not an
|
||||
// organization's pseudonym. Organization-specific visibility filters and cohort checks can further
|
||||
// generalize or suppress the card when an organization reads it.
|
||||
//
|
||||
// `card` is the closed `AnonymousCardContent` projection. It reaches no private profile or contact
|
||||
// schema and contains no name, email, phone, Telegram name, employer, salary figure, account
|
||||
// identifier, or profile identifier. Unpublished or unknown values are null. Only allowed canonical
|
||||
// skills and generalized experience are exposed; arbitrary profile text and imported excerpts never
|
||||
// appear. `categories` contains only confirmed assessment results. Self-assessed grades and work
|
||||
// formats appear only through their separate explicit publication choices, and self-assessment never
|
||||
// becomes a confirmed category. Salary compatibility is nullable and contains no salary amount.
|
||||
//
|
||||
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account
|
||||
// answers 403 forbidden.
|
||||
@@ -5713,6 +5715,234 @@ func (s *Server) handleGetOrganizationRequest(args [1]string, argsEscaped bool,
|
||||
}
|
||||
}
|
||||
|
||||
// handleGetOrganizationCandidateCardRequest handles GetOrganizationCandidateCard operation.
|
||||
//
|
||||
// Requires the session cookie of an employer account with an active membership in `org_id`. The
|
||||
// organization and membership come from the current server-side session and path, never from cached
|
||||
// search data.
|
||||
//
|
||||
// `candidate_handle` is the organization-scoped opaque alias issued by the current anonymous-card
|
||||
// projection. The server resolves it against the current visible cohort, rechecks active membership,
|
||||
// effective C2 publication, and the candidate's hiding settings on every request, and applies the
|
||||
// cohort suppression rules again. It does not use a previously cached candidate ID. An unknown handle,
|
||||
// a handle from another organization, a closed or revoked publication, a profile hidden from this
|
||||
// organization, and a profile suppressed by the minimum cohort all answer the same 404 not_found.
|
||||
//
|
||||
// The response contains only the anonymous card allowlist. It has no contact values. Contacts, if ever
|
||||
// available, are a separate operation and require the current explicit C4 grant and contact-access
|
||||
// policy; a workflow status alone never grants contact access. Closing C2 or hiding the profile blocks
|
||||
// this read immediately. Republishing does not reopen an earlier contact grant.
|
||||
//
|
||||
// Every allowed employer card read is recorded in the access history and consumes the organization's
|
||||
// current product-policy card-view quota. A repeated view within the quota window is allowed by the
|
||||
// existing distinct-card quota rule. When the quota is exhausted the operation answers 429 with
|
||||
// Retry-After. The response is `Cache-Control: no-store`.
|
||||
//
|
||||
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account
|
||||
// answers 403 forbidden; an unknown organization or account without an active membership answers 404
|
||||
// not_found. An `org_id` that is not a UUID or a malformed candidate handle answers 400
|
||||
// validation_failed.
|
||||
//
|
||||
// GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}
|
||||
func (s *Server) handleGetOrganizationCandidateCardRequest(args [2]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
|
||||
statusWriter := &codeRecorder{ResponseWriter: w}
|
||||
w = statusWriter
|
||||
otelAttrs := []attribute.KeyValue{
|
||||
otelogen.OperationID("GetOrganizationCandidateCard"),
|
||||
semconv.HTTPRequestMethodKey.String("GET"),
|
||||
semconv.HTTPRouteKey.String("/api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}"),
|
||||
}
|
||||
// Add attributes from config.
|
||||
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
|
||||
|
||||
// Start a span for this request.
|
||||
ctx, span := s.cfg.Tracer.Start(r.Context(), GetOrganizationCandidateCardOperation,
|
||||
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: GetOrganizationCandidateCardOperation,
|
||||
ID: "GetOrganizationCandidateCard",
|
||||
}
|
||||
)
|
||||
{
|
||||
type bitset = [1]uint8
|
||||
var satisfied bitset
|
||||
{
|
||||
sctx, ok, err := s.securitySessionCookie(ctx, GetOrganizationCandidateCardOperation, 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 := decodeGetOrganizationCandidateCardParams(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 GetOrganizationCandidateCardRes
|
||||
if m := s.cfg.Middleware; m != nil {
|
||||
mreq := middleware.Request{
|
||||
Context: ctx,
|
||||
OperationName: GetOrganizationCandidateCardOperation,
|
||||
OperationSummary: "Read one currently visible anonymous candidate card.",
|
||||
OperationID: "GetOrganizationCandidateCard",
|
||||
Body: nil,
|
||||
RawBody: rawBody,
|
||||
Params: middleware.Parameters{
|
||||
{
|
||||
Name: "org_id",
|
||||
In: "path",
|
||||
}: params.OrgID,
|
||||
{
|
||||
Name: "candidate_handle",
|
||||
In: "path",
|
||||
}: params.CandidateHandle,
|
||||
},
|
||||
Raw: r,
|
||||
}
|
||||
|
||||
type (
|
||||
Request = struct{}
|
||||
Params = GetOrganizationCandidateCardParams
|
||||
Response = GetOrganizationCandidateCardRes
|
||||
)
|
||||
response, err = middleware.HookMiddleware[
|
||||
Request,
|
||||
Params,
|
||||
Response,
|
||||
](
|
||||
m,
|
||||
mreq,
|
||||
unpackGetOrganizationCandidateCardParams,
|
||||
func(ctx context.Context, request Request, params Params) (response Response, err error) {
|
||||
response, err = s.h.GetOrganizationCandidateCard(ctx, params)
|
||||
return response, err
|
||||
},
|
||||
)
|
||||
} else {
|
||||
response, err = s.h.GetOrganizationCandidateCard(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 := encodeGetOrganizationCandidateCardResponse(response, w, span); err != nil {
|
||||
defer recordError("EncodeResponse", err)
|
||||
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// handleGetOrganizationInvitationRequest handles GetOrganizationInvitation operation.
|
||||
//
|
||||
// Requires the session cookie of an employer account with an active membership in `org_id`. The
|
||||
@@ -6800,11 +7030,12 @@ func (s *Server) handleGrantMyConsentRequest(args [1]string, argsEscaped bool, w
|
||||
// Anti-enumeration: an organization that does not exist and an organization that the candidate cannot
|
||||
// see answer the same 404 not_found, with the same body and without a timing or an error code that
|
||||
// tells them apart, so the operation is not a way to ask whether an identifier belongs to an
|
||||
// organization. The candidate can see an organization that has sent them an invitation, and the
|
||||
// organizations that a candidate lookup will list (planned; see the open questions of the contract).
|
||||
// The response names the organization only after that check, with its current name. The identifiers
|
||||
// are random, the general rate limit applies and can answer 429 with Retry-After before any check, and
|
||||
// the record never reveals to an organization that a candidate hides it.
|
||||
// organization. The candidate may name an organization in their own card-access history or an existing
|
||||
// hidden-organization record. Invitation visibility will be added with the invitation workflow, and a
|
||||
// candidate lookup remains planned. The response names the organization only after that check, with
|
||||
// its current name. The identifiers are random, the general rate limit applies and can answer 429 with
|
||||
// Retry-After before any check, and the record never reveals to an organization that a candidate hides
|
||||
// it.
|
||||
//
|
||||
// A candidate hides at most 1000 organizations; hiding one more answers 409 state_conflict with the
|
||||
// entry `{in: path, pointer: /org_id, code: limit_reached}` in `errors`, which tells it apart from
|
||||
@@ -7042,16 +7273,15 @@ func (s *Server) handleHideOrganizationRequest(args [1]string, argsEscaped bool,
|
||||
//
|
||||
// An access is a view of the anonymous card by an organization (`card_viewed`) or a read of the
|
||||
// contacts through an active contact grant (`contact_read`). Reading the history is not an access and
|
||||
// writes nothing. A view of the card by an organization that has no invitation relation with the
|
||||
// candidate carries `organization` null, so the candidate sees that the card was viewed without
|
||||
// learning a company that they cannot otherwise see; a contact read always names the organization,
|
||||
// because the candidate accepted its invitation. The entries carry no search query, filter, or ranking
|
||||
// of the organization, and no organization the candidate hides ever appears as a viewer, because a
|
||||
// hidden organization cannot read the card.
|
||||
// writes nothing. A retained access record permits the candidate to see the organization's identifier
|
||||
// and current name and to hide their profile from it. The nullable organization field is preserved for
|
||||
// records whose organization cannot be presented. The entries carry no employee identity, search
|
||||
// query, filter, or ranking of the organization. Hiding an organization prevents future reads; it does
|
||||
// not erase earlier permitted accesses from the history.
|
||||
//
|
||||
// The storage of accesses is planned with the card and contact operations of the organization side
|
||||
// (anonymous card reads and contact reads under the invitation contract); until then the operation
|
||||
// answers 501 not_implemented after the session and request checks.
|
||||
// Successful organization card reads are recorded transactionally with the visibility and quota
|
||||
// checks. Contact-read records require the invitation grant workflow, which is not implemented yet; an
|
||||
// accepted workflow status alone never authorizes contact access.
|
||||
//
|
||||
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account
|
||||
// answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed.
|
||||
@@ -9674,6 +9904,263 @@ func (s *Server) handleRaiseOrganizationInvitationSalaryRequest(args [2]string,
|
||||
}
|
||||
}
|
||||
|
||||
// handleRecordMyAssessmentAttemptSignalsRequest handles RecordMyAssessmentAttemptSignals operation.
|
||||
//
|
||||
// Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and an
|
||||
// Idempotency-Key. The attempt must belong to the candidate, be a real root or corrective attempt,
|
||||
// remain active, and have a current C3 consent. The server locks C3 before locking the attempt, checks
|
||||
// every item_instance_id against that attempt, and commits the receipt and any events in one
|
||||
// transaction. A terminal, expired, or demo_express attempt accepts no new evidence; demo_express
|
||||
// remains a separate training mode and receives no signal storage or grade effect.
|
||||
//
|
||||
// The contract accepts only focus-loss duration, copy/paste/cut byte counts, fullscreen exits, item
|
||||
// identifiers, and untrusted client timestamps. It never accepts answer text, clipboard contents,
|
||||
// arbitrary strings, camera, microphone, screen recordings, screenshots, or organization identifiers.
|
||||
// Client timestamps must be within five minutes before attempt creation and five minutes after the
|
||||
// database receipt clock. Server receipt time controls rolling rate limits. Signal events are removed
|
||||
// with the assessment attempt or account; this release does not promise an independent expiry
|
||||
// schedule. Signals do not change scores, categories, quotas, or candidate/employer result responses.
|
||||
//
|
||||
// A batch has at most 50 events and the raw request body is limited to 32 KiB before decoding. At most
|
||||
// 30 new receipts per candidate and attempt are accepted in a rolling minute; an over-limit request
|
||||
// answers 429 and does not consume its idempotency key. Storage is capped at 10,000 events per
|
||||
// attempt. If the whole batch would exceed that cap, the server stores no events from it and replays a
|
||||
// `saturated` receipt. Repeating the same key and body within 24 hours returns the original receipt
|
||||
// without storing another batch; using that key with another body answers 422.
|
||||
//
|
||||
// POST /api/v1/me/assessment-attempts/{attempt_id}/signals
|
||||
func (s *Server) handleRecordMyAssessmentAttemptSignalsRequest(args [1]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
|
||||
statusWriter := &codeRecorder{ResponseWriter: w}
|
||||
w = statusWriter
|
||||
otelAttrs := []attribute.KeyValue{
|
||||
otelogen.OperationID("RecordMyAssessmentAttemptSignals"),
|
||||
semconv.HTTPRequestMethodKey.String("POST"),
|
||||
semconv.HTTPRouteKey.String("/api/v1/me/assessment-attempts/{attempt_id}/signals"),
|
||||
}
|
||||
// Add attributes from config.
|
||||
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
|
||||
|
||||
// Start a span for this request.
|
||||
ctx, span := s.cfg.Tracer.Start(r.Context(), RecordMyAssessmentAttemptSignalsOperation,
|
||||
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: RecordMyAssessmentAttemptSignalsOperation,
|
||||
ID: "RecordMyAssessmentAttemptSignals",
|
||||
}
|
||||
)
|
||||
{
|
||||
type bitset = [1]uint8
|
||||
var satisfied bitset
|
||||
{
|
||||
sctx, ok, err := s.securitySessionCookie(ctx, RecordMyAssessmentAttemptSignalsOperation, 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, RecordMyAssessmentAttemptSignalsOperation, 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 := decodeRecordMyAssessmentAttemptSignalsParams(args, argsEscaped, r)
|
||||
if err != nil {
|
||||
err = &ogenerrors.DecodeParamsError{
|
||||
OperationContext: opErrContext,
|
||||
Err: err,
|
||||
}
|
||||
defer recordError("DecodeParams", err)
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
return
|
||||
}
|
||||
|
||||
var rawBody []byte
|
||||
request, rawBody, close, err := s.decodeRecordMyAssessmentAttemptSignalsRequest(r)
|
||||
if err != nil {
|
||||
err = &ogenerrors.DecodeRequestError{
|
||||
OperationContext: opErrContext,
|
||||
Err: err,
|
||||
}
|
||||
defer recordError("DecodeRequest", err)
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
if err := close(); err != nil {
|
||||
recordError("CloseRequest", err)
|
||||
}
|
||||
}()
|
||||
|
||||
var response RecordMyAssessmentAttemptSignalsRes
|
||||
if m := s.cfg.Middleware; m != nil {
|
||||
mreq := middleware.Request{
|
||||
Context: ctx,
|
||||
OperationName: RecordMyAssessmentAttemptSignalsOperation,
|
||||
OperationSummary: "Store a bounded batch of client-reported assessment signals.",
|
||||
OperationID: "RecordMyAssessmentAttemptSignals",
|
||||
Body: request,
|
||||
RawBody: rawBody,
|
||||
Params: middleware.Parameters{
|
||||
{
|
||||
Name: "attempt_id",
|
||||
In: "path",
|
||||
}: params.AttemptID,
|
||||
{
|
||||
Name: "Idempotency-Key",
|
||||
In: "header",
|
||||
}: params.IdempotencyKey,
|
||||
},
|
||||
Raw: r,
|
||||
}
|
||||
|
||||
type (
|
||||
Request = *AssessmentSignalBatch
|
||||
Params = RecordMyAssessmentAttemptSignalsParams
|
||||
Response = RecordMyAssessmentAttemptSignalsRes
|
||||
)
|
||||
response, err = middleware.HookMiddleware[
|
||||
Request,
|
||||
Params,
|
||||
Response,
|
||||
](
|
||||
m,
|
||||
mreq,
|
||||
unpackRecordMyAssessmentAttemptSignalsParams,
|
||||
func(ctx context.Context, request Request, params Params) (response Response, err error) {
|
||||
response, err = s.h.RecordMyAssessmentAttemptSignals(ctx, request, params)
|
||||
return response, err
|
||||
},
|
||||
)
|
||||
} else {
|
||||
response, err = s.h.RecordMyAssessmentAttemptSignals(ctx, request, params)
|
||||
}
|
||||
if err != nil {
|
||||
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
|
||||
if err := encodeErrorResponse(errRes, w, span); err != nil {
|
||||
defer recordError("Internal", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if errors.Is(err, ht.ErrNotImplemented) {
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
return
|
||||
}
|
||||
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
|
||||
defer recordError("Internal", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if err := encodeRecordMyAssessmentAttemptSignalsResponse(response, w, span); err != nil {
|
||||
defer recordError("EncodeResponse", err)
|
||||
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// handleRegisterAccountRequest handles RegisterAccount operation.
|
||||
//
|
||||
// Public operation without a session. The client reads the current C1 text with GetConsentText and
|
||||
|
||||
@@ -93,6 +93,10 @@ type GetMySupportCaseRes interface {
|
||||
getMySupportCaseRes()
|
||||
}
|
||||
|
||||
type GetOrganizationCandidateCardRes interface {
|
||||
getOrganizationCandidateCardRes()
|
||||
}
|
||||
|
||||
type GetOrganizationInvitationContactsRes interface {
|
||||
getOrganizationInvitationContactsRes()
|
||||
}
|
||||
@@ -165,6 +169,10 @@ type RaiseOrganizationInvitationSalaryRes interface {
|
||||
raiseOrganizationInvitationSalaryRes()
|
||||
}
|
||||
|
||||
type RecordMyAssessmentAttemptSignalsRes interface {
|
||||
recordMyAssessmentAttemptSignalsRes()
|
||||
}
|
||||
|
||||
type RegisterAccountRes interface {
|
||||
registerAccountRes()
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -31,6 +31,7 @@ const (
|
||||
GetMyQuestionnaireOperation OperationName = "GetMyQuestionnaire"
|
||||
GetMySupportCaseOperation OperationName = "GetMySupportCase"
|
||||
GetOrganizationOperation OperationName = "GetOrganization"
|
||||
GetOrganizationCandidateCardOperation OperationName = "GetOrganizationCandidateCard"
|
||||
GetOrganizationInvitationOperation OperationName = "GetOrganizationInvitation"
|
||||
GetOrganizationInvitationContactsOperation OperationName = "GetOrganizationInvitationContacts"
|
||||
GetOrganizationNeedOperation OperationName = "GetOrganizationNeed"
|
||||
@@ -49,6 +50,7 @@ const (
|
||||
LoginOperation OperationName = "Login"
|
||||
LogoutOperation OperationName = "Logout"
|
||||
RaiseOrganizationInvitationSalaryOperation OperationName = "RaiseOrganizationInvitationSalary"
|
||||
RecordMyAssessmentAttemptSignalsOperation OperationName = "RecordMyAssessmentAttemptSignals"
|
||||
RegisterAccountOperation OperationName = "RegisterAccount"
|
||||
RequestMyAccountDeletionOperation OperationName = "RequestMyAccountDeletion"
|
||||
ResendEmailVerificationOperation OperationName = "ResendEmailVerification"
|
||||
|
||||
@@ -1776,6 +1776,147 @@ func decodeGetOrganizationParams(args [1]string, argsEscaped bool, r *http.Reque
|
||||
return params, nil
|
||||
}
|
||||
|
||||
// GetOrganizationCandidateCardParams is parameters of GetOrganizationCandidateCard operation.
|
||||
type GetOrganizationCandidateCardParams 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
|
||||
// Organization-scoped opaque candidate alias issued by the current visible card projection. The server
|
||||
// resolves it only for the organization in the path and rechecks current membership, publication
|
||||
// consent, and hiding on every read. Unknown, hidden, unpublished, and suppressed candidates all
|
||||
// answer the same 404.
|
||||
CandidateHandle CandidateHandle
|
||||
}
|
||||
|
||||
func unpackGetOrganizationCandidateCardParams(packed middleware.Parameters) (params GetOrganizationCandidateCardParams) {
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "org_id",
|
||||
In: "path",
|
||||
}
|
||||
params.OrgID = packed[key].(uuid.UUID)
|
||||
}
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "candidate_handle",
|
||||
In: "path",
|
||||
}
|
||||
params.CandidateHandle = packed[key].(CandidateHandle)
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
func decodeGetOrganizationCandidateCardParams(args [2]string, argsEscaped bool, r *http.Request) (params GetOrganizationCandidateCardParams, _ 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: candidate_handle.
|
||||
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: "candidate_handle",
|
||||
Value: param,
|
||||
Style: uri.PathStyleSimple,
|
||||
Explode: false,
|
||||
})
|
||||
|
||||
if err := func() error {
|
||||
var paramsDotCandidateHandleVal string
|
||||
if err := func() error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToString(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
paramsDotCandidateHandleVal = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
params.CandidateHandle = CandidateHandle(paramsDotCandidateHandleVal)
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := func() error {
|
||||
if err := params.CandidateHandle.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return validate.ErrFieldRequired
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "candidate_handle",
|
||||
In: "path",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
return params, nil
|
||||
}
|
||||
|
||||
// GetOrganizationInvitationParams is parameters of GetOrganizationInvitation operation.
|
||||
type GetOrganizationInvitationParams struct {
|
||||
// Identifier of an organization. Access comes only from an active membership of the session account in
|
||||
@@ -4263,6 +4404,155 @@ func decodeRaiseOrganizationInvitationSalaryParams(args [2]string, argsEscaped b
|
||||
return params, nil
|
||||
}
|
||||
|
||||
// RecordMyAssessmentAttemptSignalsParams is parameters of RecordMyAssessmentAttemptSignals operation.
|
||||
type RecordMyAssessmentAttemptSignalsParams struct {
|
||||
// Identifier of an assessment attempt of the current candidate. An attempt of another candidate and an
|
||||
// unknown identifier both answer 404 not_found, so identifiers cannot be enumerated.
|
||||
AttemptID uuid.UUID
|
||||
// Client-generated key that makes a retried mutating command safe; a UUID v4 is recommended. The value
|
||||
// is sent without quotes. The server scopes the key by caller and operation and fingerprints the
|
||||
// request by method, path, and body.
|
||||
//
|
||||
// Stored for 24 hours after the first request and replayed with the same status, headers, and body:
|
||||
// the final 2xx outcome and final deterministic 4xx business outcomes of the command, such as 404
|
||||
// not_found or 409 state_conflict. A replay does not repeat the side effect.
|
||||
//
|
||||
// Not stored, so a retry with the same key is evaluated again: 400 validation_failed, 413, and 415 for
|
||||
// the request itself, 401 and 403, 409 idempotency_in_progress, 412 version_conflict and 428
|
||||
// precondition_required (nothing changed; read the resource again and retry), 422
|
||||
// idempotency_key_reused, 429, and every 5xx.
|
||||
//
|
||||
// Order of checks: authentication (401), request validation (400, 413, 415), authorization (403), then
|
||||
// the key. A stored or running request with a different fingerprint returns 422 idempotency_key_reused
|
||||
// before any other key check; a running request with the same fingerprint returns 409
|
||||
// idempotency_in_progress; a stored outcome with the same fingerprint is replayed. Only after that
|
||||
// does the server check If-Match, so a retry of a completed change replays its outcome instead of
|
||||
// failing on the version it has just changed. After 24 hours the key may be accepted as new.
|
||||
IdempotencyKey string
|
||||
}
|
||||
|
||||
func unpackRecordMyAssessmentAttemptSignalsParams(packed middleware.Parameters) (params RecordMyAssessmentAttemptSignalsParams) {
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "attempt_id",
|
||||
In: "path",
|
||||
}
|
||||
params.AttemptID = packed[key].(uuid.UUID)
|
||||
}
|
||||
{
|
||||
key := middleware.ParameterKey{
|
||||
Name: "Idempotency-Key",
|
||||
In: "header",
|
||||
}
|
||||
params.IdempotencyKey = packed[key].(string)
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
func decodeRecordMyAssessmentAttemptSignalsParams(args [1]string, argsEscaped bool, r *http.Request) (params RecordMyAssessmentAttemptSignalsParams, _ error) {
|
||||
h := uri.NewHeaderDecoder(r.Header)
|
||||
// Decode path: attempt_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: "attempt_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.AttemptID = c
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return validate.ErrFieldRequired
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "attempt_id",
|
||||
In: "path",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
// Decode header: Idempotency-Key.
|
||||
if err := func() error {
|
||||
cfg := uri.HeaderParameterDecodingConfig{
|
||||
Name: "Idempotency-Key",
|
||||
Explode: false,
|
||||
}
|
||||
if err := h.HasParam(cfg); err == nil {
|
||||
if err := h.DecodeParam(cfg, func(d uri.Decoder) error {
|
||||
val, err := d.DecodeValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c, err := conv.ToString(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
params.IdempotencyKey = c
|
||||
return nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := func() error {
|
||||
if err := (validate.String{
|
||||
MinLength: 1,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 255,
|
||||
MaxLengthSet: true,
|
||||
Email: false,
|
||||
Hostname: false,
|
||||
Regex: regexMap["^[A-Za-z0-9._:-]+$"],
|
||||
MinNumeric: 0,
|
||||
MinNumericSet: false,
|
||||
MaxNumeric: 0,
|
||||
MaxNumericSet: false,
|
||||
}).Validate(string(params.IdempotencyKey)); err != nil {
|
||||
return errors.Wrap(err, "string")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return params, &ogenerrors.DecodeParamError{
|
||||
Name: "Idempotency-Key",
|
||||
In: "header",
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
return params, nil
|
||||
}
|
||||
|
||||
// RegisterAccountParams is parameters of RegisterAccount operation.
|
||||
type RegisterAccountParams struct {
|
||||
// Client-generated key that makes a retried mutating command safe; a UUID v4 is recommended. The value
|
||||
|
||||
@@ -1041,6 +1041,85 @@ func (s *Server) decodeRaiseOrganizationInvitationSalaryRequest(r *http.Request)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) decodeRecordMyAssessmentAttemptSignalsRequest(r *http.Request) (
|
||||
req *AssessmentSignalBatch,
|
||||
rawBody []byte,
|
||||
close func() error,
|
||||
rerr error,
|
||||
) {
|
||||
var closers []func() error
|
||||
close = func() error {
|
||||
var merr error
|
||||
// Close in reverse order, to match defer behavior.
|
||||
for i := len(closers) - 1; i >= 0; i-- {
|
||||
c := closers[i]
|
||||
merr = errors.Join(merr, c())
|
||||
}
|
||||
return merr
|
||||
}
|
||||
defer func() {
|
||||
if rerr != nil {
|
||||
rerr = errors.Join(rerr, close())
|
||||
}
|
||||
}()
|
||||
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return req, rawBody, close, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "application/json":
|
||||
if r.ContentLength == 0 {
|
||||
return req, rawBody, close, validate.ErrBodyRequired
|
||||
}
|
||||
buf, err := io.ReadAll(r.Body)
|
||||
defer func() {
|
||||
_ = r.Body.Close()
|
||||
}()
|
||||
if err != nil {
|
||||
return req, rawBody, close, err
|
||||
}
|
||||
|
||||
// Reset the body to allow for downstream reading.
|
||||
r.Body = io.NopCloser(bytes.NewBuffer(buf))
|
||||
|
||||
if len(buf) == 0 {
|
||||
return req, rawBody, close, validate.ErrBodyRequired
|
||||
}
|
||||
|
||||
rawBody = append(rawBody, buf...)
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var request AssessmentSignalBatch
|
||||
if err := func() error {
|
||||
if err := request.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Skip(); err != io.EOF {
|
||||
return errors.New("unexpected trailing data")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
err = &ogenerrors.DecodeBodyError{
|
||||
ContentType: ct,
|
||||
Body: buf,
|
||||
Err: err,
|
||||
}
|
||||
return req, rawBody, close, err
|
||||
}
|
||||
if err := func() error {
|
||||
if err := request.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return req, rawBody, close, errors.Wrap(err, "validate")
|
||||
}
|
||||
return &request, rawBody, close, nil
|
||||
default:
|
||||
return req, rawBody, close, validate.InvalidContentType(ct)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) decodeRegisterAccountRequest(r *http.Request) (
|
||||
req *RegistrationRequest,
|
||||
rawBody []byte,
|
||||
|
||||
@@ -1291,7 +1291,7 @@ func encodeFinalizeMyAssessmentAttemptResponse(response FinalizeMyAssessmentAtte
|
||||
|
||||
return nil
|
||||
|
||||
case *FinalizeMyAssessmentAttemptConflict:
|
||||
case *AssessmentFinalizeConflictProblem:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(409)
|
||||
|
||||
@@ -2215,6 +2215,121 @@ func encodeGetOrganizationResponse(response GetOrganizationRes, w http.ResponseW
|
||||
}
|
||||
}
|
||||
|
||||
func encodeGetOrganizationCandidateCardResponse(response GetOrganizationCandidateCardRes, w http.ResponseWriter, span trace.Span) error {
|
||||
switch response := response.(type) {
|
||||
case *AnonymousCardContentHeaders:
|
||||
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 *GetOrganizationCandidateCardBadRequest:
|
||||
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 *GetOrganizationCandidateCardUnauthorized:
|
||||
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 *GetOrganizationCandidateCardForbidden:
|
||||
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 *GetOrganizationCandidateCardNotFound:
|
||||
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 encodeGetOrganizationInvitationResponse(response GetOrganizationInvitationRes, w http.ResponseWriter, span trace.Span) error {
|
||||
switch response := response.(type) {
|
||||
case *OrganizationInvitationHeaders:
|
||||
@@ -3651,6 +3766,157 @@ func encodeRaiseOrganizationInvitationSalaryResponse(response RaiseOrganizationI
|
||||
}
|
||||
}
|
||||
|
||||
func encodeRecordMyAssessmentAttemptSignalsResponse(response RecordMyAssessmentAttemptSignalsRes, w http.ResponseWriter, span trace.Span) error {
|
||||
switch response := response.(type) {
|
||||
case *AssessmentSignalReceiptHeaders:
|
||||
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 *RecordMyAssessmentAttemptSignalsBadRequest:
|
||||
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 *RecordMyAssessmentAttemptSignalsUnauthorized:
|
||||
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 *RecordMyAssessmentAttemptSignalsForbidden:
|
||||
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 *RecordMyAssessmentAttemptSignalsNotFound:
|
||||
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 *RecordMyAssessmentAttemptSignalsConflict:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(409)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *RecordMyAssessmentAttemptSignalsRequestEntityTooLarge:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(413)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *RecordMyAssessmentAttemptSignalsUnprocessableEntity:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(422)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *TooManyRequestsHeaders:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.Header().Set("Access-Control-Expose-Headers", "Retry-After")
|
||||
// Encoding response headers.
|
||||
{
|
||||
h := uri.NewHeaderEncoder(w.Header())
|
||||
// Encode "Retry-After" header.
|
||||
{
|
||||
cfg := uri.HeaderParameterEncodingConfig{
|
||||
Name: "Retry-After",
|
||||
Explode: false,
|
||||
}
|
||||
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
|
||||
if val, ok := response.RetryAfter.Get(); ok {
|
||||
return e.EncodeValue(conv.Int32ToString(val))
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return errors.Wrap(err, "encode Retry-After header")
|
||||
}
|
||||
}
|
||||
}
|
||||
w.WriteHeader(429)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
default:
|
||||
return errors.Errorf("unexpected response type: %T", response)
|
||||
}
|
||||
}
|
||||
|
||||
func encodeRegisterAccountResponse(response RegisterAccountRes, w http.ResponseWriter, span trace.Span) error {
|
||||
switch response := response.(type) {
|
||||
case *IdentityRequestAccepted:
|
||||
|
||||
@@ -11,40 +11,43 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
rn66AllowedHeaders = map[string]string{
|
||||
rn69AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type",
|
||||
}
|
||||
rn7AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Origin",
|
||||
}
|
||||
rn62AllowedHeaders = map[string]string{
|
||||
rn65AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key",
|
||||
}
|
||||
rn59AllowedHeaders = map[string]string{
|
||||
rn61AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type",
|
||||
}
|
||||
rn25AllowedHeaders = map[string]string{
|
||||
"DELETE": "X-Csrf-Token",
|
||||
}
|
||||
rn64AllowedHeaders = map[string]string{
|
||||
rn67AllowedHeaders = map[string]string{
|
||||
"POST": "X-Csrf-Token",
|
||||
}
|
||||
rn9AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn75AllowedHeaders = map[string]string{
|
||||
rn79AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn20AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn74AllowedHeaders = map[string]string{
|
||||
rn78AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn68AllowedHeaders = map[string]string{
|
||||
rn64AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn71AllowedHeaders = map[string]string{
|
||||
"DELETE": "X-Csrf-Token",
|
||||
}
|
||||
rn48AllowedHeaders = map[string]string{
|
||||
rn50AllowedHeaders = map[string]string{
|
||||
"DELETE": "X-Csrf-Token",
|
||||
"PUT": "Content-Type,X-Csrf-Token",
|
||||
}
|
||||
@@ -57,17 +60,17 @@ var (
|
||||
rn17AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn76AllowedHeaders = map[string]string{
|
||||
rn80AllowedHeaders = map[string]string{
|
||||
"POST": "X-Csrf-Token",
|
||||
}
|
||||
rn51AllowedHeaders = map[string]string{
|
||||
rn53AllowedHeaders = map[string]string{
|
||||
"DELETE": "X-Csrf-Token",
|
||||
"PUT": "X-Csrf-Token",
|
||||
}
|
||||
rn72AllowedHeaders = map[string]string{
|
||||
rn75AllowedHeaders = map[string]string{
|
||||
"PUT": "Content-Type,X-Csrf-Token",
|
||||
}
|
||||
rn73AllowedHeaders = map[string]string{
|
||||
rn76AllowedHeaders = map[string]string{
|
||||
"PUT": "Content-Type,X-Csrf-Token",
|
||||
}
|
||||
rn36AllowedHeaders = map[string]string{
|
||||
@@ -88,22 +91,22 @@ var (
|
||||
rn14AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn41AllowedHeaders = map[string]string{
|
||||
rn43AllowedHeaders = map[string]string{
|
||||
"PATCH": "Content-Type,X-Csrf-Token",
|
||||
}
|
||||
rn61AllowedHeaders = map[string]string{
|
||||
rn63AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn70AllowedHeaders = map[string]string{
|
||||
rn73AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn77AllowedHeaders = map[string]string{
|
||||
rn81AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn16AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn44AllowedHeaders = map[string]string{
|
||||
rn46AllowedHeaders = map[string]string{
|
||||
"PATCH": "Content-Type,X-Csrf-Token",
|
||||
}
|
||||
)
|
||||
@@ -260,7 +263,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: "",
|
||||
})
|
||||
@@ -337,7 +340,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn62AllowedHeaders,
|
||||
allowedHeaders: rn65AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -361,7 +364,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn59AllowedHeaders,
|
||||
allowedHeaders: rn61AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -441,7 +444,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn64AllowedHeaders,
|
||||
allowedHeaders: rn67AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -551,7 +554,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn75AllowedHeaders,
|
||||
allowedHeaders: rn79AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -614,31 +617,72 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
case 's': // Prefix: "sessions"
|
||||
case 's': // Prefix: "s"
|
||||
|
||||
if l := len("sessions"); len(elem) >= l && elem[0:l] == "sessions" {
|
||||
if l := len("s"); len(elem) >= l && elem[0:l] == "s" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch r.Method {
|
||||
case "POST":
|
||||
s.handleStartMyAssessmentAttemptSessionRequest([1]string{
|
||||
args[0],
|
||||
}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn74AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case 'e': // Prefix: "essions"
|
||||
|
||||
if l := len("essions"); len(elem) >= l && elem[0:l] == "essions" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch r.Method {
|
||||
case "POST":
|
||||
s.handleStartMyAssessmentAttemptSessionRequest([1]string{
|
||||
args[0],
|
||||
}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn78AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
case 'i': // Prefix: "ignals"
|
||||
|
||||
if l := len("ignals"); len(elem) >= l && elem[0:l] == "ignals" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch r.Method {
|
||||
case "POST":
|
||||
s.handleRecordMyAssessmentAttemptSignalsRequest([1]string{
|
||||
args[0],
|
||||
}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn64AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
@@ -787,7 +831,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "DELETE",
|
||||
allowedHeaders: rn68AllowedHeaders,
|
||||
allowedHeaders: rn71AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -821,7 +865,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "DELETE,PUT",
|
||||
allowedHeaders: rn48AllowedHeaders,
|
||||
allowedHeaders: rn50AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -1004,7 +1048,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn76AllowedHeaders,
|
||||
allowedHeaders: rn80AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -1184,7 +1228,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "DELETE,PUT",
|
||||
allowedHeaders: rn51AllowedHeaders,
|
||||
allowedHeaders: rn53AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -1275,7 +1319,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "PUT",
|
||||
allowedHeaders: rn72AllowedHeaders,
|
||||
allowedHeaders: rn75AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -1302,7 +1346,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "PUT",
|
||||
allowedHeaders: rn73AllowedHeaders,
|
||||
allowedHeaders: rn76AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -1512,6 +1556,43 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case 'c': // Prefix: "candidate-cards/"
|
||||
|
||||
if l := len("candidate-cards/"); len(elem) >= l && elem[0:l] == "candidate-cards/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
// Param: "candidate_handle"
|
||||
// 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.handleGetOrganizationCandidateCardRequest([2]string{
|
||||
args[0],
|
||||
args[1],
|
||||
}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "GET",
|
||||
allowedHeaders: nil,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
case 'i': // Prefix: "invitations"
|
||||
|
||||
if l := len("invitations"); len(elem) >= l && elem[0:l] == "invitations" {
|
||||
@@ -1574,7 +1655,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "GET,PATCH",
|
||||
allowedHeaders: rn41AllowedHeaders,
|
||||
allowedHeaders: rn43AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "application/json",
|
||||
})
|
||||
@@ -1654,7 +1735,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn61AllowedHeaders,
|
||||
allowedHeaders: rn63AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -1682,7 +1763,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn70AllowedHeaders,
|
||||
allowedHeaders: rn73AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -1712,7 +1793,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn77AllowedHeaders,
|
||||
allowedHeaders: rn81AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -1790,7 +1871,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "GET,PATCH",
|
||||
allowedHeaders: rn44AllowedHeaders,
|
||||
allowedHeaders: rn46AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "application/json",
|
||||
})
|
||||
@@ -2384,29 +2465,68 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
|
||||
}
|
||||
}
|
||||
|
||||
case 's': // Prefix: "sessions"
|
||||
case 's': // Prefix: "s"
|
||||
|
||||
if l := len("sessions"); len(elem) >= l && elem[0:l] == "sessions" {
|
||||
if l := len("s"); len(elem) >= l && elem[0:l] == "s" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch method {
|
||||
case "POST":
|
||||
r.name = StartMyAssessmentAttemptSessionOperation
|
||||
r.summary = "Start or resume a work session for the current candidate's attempt."
|
||||
r.operationID = "StartMyAssessmentAttemptSession"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/sessions"
|
||||
r.args = args
|
||||
r.count = 1
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case 'e': // Prefix: "essions"
|
||||
|
||||
if l := len("essions"); len(elem) >= l && elem[0:l] == "essions" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch method {
|
||||
case "POST":
|
||||
r.name = StartMyAssessmentAttemptSessionOperation
|
||||
r.summary = "Start or resume a work session for the current candidate's attempt."
|
||||
r.operationID = "StartMyAssessmentAttemptSession"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/sessions"
|
||||
r.args = args
|
||||
r.count = 1
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
case 'i': // Prefix: "ignals"
|
||||
|
||||
if l := len("ignals"); len(elem) >= l && elem[0:l] == "ignals" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch method {
|
||||
case "POST":
|
||||
r.name = RecordMyAssessmentAttemptSignalsOperation
|
||||
r.summary = "Store a bounded batch of client-reported assessment signals."
|
||||
r.operationID = "RecordMyAssessmentAttemptSignals"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/api/v1/me/assessment-attempts/{attempt_id}/signals"
|
||||
r.args = args
|
||||
r.count = 1
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -3294,6 +3414,40 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case 'c': // Prefix: "candidate-cards/"
|
||||
|
||||
if l := len("candidate-cards/"); len(elem) >= l && elem[0:l] == "candidate-cards/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
// Param: "candidate_handle"
|
||||
// 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 = GetOrganizationCandidateCardOperation
|
||||
r.summary = "Read one currently visible anonymous candidate card."
|
||||
r.operationID = "GetOrganizationCandidateCard"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}"
|
||||
r.args = args
|
||||
r.count = 2
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
case 'i': // Prefix: "invitations"
|
||||
|
||||
if l := len("invitations"); len(elem) >= l && elem[0:l] == "invitations" {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -78,6 +78,7 @@ var operationRolesSessionCookie = map[string][]string{
|
||||
GetMyQuestionnaireOperation: []string{},
|
||||
GetMySupportCaseOperation: []string{},
|
||||
GetOrganizationOperation: []string{},
|
||||
GetOrganizationCandidateCardOperation: []string{},
|
||||
GetOrganizationInvitationOperation: []string{},
|
||||
GetOrganizationInvitationContactsOperation: []string{},
|
||||
GetOrganizationNeedOperation: []string{},
|
||||
@@ -94,6 +95,7 @@ var operationRolesSessionCookie = map[string][]string{
|
||||
ListOrganizationNeedsOperation: []string{},
|
||||
LogoutOperation: []string{},
|
||||
RaiseOrganizationInvitationSalaryOperation: []string{},
|
||||
RecordMyAssessmentAttemptSignalsOperation: []string{},
|
||||
RequestMyAccountDeletionOperation: []string{},
|
||||
RevokeMyConsentOperation: []string{},
|
||||
RevokeMyOrganizationContactConsentOperation: []string{},
|
||||
@@ -148,6 +150,7 @@ var operationRolesSessionCsrf = map[string][]string{
|
||||
HideOrganizationOperation: []string{},
|
||||
LogoutOperation: []string{},
|
||||
RaiseOrganizationInvitationSalaryOperation: []string{},
|
||||
RecordMyAssessmentAttemptSignalsOperation: []string{},
|
||||
RequestMyAccountDeletionOperation: []string{},
|
||||
RevokeMyConsentOperation: []string{},
|
||||
RevokeMyOrganizationContactConsentOperation: []string{},
|
||||
|
||||
@@ -479,9 +479,10 @@ type Handler interface {
|
||||
// transition answers 200 with the stored `completed` attempt; a GET never commits it.
|
||||
//
|
||||
// An attempt in `in_progress` or `practice_pending`, one with a practice verdict `pending`, or one
|
||||
// that ended as `expired` or `insufficient_bank` answers 409 state_conflict. The problem does not list
|
||||
// what is unfinished; the attempt shows it in `state`, `progress`, `current_item`, and `practices`. A
|
||||
// stale `expected_version` answers 412 version_conflict, the repository status for a stale version.
|
||||
// that ended as `expired` or `insufficient_bank` answers 409 state_conflict. When required questions
|
||||
// are unfinished, the problem includes their frozen IDs in `pending_item_ids`; other state conflicts
|
||||
// omit that field. A stale `expected_version` answers 412 version_conflict, the repository status for
|
||||
// a stale version.
|
||||
//
|
||||
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
|
||||
// account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay),
|
||||
@@ -600,21 +601,22 @@ type Handler interface {
|
||||
GetMyAssessmentResult(ctx context.Context, params GetMyAssessmentResultParams) (GetMyAssessmentResultRes, error)
|
||||
// GetMyCardPreview implements GetMyCardPreview operation.
|
||||
//
|
||||
// Requires the session cookie of a candidate account. Returns the card exactly as an organization that
|
||||
// the candidate does not hide the profile from would read it now, built from the current profile, the
|
||||
// current publication, and the consent ledger. The response is `Cache-Control: no-store`.
|
||||
// Requires the session cookie of a candidate account. Returns a private preview of the permitted
|
||||
// anonymous-card fields from the current profile, publication, and consent ledger. The response is
|
||||
// `Cache-Control: no-store`.
|
||||
//
|
||||
// The preview is a private read for the candidate: it creates no view, leaves no access record, and is
|
||||
// never shown to an organization. While the profile is closed `card` is null. `card` is
|
||||
// `AnonymousCardContent`, whose schema reaches no private profile schema, no contact, and no
|
||||
// identifier of the candidate: it has no name, email, phone, Telegram name, employer, salary figure,
|
||||
// or account or profile identifier, and each property is null when it is not published or has no
|
||||
// value, so a reader cannot tell the two apart. Only the fields in `fields` are filled, and only with
|
||||
// values that the candidate confirmed: an unconfirmed suggestion and an unknown value never appear. A
|
||||
// free text value that looks like a contact (an email address, a phone number, a URL, a Telegram link,
|
||||
// an @handle) is dropped from the card, so the preview shows exactly what an organization would read.
|
||||
// The self-assessed grade is not a category and never appears; categories come only from assessment
|
||||
// results.
|
||||
// The preview creates no view or access record and is never shown to an organization. While the
|
||||
// profile is closed `card` is null. Its pseudonym uses a separate preview context and is not an
|
||||
// organization's pseudonym. Organization-specific visibility filters and cohort checks can further
|
||||
// generalize or suppress the card when an organization reads it.
|
||||
//
|
||||
// `card` is the closed `AnonymousCardContent` projection. It reaches no private profile or contact
|
||||
// schema and contains no name, email, phone, Telegram name, employer, salary figure, account
|
||||
// identifier, or profile identifier. Unpublished or unknown values are null. Only allowed canonical
|
||||
// skills and generalized experience are exposed; arbitrary profile text and imported excerpts never
|
||||
// appear. `categories` contains only confirmed assessment results. Self-assessed grades and work
|
||||
// formats appear only through their separate explicit publication choices, and self-assessment never
|
||||
// becomes a confirmed category. Salary compatibility is nullable and contains no salary amount.
|
||||
//
|
||||
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account
|
||||
// answers 403 forbidden.
|
||||
@@ -764,6 +766,36 @@ type Handler interface {
|
||||
//
|
||||
// GET /api/v1/organizations/{org_id}
|
||||
GetOrganization(ctx context.Context, params GetOrganizationParams) (GetOrganizationRes, error)
|
||||
// GetOrganizationCandidateCard implements GetOrganizationCandidateCard operation.
|
||||
//
|
||||
// Requires the session cookie of an employer account with an active membership in `org_id`. The
|
||||
// organization and membership come from the current server-side session and path, never from cached
|
||||
// search data.
|
||||
//
|
||||
// `candidate_handle` is the organization-scoped opaque alias issued by the current anonymous-card
|
||||
// projection. The server resolves it against the current visible cohort, rechecks active membership,
|
||||
// effective C2 publication, and the candidate's hiding settings on every request, and applies the
|
||||
// cohort suppression rules again. It does not use a previously cached candidate ID. An unknown handle,
|
||||
// a handle from another organization, a closed or revoked publication, a profile hidden from this
|
||||
// organization, and a profile suppressed by the minimum cohort all answer the same 404 not_found.
|
||||
//
|
||||
// The response contains only the anonymous card allowlist. It has no contact values. Contacts, if ever
|
||||
// available, are a separate operation and require the current explicit C4 grant and contact-access
|
||||
// policy; a workflow status alone never grants contact access. Closing C2 or hiding the profile blocks
|
||||
// this read immediately. Republishing does not reopen an earlier contact grant.
|
||||
//
|
||||
// Every allowed employer card read is recorded in the access history and consumes the organization's
|
||||
// current product-policy card-view quota. A repeated view within the quota window is allowed by the
|
||||
// existing distinct-card quota rule. When the quota is exhausted the operation answers 429 with
|
||||
// Retry-After. The response is `Cache-Control: no-store`.
|
||||
//
|
||||
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account
|
||||
// answers 403 forbidden; an unknown organization or account without an active membership answers 404
|
||||
// not_found. An `org_id` that is not a UUID or a malformed candidate handle answers 400
|
||||
// validation_failed.
|
||||
//
|
||||
// GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}
|
||||
GetOrganizationCandidateCard(ctx context.Context, params GetOrganizationCandidateCardParams) (GetOrganizationCandidateCardRes, error)
|
||||
// GetOrganizationInvitation implements GetOrganizationInvitation operation.
|
||||
//
|
||||
// Requires the session cookie of an employer account with an active membership in `org_id`. The
|
||||
@@ -901,11 +933,12 @@ type Handler interface {
|
||||
// Anti-enumeration: an organization that does not exist and an organization that the candidate cannot
|
||||
// see answer the same 404 not_found, with the same body and without a timing or an error code that
|
||||
// tells them apart, so the operation is not a way to ask whether an identifier belongs to an
|
||||
// organization. The candidate can see an organization that has sent them an invitation, and the
|
||||
// organizations that a candidate lookup will list (planned; see the open questions of the contract).
|
||||
// The response names the organization only after that check, with its current name. The identifiers
|
||||
// are random, the general rate limit applies and can answer 429 with Retry-After before any check, and
|
||||
// the record never reveals to an organization that a candidate hides it.
|
||||
// organization. The candidate may name an organization in their own card-access history or an existing
|
||||
// hidden-organization record. Invitation visibility will be added with the invitation workflow, and a
|
||||
// candidate lookup remains planned. The response names the organization only after that check, with
|
||||
// its current name. The identifiers are random, the general rate limit applies and can answer 429 with
|
||||
// Retry-After before any check, and the record never reveals to an organization that a candidate hides
|
||||
// it.
|
||||
//
|
||||
// A candidate hides at most 1000 organizations; hiding one more answers 409 state_conflict with the
|
||||
// entry `{in: path, pointer: /org_id, code: limit_reached}` in `errors`, which tells it apart from
|
||||
@@ -931,16 +964,15 @@ type Handler interface {
|
||||
//
|
||||
// An access is a view of the anonymous card by an organization (`card_viewed`) or a read of the
|
||||
// contacts through an active contact grant (`contact_read`). Reading the history is not an access and
|
||||
// writes nothing. A view of the card by an organization that has no invitation relation with the
|
||||
// candidate carries `organization` null, so the candidate sees that the card was viewed without
|
||||
// learning a company that they cannot otherwise see; a contact read always names the organization,
|
||||
// because the candidate accepted its invitation. The entries carry no search query, filter, or ranking
|
||||
// of the organization, and no organization the candidate hides ever appears as a viewer, because a
|
||||
// hidden organization cannot read the card.
|
||||
// writes nothing. A retained access record permits the candidate to see the organization's identifier
|
||||
// and current name and to hide their profile from it. The nullable organization field is preserved for
|
||||
// records whose organization cannot be presented. The entries carry no employee identity, search
|
||||
// query, filter, or ranking of the organization. Hiding an organization prevents future reads; it does
|
||||
// not erase earlier permitted accesses from the history.
|
||||
//
|
||||
// The storage of accesses is planned with the card and contact operations of the organization side
|
||||
// (anonymous card reads and contact reads under the invitation contract); until then the operation
|
||||
// answers 501 not_implemented after the session and request checks.
|
||||
// Successful organization card reads are recorded transactionally with the visibility and quota
|
||||
// checks. Contact-read records require the invitation grant workflow, which is not implemented yet; an
|
||||
// accepted workflow status alone never authorizes contact access.
|
||||
//
|
||||
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account
|
||||
// answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed.
|
||||
@@ -1189,6 +1221,32 @@ type Handler interface {
|
||||
//
|
||||
// POST /api/v1/organizations/{org_id}/invitations/{invitation_id}/salary-raise
|
||||
RaiseOrganizationInvitationSalary(ctx context.Context, req *InvitationSalaryRaise, params RaiseOrganizationInvitationSalaryParams) (RaiseOrganizationInvitationSalaryRes, error)
|
||||
// RecordMyAssessmentAttemptSignals implements RecordMyAssessmentAttemptSignals operation.
|
||||
//
|
||||
// Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and an
|
||||
// Idempotency-Key. The attempt must belong to the candidate, be a real root or corrective attempt,
|
||||
// remain active, and have a current C3 consent. The server locks C3 before locking the attempt, checks
|
||||
// every item_instance_id against that attempt, and commits the receipt and any events in one
|
||||
// transaction. A terminal, expired, or demo_express attempt accepts no new evidence; demo_express
|
||||
// remains a separate training mode and receives no signal storage or grade effect.
|
||||
//
|
||||
// The contract accepts only focus-loss duration, copy/paste/cut byte counts, fullscreen exits, item
|
||||
// identifiers, and untrusted client timestamps. It never accepts answer text, clipboard contents,
|
||||
// arbitrary strings, camera, microphone, screen recordings, screenshots, or organization identifiers.
|
||||
// Client timestamps must be within five minutes before attempt creation and five minutes after the
|
||||
// database receipt clock. Server receipt time controls rolling rate limits. Signal events are removed
|
||||
// with the assessment attempt or account; this release does not promise an independent expiry
|
||||
// schedule. Signals do not change scores, categories, quotas, or candidate/employer result responses.
|
||||
//
|
||||
// A batch has at most 50 events and the raw request body is limited to 32 KiB before decoding. At most
|
||||
// 30 new receipts per candidate and attempt are accepted in a rolling minute; an over-limit request
|
||||
// answers 429 and does not consume its idempotency key. Storage is capped at 10,000 events per
|
||||
// attempt. If the whole batch would exceed that cap, the server stores no events from it and replays a
|
||||
// `saturated` receipt. Repeating the same key and body within 24 hours returns the original receipt
|
||||
// without storing another batch; using that key with another body answers 422.
|
||||
//
|
||||
// POST /api/v1/me/assessment-attempts/{attempt_id}/signals
|
||||
RecordMyAssessmentAttemptSignals(ctx context.Context, req *AssessmentSignalBatch, params RecordMyAssessmentAttemptSignalsParams) (RecordMyAssessmentAttemptSignalsRes, error)
|
||||
// RegisterAccount implements RegisterAccount operation.
|
||||
//
|
||||
// Public operation without a session. The client reads the current C1 text with GetConsentText and
|
||||
|
||||
@@ -511,9 +511,10 @@ func (UnimplementedHandler) DeclineMyInvitation(ctx context.Context, req *Invita
|
||||
// transition answers 200 with the stored `completed` attempt; a GET never commits it.
|
||||
//
|
||||
// An attempt in `in_progress` or `practice_pending`, one with a practice verdict `pending`, or one
|
||||
// that ended as `expired` or `insufficient_bank` answers 409 state_conflict. The problem does not list
|
||||
// what is unfinished; the attempt shows it in `state`, `progress`, `current_item`, and `practices`. A
|
||||
// stale `expected_version` answers 412 version_conflict, the repository status for a stale version.
|
||||
// that ended as `expired` or `insufficient_bank` answers 409 state_conflict. When required questions
|
||||
// are unfinished, the problem includes their frozen IDs in `pending_item_ids`; other state conflicts
|
||||
// omit that field. A stale `expected_version` answers 412 version_conflict, the repository status for
|
||||
// a stale version.
|
||||
//
|
||||
// Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400),
|
||||
// account scenario (403 forbidden), the Idempotency-Key (422, 409 idempotency_in_progress, replay),
|
||||
@@ -656,21 +657,22 @@ func (UnimplementedHandler) GetMyAssessmentResult(ctx context.Context, params Ge
|
||||
|
||||
// GetMyCardPreview implements GetMyCardPreview operation.
|
||||
//
|
||||
// Requires the session cookie of a candidate account. Returns the card exactly as an organization that
|
||||
// the candidate does not hide the profile from would read it now, built from the current profile, the
|
||||
// current publication, and the consent ledger. The response is `Cache-Control: no-store`.
|
||||
// Requires the session cookie of a candidate account. Returns a private preview of the permitted
|
||||
// anonymous-card fields from the current profile, publication, and consent ledger. The response is
|
||||
// `Cache-Control: no-store`.
|
||||
//
|
||||
// The preview is a private read for the candidate: it creates no view, leaves no access record, and is
|
||||
// never shown to an organization. While the profile is closed `card` is null. `card` is
|
||||
// `AnonymousCardContent`, whose schema reaches no private profile schema, no contact, and no
|
||||
// identifier of the candidate: it has no name, email, phone, Telegram name, employer, salary figure,
|
||||
// or account or profile identifier, and each property is null when it is not published or has no
|
||||
// value, so a reader cannot tell the two apart. Only the fields in `fields` are filled, and only with
|
||||
// values that the candidate confirmed: an unconfirmed suggestion and an unknown value never appear. A
|
||||
// free text value that looks like a contact (an email address, a phone number, a URL, a Telegram link,
|
||||
// an @handle) is dropped from the card, so the preview shows exactly what an organization would read.
|
||||
// The self-assessed grade is not a category and never appears; categories come only from assessment
|
||||
// results.
|
||||
// The preview creates no view or access record and is never shown to an organization. While the
|
||||
// profile is closed `card` is null. Its pseudonym uses a separate preview context and is not an
|
||||
// organization's pseudonym. Organization-specific visibility filters and cohort checks can further
|
||||
// generalize or suppress the card when an organization reads it.
|
||||
//
|
||||
// `card` is the closed `AnonymousCardContent` projection. It reaches no private profile or contact
|
||||
// schema and contains no name, email, phone, Telegram name, employer, salary figure, account
|
||||
// identifier, or profile identifier. Unpublished or unknown values are null. Only allowed canonical
|
||||
// skills and generalized experience are exposed; arbitrary profile text and imported excerpts never
|
||||
// appear. `categories` contains only confirmed assessment results. Self-assessed grades and work
|
||||
// formats appear only through their separate explicit publication choices, and self-assessment never
|
||||
// becomes a confirmed category. Salary compatibility is nullable and contains no salary amount.
|
||||
//
|
||||
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account
|
||||
// answers 403 forbidden.
|
||||
@@ -844,6 +846,39 @@ func (UnimplementedHandler) GetOrganization(ctx context.Context, params GetOrgan
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// GetOrganizationCandidateCard implements GetOrganizationCandidateCard operation.
|
||||
//
|
||||
// Requires the session cookie of an employer account with an active membership in `org_id`. The
|
||||
// organization and membership come from the current server-side session and path, never from cached
|
||||
// search data.
|
||||
//
|
||||
// `candidate_handle` is the organization-scoped opaque alias issued by the current anonymous-card
|
||||
// projection. The server resolves it against the current visible cohort, rechecks active membership,
|
||||
// effective C2 publication, and the candidate's hiding settings on every request, and applies the
|
||||
// cohort suppression rules again. It does not use a previously cached candidate ID. An unknown handle,
|
||||
// a handle from another organization, a closed or revoked publication, a profile hidden from this
|
||||
// organization, and a profile suppressed by the minimum cohort all answer the same 404 not_found.
|
||||
//
|
||||
// The response contains only the anonymous card allowlist. It has no contact values. Contacts, if ever
|
||||
// available, are a separate operation and require the current explicit C4 grant and contact-access
|
||||
// policy; a workflow status alone never grants contact access. Closing C2 or hiding the profile blocks
|
||||
// this read immediately. Republishing does not reopen an earlier contact grant.
|
||||
//
|
||||
// Every allowed employer card read is recorded in the access history and consumes the organization's
|
||||
// current product-policy card-view quota. A repeated view within the quota window is allowed by the
|
||||
// existing distinct-card quota rule. When the quota is exhausted the operation answers 429 with
|
||||
// Retry-After. The response is `Cache-Control: no-store`.
|
||||
//
|
||||
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account
|
||||
// answers 403 forbidden; an unknown organization or account without an active membership answers 404
|
||||
// not_found. An `org_id` that is not a UUID or a malformed candidate handle answers 400
|
||||
// validation_failed.
|
||||
//
|
||||
// GET /api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}
|
||||
func (UnimplementedHandler) GetOrganizationCandidateCard(ctx context.Context, params GetOrganizationCandidateCardParams) (r GetOrganizationCandidateCardRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// GetOrganizationInvitation implements GetOrganizationInvitation operation.
|
||||
//
|
||||
// Requires the session cookie of an employer account with an active membership in `org_id`. The
|
||||
@@ -996,11 +1031,12 @@ func (UnimplementedHandler) GrantMyConsent(ctx context.Context, req *ConsentSett
|
||||
// Anti-enumeration: an organization that does not exist and an organization that the candidate cannot
|
||||
// see answer the same 404 not_found, with the same body and without a timing or an error code that
|
||||
// tells them apart, so the operation is not a way to ask whether an identifier belongs to an
|
||||
// organization. The candidate can see an organization that has sent them an invitation, and the
|
||||
// organizations that a candidate lookup will list (planned; see the open questions of the contract).
|
||||
// The response names the organization only after that check, with its current name. The identifiers
|
||||
// are random, the general rate limit applies and can answer 429 with Retry-After before any check, and
|
||||
// the record never reveals to an organization that a candidate hides it.
|
||||
// organization. The candidate may name an organization in their own card-access history or an existing
|
||||
// hidden-organization record. Invitation visibility will be added with the invitation workflow, and a
|
||||
// candidate lookup remains planned. The response names the organization only after that check, with
|
||||
// its current name. The identifiers are random, the general rate limit applies and can answer 429 with
|
||||
// Retry-After before any check, and the record never reveals to an organization that a candidate hides
|
||||
// it.
|
||||
//
|
||||
// A candidate hides at most 1000 organizations; hiding one more answers 409 state_conflict with the
|
||||
// entry `{in: path, pointer: /org_id, code: limit_reached}` in `errors`, which tells it apart from
|
||||
@@ -1029,16 +1065,15 @@ func (UnimplementedHandler) HideOrganization(ctx context.Context, params HideOrg
|
||||
//
|
||||
// An access is a view of the anonymous card by an organization (`card_viewed`) or a read of the
|
||||
// contacts through an active contact grant (`contact_read`). Reading the history is not an access and
|
||||
// writes nothing. A view of the card by an organization that has no invitation relation with the
|
||||
// candidate carries `organization` null, so the candidate sees that the card was viewed without
|
||||
// learning a company that they cannot otherwise see; a contact read always names the organization,
|
||||
// because the candidate accepted its invitation. The entries carry no search query, filter, or ranking
|
||||
// of the organization, and no organization the candidate hides ever appears as a viewer, because a
|
||||
// hidden organization cannot read the card.
|
||||
// writes nothing. A retained access record permits the candidate to see the organization's identifier
|
||||
// and current name and to hide their profile from it. The nullable organization field is preserved for
|
||||
// records whose organization cannot be presented. The entries carry no employee identity, search
|
||||
// query, filter, or ranking of the organization. Hiding an organization prevents future reads; it does
|
||||
// not erase earlier permitted accesses from the history.
|
||||
//
|
||||
// The storage of accesses is planned with the card and contact operations of the organization side
|
||||
// (anonymous card reads and contact reads under the invitation contract); until then the operation
|
||||
// answers 501 not_implemented after the session and request checks.
|
||||
// Successful organization card reads are recorded transactionally with the visibility and quota
|
||||
// checks. Contact-read records require the invitation grant workflow, which is not implemented yet; an
|
||||
// accepted workflow status alone never authorizes contact access.
|
||||
//
|
||||
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; an employer account
|
||||
// answers 403 forbidden. A malformed `limit` or `cursor` answers 400 validation_failed.
|
||||
@@ -1323,6 +1358,35 @@ func (UnimplementedHandler) RaiseOrganizationInvitationSalary(ctx context.Contex
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// RecordMyAssessmentAttemptSignals implements RecordMyAssessmentAttemptSignals operation.
|
||||
//
|
||||
// Requires a candidate session, its CSRF token in X-CSRF-Token, an allowed Origin, and an
|
||||
// Idempotency-Key. The attempt must belong to the candidate, be a real root or corrective attempt,
|
||||
// remain active, and have a current C3 consent. The server locks C3 before locking the attempt, checks
|
||||
// every item_instance_id against that attempt, and commits the receipt and any events in one
|
||||
// transaction. A terminal, expired, or demo_express attempt accepts no new evidence; demo_express
|
||||
// remains a separate training mode and receives no signal storage or grade effect.
|
||||
//
|
||||
// The contract accepts only focus-loss duration, copy/paste/cut byte counts, fullscreen exits, item
|
||||
// identifiers, and untrusted client timestamps. It never accepts answer text, clipboard contents,
|
||||
// arbitrary strings, camera, microphone, screen recordings, screenshots, or organization identifiers.
|
||||
// Client timestamps must be within five minutes before attempt creation and five minutes after the
|
||||
// database receipt clock. Server receipt time controls rolling rate limits. Signal events are removed
|
||||
// with the assessment attempt or account; this release does not promise an independent expiry
|
||||
// schedule. Signals do not change scores, categories, quotas, or candidate/employer result responses.
|
||||
//
|
||||
// A batch has at most 50 events and the raw request body is limited to 32 KiB before decoding. At most
|
||||
// 30 new receipts per candidate and attempt are accepted in a rolling minute; an over-limit request
|
||||
// answers 429 and does not consume its idempotency key. Storage is capped at 10,000 events per
|
||||
// attempt. If the whole batch would exceed that cap, the server stores no events from it and replays a
|
||||
// `saturated` receipt. Repeating the same key and body within 24 hours returns the original receipt
|
||||
// without storing another batch; using that key with another body answers 422.
|
||||
//
|
||||
// POST /api/v1/me/assessment-attempts/{attempt_id}/signals
|
||||
func (UnimplementedHandler) RecordMyAssessmentAttemptSignals(ctx context.Context, req *AssessmentSignalBatch, params RecordMyAssessmentAttemptSignalsParams) (r RecordMyAssessmentAttemptSignalsRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// RegisterAccount implements RegisterAccount operation.
|
||||
//
|
||||
// Public operation without a session. The client reads the current C1 text with GetConsentText and
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,55 @@
|
||||
package apitypes
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
)
|
||||
|
||||
// AssessmentNumber preserves the JSON number token for exact answer comparison.
|
||||
type AssessmentNumber string
|
||||
|
||||
func (number *AssessmentNumber) UnmarshalJSON(encoded []byte) error {
|
||||
if number == nil {
|
||||
return errors.New("assessment number target is nil")
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewReader(encoded))
|
||||
decoder.UseNumber()
|
||||
var value any
|
||||
if err := decoder.Decode(&value); err != nil {
|
||||
return errors.New("assessment answer number is invalid")
|
||||
}
|
||||
parsed, ok := value.(json.Number)
|
||||
if !ok {
|
||||
return errors.New("assessment answer must be a JSON number")
|
||||
}
|
||||
var extra any
|
||||
if !errors.Is(decoder.Decode(&extra), io.EOF) {
|
||||
return errors.New("assessment answer number has trailing data")
|
||||
}
|
||||
*number = AssessmentNumber(parsed.String())
|
||||
return nil
|
||||
}
|
||||
|
||||
func (number AssessmentNumber) MarshalJSON() ([]byte, error) {
|
||||
encoded := []byte(number)
|
||||
decoder := json.NewDecoder(bytes.NewReader(encoded))
|
||||
decoder.UseNumber()
|
||||
var value any
|
||||
if err := decoder.Decode(&value); err != nil {
|
||||
return nil, errors.New("assessment answer number is invalid")
|
||||
}
|
||||
if _, ok := value.(json.Number); !ok {
|
||||
return nil, errors.New("assessment answer must be a JSON number")
|
||||
}
|
||||
var extra any
|
||||
if !errors.Is(decoder.Decode(&extra), io.EOF) {
|
||||
return nil, errors.New("assessment answer number has trailing data")
|
||||
}
|
||||
return encoded, nil
|
||||
}
|
||||
|
||||
func (number AssessmentNumber) String() string {
|
||||
return string(number)
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package apitypes
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAssessmentNumberPreservesOnlyJSONNumberTokens(t *testing.T) {
|
||||
var number AssessmentNumber
|
||||
if err := json.Unmarshal([]byte(`1.0000000000000001`), &number); err != nil {
|
||||
t.Fatalf("UnmarshalJSON() error = %v", err)
|
||||
}
|
||||
encoded, err := json.Marshal(number)
|
||||
if err != nil || string(encoded) != `1.0000000000000001` {
|
||||
t.Fatalf("MarshalJSON() = %s, error %v; want original exact token", encoded, err)
|
||||
}
|
||||
for _, input := range []string{`"1"`, `null`, `true`, `1 2`} {
|
||||
if err := json.Unmarshal([]byte(input), &number); err == nil {
|
||||
t.Errorf("UnmarshalJSON(%s) unexpectedly succeeded", input)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package httpadapter
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
)
|
||||
|
||||
const maxAssessmentSignalBodyBytes int64 = 32 << 10
|
||||
|
||||
// limitAssessmentSignalBody is called only after the generated router has
|
||||
// matched the signal operation. It leaves decoding and authentication order
|
||||
// to the generated server while bounding both fixed-length and chunked bodies.
|
||||
func limitAssessmentSignalBody(w http.ResponseWriter, request *http.Request) {
|
||||
if request.Body != nil {
|
||||
request.Body = http.MaxBytesReader(w, request.Body, maxAssessmentSignalBodyBytes)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package httpadapter
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLimitAssessmentSignalBodyBoundsFixedAndChunkedBodies(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
contentLength int64
|
||||
}{
|
||||
{name: "content length", contentLength: maxAssessmentSignalBodyBytes + 1},
|
||||
{name: "chunked body", contentLength: -1},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
request := httptest.NewRequest("POST", "/", strings.NewReader(strings.Repeat("x", int(maxAssessmentSignalBodyBytes+1))))
|
||||
request.ContentLength = testCase.contentLength
|
||||
response := httptest.NewRecorder()
|
||||
limitAssessmentSignalBody(response, request)
|
||||
|
||||
body, err := io.ReadAll(request.Body)
|
||||
var limitError *http.MaxBytesError
|
||||
if !errors.As(err, &limitError) {
|
||||
t.Fatalf("ReadAll() error = %v, want MaxBytesError", err)
|
||||
}
|
||||
if int64(len(body)) != maxAssessmentSignalBodyBytes {
|
||||
t.Fatalf("ReadAll() returned %d bytes, want %d", len(body), maxAssessmentSignalBodyBytes)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLimitAssessmentSignalBodyAllowsExactLimit(t *testing.T) {
|
||||
request := httptest.NewRequest("POST", "/", strings.NewReader(strings.Repeat("x", int(maxAssessmentSignalBodyBytes))))
|
||||
response := httptest.NewRecorder()
|
||||
limitAssessmentSignalBody(response, request)
|
||||
|
||||
body, err := io.ReadAll(request.Body)
|
||||
if err != nil {
|
||||
t.Fatalf("ReadAll() error = %v", err)
|
||||
}
|
||||
if int64(len(body)) != maxAssessmentSignalBodyBytes {
|
||||
t.Fatalf("ReadAll() returned %d bytes, want %d", len(body), maxAssessmentSignalBodyBytes)
|
||||
}
|
||||
}
|
||||
@@ -31,7 +31,12 @@ var (
|
||||
publicationSchemas = []string{"Publication", "PublicationUpdate", "PublicationVersion", "PublicationState", "PublicationClosedReason", "CardField", "CardFieldSet"}
|
||||
searchStatusSchemas = []string{"SearchStatus", "SearchStatusUpdate", "SearchStatusVersion", "SearchStatusValue"}
|
||||
hiddenSchemas = []string{"HiddenOrganization", "HiddenOrganizationList", "PrivacyOrganization"}
|
||||
privacyOnlySchemas = []string{"PrivacySettings", "CardPreview", "AnonymousCardContent", "CardCategory", "PrivacyEvent", "PrivacyEventKind", "PrivacyEventList", "CardAccess", "CardAccessKind", "CardAccessList"}
|
||||
privacyOnlySchemas = []string{
|
||||
"PrivacySettings", "CardPreview", "AnonymousCardContent", "CardCategory", "CardCategoryStrength", "CardSelfAssessment",
|
||||
"CardSelfAssessmentConfirmationStatus",
|
||||
"CandidateExperienceBand", "CandidateWorkFormat", "CandidateSalaryCompatibility",
|
||||
"PrivacyEvent", "PrivacyEventKind", "PrivacyEventList", "CardAccess", "CardAccessKind", "CardAccessList",
|
||||
}
|
||||
// sharedLeafSchemas are the reusable leaves that the privacy family may
|
||||
// refer to; none of them identifies a person or carries a contact.
|
||||
sharedLeafSchemas = []string{"Timestamp", "PageInfo", "SpecializationCode", "GradeCode", "StackTag"}
|
||||
@@ -207,13 +212,16 @@ func TestPublicationAndSearchStatusAreNotConsents(t *testing.T) {
|
||||
|
||||
// The published field set cannot name a name, a contact, or the salary.
|
||||
fields := enumValues(t, resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/CardField"}))
|
||||
want := []string{"categories", "stack", "experience", "soft_skills", "location", "relocation"}
|
||||
want := []string{
|
||||
"categories", "stack", "experience", "soft_skills", "location", "relocation",
|
||||
"self_assessment", "work_formats", "salary_compatibility",
|
||||
}
|
||||
slices.Sort(fields)
|
||||
slices.Sort(want)
|
||||
if !slices.Equal(fields, want) {
|
||||
t.Errorf("CardField = %v, want %v", fields, want)
|
||||
}
|
||||
if update := spec.Components.Schemas["CardFieldSet"]; update.UniqueItems != true || update.MaxItems == nil || *update.MaxItems != uint64(len(want)) {
|
||||
if update := spec.Components.Schemas["CardFieldSet"]; update.UniqueItems != true || update.MaxItems == nil || *update.MaxItems != 9 {
|
||||
t.Error("CardFieldSet must hold distinct items and at most one per field")
|
||||
}
|
||||
status := enumValues(t, resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/SearchStatusValue"}))
|
||||
@@ -233,7 +241,9 @@ func TestAnonymousCardReachesNoProfileOrContactSchema(t *testing.T) {
|
||||
if card == nil {
|
||||
t.Fatal("the contract has no AnonymousCardContent")
|
||||
}
|
||||
if got, want := propertyNames(card), []string{"categories", "experience_months", "location", "relocation", "soft_skills", "stack"}; !slices.Equal(got, want) {
|
||||
if got, want := propertyNames(card), []string{
|
||||
"categories", "experience_band", "pseudonym", "salary_compatibility", "self_assessment", "stack", "work_formats",
|
||||
}; !slices.Equal(got, want) {
|
||||
t.Errorf("AnonymousCardContent properties = %v, want %v", got, want)
|
||||
}
|
||||
if card.AdditionalProperties.Bool == nil || *card.AdditionalProperties.Bool {
|
||||
@@ -241,7 +251,9 @@ func TestAnonymousCardReachesNoProfileOrContactSchema(t *testing.T) {
|
||||
}
|
||||
// Each property is a card field and nothing else; a null is a hidden or
|
||||
// missing value, never a flag that tells which.
|
||||
for _, forbidden := range []string{"email", "phone", "telegram", "contact", "name", "salary", "user", "account", "profile", "employer", "id", "url", "link", "github", "resume"} {
|
||||
for _, forbidden := range []string{
|
||||
"email", "phone", "telegram", "contact", "name", "salary_minimum", "salary_amount", "user", "account", "profile", "employer", "id", "url", "link", "github", "resume",
|
||||
} {
|
||||
for _, name := range propertyNames(card) {
|
||||
if strings.Contains(name, forbidden) {
|
||||
t.Errorf("AnonymousCardContent has the property %q, which looks like %q", name, forbidden)
|
||||
@@ -250,7 +262,11 @@ func TestAnonymousCardReachesNoProfileOrContactSchema(t *testing.T) {
|
||||
}
|
||||
|
||||
// What the card and the preview reach is a small closed list of leaves.
|
||||
allowed := []string{"AnonymousCardContent", "CardCategory", "CardField", "CardFieldSet", "PublicationState", "SpecializationCode", "GradeCode", "StackTag", "Timestamp", "CardPreview"}
|
||||
allowed := []string{
|
||||
"AnonymousCardContent", "CardCategory", "CardCategoryStrength", "CardSelfAssessment", "CardSelfAssessmentConfirmationStatus", "CandidateExperienceBand", "CandidateWorkFormat",
|
||||
"CandidateSalaryCompatibility", "CardField", "CardFieldSet", "PublicationState", "SpecializationCode",
|
||||
"GradeCode", "StackTag", "Timestamp", "CardPreview",
|
||||
}
|
||||
for _, name := range []string{"AnonymousCardContent", "CardPreview"} {
|
||||
for reached := range reachableSchemas(index, mustJSONValue(t, spec.Components.Schemas[name])) {
|
||||
if !slices.Contains(allowed, reached) {
|
||||
@@ -296,6 +312,14 @@ func TestAnonymousCardReachesNoProfileOrContactSchema(t *testing.T) {
|
||||
continue
|
||||
}
|
||||
for reached := range reachableSchemas(index, mustJSONValue(t, item)) {
|
||||
if path == "/api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}" &&
|
||||
slices.Contains([]string{
|
||||
"AnonymousCardContent", "CardCategory", "CardCategoryStrength", "CardSelfAssessment",
|
||||
"CardSelfAssessmentConfirmationStatus", "CandidateExperienceBand", "CandidateWorkFormat",
|
||||
"CandidateSalaryCompatibility",
|
||||
}, reached) {
|
||||
continue
|
||||
}
|
||||
if isPrivacySchema(reached) {
|
||||
t.Errorf("%s reaches the candidate-private schema %s", path, reached)
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ func (authorizer companyAuthorizerFunc) AuthorizeCompany(ctx context.Context, ac
|
||||
return authorizer(ctx, actorID, organizationID)
|
||||
}
|
||||
|
||||
func TestCompanyContextMiddlewareFailsClosedAndExcludesCandidateScopes(t *testing.T) {
|
||||
func TestCompanyContextMiddlewareFailsClosedAndExcludesOtherScopes(t *testing.T) {
|
||||
organizationID := uuid.New()
|
||||
request := ownerCompanyMiddlewareRequest(t, uuid.New(), apiadapter.GetOrganizationOperation, organizationID)
|
||||
if _, err := NewCompanyContextMiddleware(nil)(request, func(ogenmiddleware.Request) (ogenmiddleware.Response, error) {
|
||||
@@ -49,6 +49,9 @@ func TestCompanyContextMiddlewareFailsClosedAndExcludesCandidateScopes(t *testin
|
||||
}
|
||||
|
||||
for _, operation := range []apiadapter.OperationName{
|
||||
// Card reads lock any active membership inside their read transaction;
|
||||
// the owner-only capability does not apply to that operation.
|
||||
apiadapter.GetOrganizationCandidateCardOperation,
|
||||
apiadapter.HideOrganizationOperation,
|
||||
apiadapter.UnhideOrganizationOperation,
|
||||
apiadapter.RevokeMyOrganizationContactConsentOperation,
|
||||
@@ -62,7 +65,7 @@ func TestCompanyContextMiddlewareFailsClosedAndExcludesCandidateScopes(t *testin
|
||||
return ogenmiddleware.Response{}, nil
|
||||
})
|
||||
if err != nil || !called {
|
||||
t.Fatalf("candidate/self-scoped operation: called=%v err=%v; want pass-through", called, err)
|
||||
t.Fatalf("operation outside owner scope: called=%v err=%v; want pass-through", called, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -131,6 +134,7 @@ func TestCompanyContextOperationInventoryMatchesOpenAPI(t *testing.T) {
|
||||
}
|
||||
seen := make(map[string]string, len(ownerCompanyOperations))
|
||||
seenExceptions := make(map[string]bool, len(candidateExceptions))
|
||||
seenCardRead := false
|
||||
for path, methods := range document.Paths {
|
||||
for _, operation := range methods {
|
||||
if operation.OperationID == "" {
|
||||
@@ -150,6 +154,13 @@ func TestCompanyContextOperationInventoryMatchesOpenAPI(t *testing.T) {
|
||||
if !strings.Contains(path, "{org_id}") {
|
||||
continue
|
||||
}
|
||||
// The card usecase checks and locks active membership together with
|
||||
// current visibility and quota. It does not require the owner role.
|
||||
if operation.OperationID == "GetOrganizationCandidateCard" &&
|
||||
path == "/api/v1/organizations/{org_id}/candidate-cards/{candidate_handle}" {
|
||||
seenCardRead = true
|
||||
continue
|
||||
}
|
||||
expectedPath, candidateOperation := candidateExceptions[operation.OperationID]
|
||||
if candidateOperation && expectedPath == path && strings.HasPrefix(path, "/api/v1/me/") {
|
||||
seenExceptions[operation.OperationID] = true
|
||||
@@ -168,6 +179,9 @@ func TestCompanyContextOperationInventoryMatchesOpenAPI(t *testing.T) {
|
||||
t.Errorf("candidate exception %s is absent or moved without updating the explicit exception", operation)
|
||||
}
|
||||
}
|
||||
if !seenCardRead {
|
||||
t.Error("transaction-authorized candidate card read is absent or moved")
|
||||
}
|
||||
}
|
||||
|
||||
type companyContextAuthenticator struct {
|
||||
|
||||
@@ -79,7 +79,7 @@ func NewRouter(
|
||||
// server aborts the response; the kit Recoverer would swallow that panic.
|
||||
router.Group(func(public chi.Router) {
|
||||
public.Use(problems.Recover)
|
||||
public.Handle(apiWildcard, clearUnauthorizedLogoutCookie(apiServer))
|
||||
public.Handle(apiWildcard, clearUnauthorizedLogoutCookie(limitOperationBody(apiServer)))
|
||||
// Unknown /api paths outside the versioned prefix are also problems,
|
||||
// so every error under /api has the contract's format.
|
||||
public.Handle(apiRoot, http.HandlerFunc(problems.NotFound))
|
||||
@@ -88,6 +88,16 @@ func NewRouter(
|
||||
return router, nil
|
||||
}
|
||||
|
||||
func limitOperationBody(server *apiadapter.Server) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
operation, found := server.FindPath(r.Method, r.URL)
|
||||
if found && operation.PathPattern() == publicPrefix+"/me/assessment-attempts/{attempt_id}/signals" {
|
||||
limitAssessmentSignalBody(w, r)
|
||||
}
|
||||
server.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func clearUnauthorizedLogoutCookie(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
clearCookie := r.Method == http.MethodDelete && r.URL.Path == publicPrefix+"/identity/sessions/current"
|
||||
|
||||
@@ -1413,7 +1413,7 @@ const (
|
||||
`"offer_type":"full_time","tasks":["Развивать сервис выплат"],"team":"Команда платежей из шести человек",` +
|
||||
`"tech_stack":["Go","PostgreSQL"],"work_formats":["remote"],"location":null,` +
|
||||
`"communication_method":` + invitationCommunication + `,"salary":` + invitationSalary + `,"package":` + invitationPackage + `}`
|
||||
validInvitationCreate = `{"candidate_handle":"cand_7Qm2xVb9Lr4Kp0Zt",` +
|
||||
validInvitationCreate = `{"candidate_handle":"cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",` +
|
||||
`"need":{"need_id":"01928f7a-2b3c-7d4e-9f5a-6b7c8d9e0f12","requirements_version":3},` +
|
||||
`"response_period_days":7,"terms":` + validInvitationTerms + `}`
|
||||
validInvitationAccept = `{"expected_version":5,"terms_version":3,"consent_c4":{"text_version":"c4-2026-10-01","accepted":true,"fields":["email"]}}`
|
||||
@@ -1422,7 +1422,7 @@ const (
|
||||
// invitationCreateWithTerms returns a CreateOrganizationInvitation body whose
|
||||
// terms are the valid terms with one replacement applied.
|
||||
func invitationCreateWithTerms(old, replacement string) string {
|
||||
return `{"candidate_handle":"cand_7Qm2xVb9Lr4Kp0Zt","terms":` + strings.Replace(validInvitationTerms, old, replacement, 1) + `}`
|
||||
return `{"candidate_handle":"cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","terms":` + strings.Replace(validInvitationTerms, old, replacement, 1) + `}`
|
||||
}
|
||||
|
||||
// The schema alone must accept a complete invitation and reject what the
|
||||
@@ -1476,7 +1476,7 @@ func TestInvitationSchemaValidationPrecedesImplementation(t *testing.T) {
|
||||
},
|
||||
{
|
||||
name: "create a direct draft with the default response period",
|
||||
request: create(`{"candidate_handle":"cand_7Qm2xVb9Lr4Kp0Zt","need":null,"terms":` + validInvitationTerms + `}`),
|
||||
request: create(`{"candidate_handle":"cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","need":null,"terms":` + validInvitationTerms + `}`),
|
||||
},
|
||||
{
|
||||
// The cross-field salary rules and the place of work for an
|
||||
@@ -1505,12 +1505,12 @@ func TestInvitationSchemaValidationPrecedesImplementation(t *testing.T) {
|
||||
},
|
||||
{
|
||||
name: "create for a candidate named by an email address",
|
||||
request: create(strings.Replace(validInvitationCreate, `"cand_7Qm2xVb9Lr4Kp0Zt"`, `"candidate@example.com"`, 1)),
|
||||
request: create(strings.Replace(validInvitationCreate, `"cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"`, `"candidate@example.com"`, 1)),
|
||||
location: api.ProblemFieldLocationBody, pointer: "/candidate_handle", code: "invalid",
|
||||
},
|
||||
{
|
||||
name: "create without terms",
|
||||
request: create(`{"candidate_handle":"cand_7Qm2xVb9Lr4Kp0Zt"}`),
|
||||
request: create(`{"candidate_handle":"cv1_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}`),
|
||||
location: api.ProblemFieldLocationBody, pointer: "/terms", code: "required",
|
||||
},
|
||||
{
|
||||
@@ -1659,7 +1659,7 @@ func TestInvitationSchemaValidationPrecedesImplementation(t *testing.T) {
|
||||
},
|
||||
{
|
||||
name: "update that changes the candidate",
|
||||
request: update(`{"expected_version":1,"candidate_handle":"cand_Hx3Tn8Wq1Ys6Fd2Vb"}`),
|
||||
request: update(`{"expected_version":1,"candidate_handle":"cv1_BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"}`),
|
||||
location: api.ProblemFieldLocationBody, pointer: "", code: "invalid",
|
||||
},
|
||||
{
|
||||
|
||||
@@ -17,14 +17,19 @@ import (
|
||||
type Handler struct {
|
||||
api.UnimplementedHandler
|
||||
|
||||
health *HealthHandler
|
||||
identity *IdentityHandler
|
||||
consent *ConsentHandler
|
||||
profile *ProfileHandler
|
||||
questionnaire *QuestionnaireHandler
|
||||
catalog *CatalogHandler
|
||||
organization *OrganizationHandler
|
||||
problems *problem.Responder
|
||||
health *HealthHandler
|
||||
identity *IdentityHandler
|
||||
consent *ConsentHandler
|
||||
profile *ProfileHandler
|
||||
questionnaire *QuestionnaireHandler
|
||||
catalog *CatalogHandler
|
||||
organization *OrganizationHandler
|
||||
need *NeedHandler
|
||||
support *SupportHandler
|
||||
assessment *AssessmentHandler
|
||||
assessmentSignals *AssessmentSignalHandler
|
||||
privacy *PrivacyHandler
|
||||
problems *problem.Responder
|
||||
}
|
||||
|
||||
var _ api.Handler = (*Handler)(nil)
|
||||
@@ -62,6 +67,31 @@ func WithOrganization(organization *OrganizationHandler) HandlerOption {
|
||||
return func(handler *Handler) { handler.organization = organization }
|
||||
}
|
||||
|
||||
// WithNeed serves organization-scoped hiring needs.
|
||||
func WithNeed(need *NeedHandler) HandlerOption {
|
||||
return func(handler *Handler) { handler.need = need }
|
||||
}
|
||||
|
||||
// WithSupport serves account-owned support cases.
|
||||
func WithSupport(support *SupportHandler) HandlerOption {
|
||||
return func(handler *Handler) { handler.support = support }
|
||||
}
|
||||
|
||||
// WithAssessment serves candidate-owned assessment attempts and sessions.
|
||||
func WithAssessment(assessment *AssessmentHandler) HandlerOption {
|
||||
return func(handler *Handler) { handler.assessment = assessment }
|
||||
}
|
||||
|
||||
// WithAssessmentSignals serves bounded candidate assessment event receipts.
|
||||
func WithAssessmentSignals(signals *AssessmentSignalHandler) HandlerOption {
|
||||
return func(handler *Handler) { handler.assessmentSignals = signals }
|
||||
}
|
||||
|
||||
// WithPrivacy serves current publication and candidate-card visibility operations.
|
||||
func WithPrivacy(privacy *PrivacyHandler) HandlerOption {
|
||||
return func(handler *Handler) { handler.privacy = privacy }
|
||||
}
|
||||
|
||||
func NewHandler(health *HealthHandler, problems *problem.Responder, options ...HandlerOption) *Handler {
|
||||
handler := &Handler{health: health, problems: problems}
|
||||
for _, option := range options {
|
||||
|
||||
@@ -0,0 +1,799 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
"lincodex/backend/internal/adapter/primary/http/problem"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
assessmentusecase "lincodex/backend/internal/usecase/assessment"
|
||||
)
|
||||
|
||||
// AssessmentOperations serves candidate-owned attempt reads and commands.
|
||||
type AssessmentOperations interface {
|
||||
CreateAttempt(ctx context.Context, command assessmentusecase.CreateAttemptCommand) (outbound.AssessmentAttemptCreateResult, error)
|
||||
GetMyAssessmentAvailability(ctx context.Context, userID uuid.UUID) (assessmentusecase.AssessmentAvailability, error)
|
||||
GetMyAttempt(ctx context.Context, userID uuid.UUID, attemptID domain.AssessmentAttemptID) (domain.AssessmentAttemptPublicSnapshot, error)
|
||||
StartSession(ctx context.Context, command assessmentusecase.StartAttemptSessionCommand) (outbound.AssessmentAttemptSessionResult, error)
|
||||
}
|
||||
|
||||
// AssessmentHandler serves the candidate's frozen assessment attempts.
|
||||
type AssessmentHandler struct {
|
||||
operations AssessmentOperations
|
||||
}
|
||||
|
||||
func NewAssessmentHandler(operations AssessmentOperations) *AssessmentHandler {
|
||||
if operations == nil {
|
||||
panic("v1.NewAssessmentHandler - assessment operations must not be nil")
|
||||
}
|
||||
return &AssessmentHandler{operations: operations}
|
||||
}
|
||||
|
||||
func (handler *Handler) CreateMyAssessmentAttempt(
|
||||
ctx context.Context,
|
||||
request api.AssessmentAttemptCreate,
|
||||
params api.CreateMyAssessmentAttemptParams,
|
||||
) (api.CreateMyAssessmentAttemptRes, error) {
|
||||
if handler.assessment == nil {
|
||||
return handler.UnimplementedHandler.CreateMyAssessmentAttempt(ctx, request, params)
|
||||
}
|
||||
return handler.assessment.CreateMyAssessmentAttempt(ctx, request, params)
|
||||
}
|
||||
|
||||
func (handler *Handler) GetMyAssessmentAvailability(
|
||||
ctx context.Context,
|
||||
) (api.GetMyAssessmentAvailabilityRes, error) {
|
||||
if handler.assessment == nil {
|
||||
return handler.UnimplementedHandler.GetMyAssessmentAvailability(ctx)
|
||||
}
|
||||
return handler.assessment.GetMyAssessmentAvailability(ctx)
|
||||
}
|
||||
|
||||
func (handler *Handler) GetMyAssessmentAttempt(
|
||||
ctx context.Context,
|
||||
params api.GetMyAssessmentAttemptParams,
|
||||
) (api.GetMyAssessmentAttemptRes, error) {
|
||||
if handler.assessment == nil {
|
||||
return handler.UnimplementedHandler.GetMyAssessmentAttempt(ctx, params)
|
||||
}
|
||||
return handler.assessment.GetMyAssessmentAttempt(ctx, params)
|
||||
}
|
||||
|
||||
func (handler *Handler) StartMyAssessmentAttemptSession(
|
||||
ctx context.Context,
|
||||
request *api.AssessmentAttemptSessionStart,
|
||||
params api.StartMyAssessmentAttemptSessionParams,
|
||||
) (api.StartMyAssessmentAttemptSessionRes, error) {
|
||||
if handler.assessment == nil {
|
||||
return handler.UnimplementedHandler.StartMyAssessmentAttemptSession(ctx, request, params)
|
||||
}
|
||||
return handler.assessment.StartMyAssessmentAttemptSession(ctx, request, params)
|
||||
}
|
||||
|
||||
func (handler *Handler) SubmitMyAssessmentAnswer(
|
||||
ctx context.Context,
|
||||
request *api.AssessmentAnswerSubmission,
|
||||
params api.SubmitMyAssessmentAnswerParams,
|
||||
) (api.SubmitMyAssessmentAnswerRes, error) {
|
||||
if handler.assessment == nil {
|
||||
return handler.UnimplementedHandler.SubmitMyAssessmentAnswer(ctx, request, params)
|
||||
}
|
||||
return handler.assessment.SubmitMyAssessmentAnswer(ctx, request, params)
|
||||
}
|
||||
|
||||
func (handler *Handler) FinalizeMyAssessmentAttempt(
|
||||
ctx context.Context,
|
||||
request *api.AssessmentFinalization,
|
||||
params api.FinalizeMyAssessmentAttemptParams,
|
||||
) (api.FinalizeMyAssessmentAttemptRes, error) {
|
||||
if handler.assessment == nil {
|
||||
return handler.UnimplementedHandler.FinalizeMyAssessmentAttempt(ctx, request, params)
|
||||
}
|
||||
return handler.assessment.FinalizeMyAssessmentAttempt(ctx, request, params)
|
||||
}
|
||||
|
||||
func (handler *Handler) GetMyAssessmentResult(
|
||||
ctx context.Context,
|
||||
params api.GetMyAssessmentResultParams,
|
||||
) (api.GetMyAssessmentResultRes, error) {
|
||||
if handler.assessment == nil {
|
||||
return handler.UnimplementedHandler.GetMyAssessmentResult(ctx, params)
|
||||
}
|
||||
return handler.assessment.GetMyAssessmentResult(ctx, params)
|
||||
}
|
||||
|
||||
func (handler *AssessmentHandler) CreateMyAssessmentAttempt(
|
||||
ctx context.Context,
|
||||
request api.AssessmentAttemptCreate,
|
||||
params api.CreateMyAssessmentAttemptParams,
|
||||
) (api.CreateMyAssessmentAttemptRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.CreateMyAssessmentAttemptUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
command, valid := assessmentCreateCommand(principal.UserID, params.IdempotencyKey, request)
|
||||
if !valid {
|
||||
return assessmentCreateInvalid(ctx, ""), nil
|
||||
}
|
||||
result, err := handler.operations.CreateAttempt(ctx, command)
|
||||
if err != nil {
|
||||
return assessmentCreateFailure(ctx, err)
|
||||
}
|
||||
if result.Outcome.StatusCode == 409 {
|
||||
return (*api.CreateMyAssessmentAttemptConflict)(&problem.New(ctx, api.ProblemCodeStateConflict).Response), nil
|
||||
}
|
||||
if result.Outcome.StatusCode != 201 {
|
||||
return nil, fmt.Errorf("AssessmentHandler.CreateMyAssessmentAttempt - unexpected stored status %d", result.Outcome.StatusCode)
|
||||
}
|
||||
response, err := assessmentAttemptResponse(result.Outcome.Response)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("AssessmentHandler.CreateMyAssessmentAttempt - map response: %w", err)
|
||||
}
|
||||
return &api.AssessmentAttemptHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: response}, nil
|
||||
}
|
||||
|
||||
func (handler *AssessmentHandler) GetMyAssessmentAttempt(
|
||||
ctx context.Context,
|
||||
params api.GetMyAssessmentAttemptParams,
|
||||
) (api.GetMyAssessmentAttemptRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.GetMyAssessmentAttemptUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
snapshot, err := handler.operations.GetMyAttempt(ctx, principal.UserID, domain.AssessmentAttemptID(params.AttemptID))
|
||||
if err != nil {
|
||||
return assessmentAttemptReadFailure(ctx, err)
|
||||
}
|
||||
response, err := assessmentAttemptResponse(snapshot)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("AssessmentHandler.GetMyAssessmentAttempt - map response: %w", err)
|
||||
}
|
||||
return &api.AssessmentAttemptHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: response}, nil
|
||||
}
|
||||
|
||||
func (handler *AssessmentHandler) StartMyAssessmentAttemptSession(
|
||||
ctx context.Context,
|
||||
request *api.AssessmentAttemptSessionStart,
|
||||
params api.StartMyAssessmentAttemptSessionParams,
|
||||
) (api.StartMyAssessmentAttemptSessionRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.StartMyAssessmentAttemptSessionUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
if request == nil {
|
||||
return (*api.StartMyAssessmentAttemptSessionBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
|
||||
}
|
||||
result, err := handler.operations.StartSession(ctx, assessmentusecase.StartAttemptSessionCommand{
|
||||
ActorID: principal.UserID, AttemptID: domain.AssessmentAttemptID(params.AttemptID),
|
||||
ExpectedVersion: int64(request.ExpectedVersion), IdempotencyKey: params.IdempotencyKey,
|
||||
})
|
||||
if err != nil {
|
||||
return assessmentSessionFailure(ctx, err)
|
||||
}
|
||||
response, err := assessmentAttemptResponse(result.Response)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("AssessmentHandler.StartMyAssessmentAttemptSession - map response: %w", err)
|
||||
}
|
||||
return &api.AssessmentAttemptHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: response}, nil
|
||||
}
|
||||
|
||||
func (handler *AssessmentHandler) SubmitMyAssessmentAnswer(
|
||||
ctx context.Context,
|
||||
request *api.AssessmentAnswerSubmission,
|
||||
params api.SubmitMyAssessmentAnswerParams,
|
||||
) (api.SubmitMyAssessmentAnswerRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.SubmitMyAssessmentAnswerUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
if request == nil {
|
||||
return (*api.SubmitMyAssessmentAnswerBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
|
||||
}
|
||||
answer, valid := assessmentAnswerJSON(request.Answer)
|
||||
if !valid {
|
||||
return (*api.SubmitMyAssessmentAnswerBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "/answer").Response), nil
|
||||
}
|
||||
operations, ok := handler.operations.(interface {
|
||||
SubmitAnswer(ctx context.Context, command assessmentusecase.SubmitAttemptAnswerCommand) (outbound.AssessmentAttemptCommandResult, error)
|
||||
})
|
||||
if !ok {
|
||||
return nil, errors.New("AssessmentHandler.SubmitMyAssessmentAnswer - answer operation is unavailable")
|
||||
}
|
||||
result, err := operations.SubmitAnswer(ctx, assessmentusecase.SubmitAttemptAnswerCommand{
|
||||
ActorID: principal.UserID, AttemptID: domain.AssessmentAttemptID(params.AttemptID),
|
||||
ItemID: uuid.UUID(request.ItemID), ExpectedVersion: int64(request.ExpectedVersion),
|
||||
IdempotencyKey: params.IdempotencyKey, Answer: answer,
|
||||
})
|
||||
if err != nil {
|
||||
return assessmentAnswerFailure(ctx, err)
|
||||
}
|
||||
if result.Outcome.StatusCode != 200 {
|
||||
return assessmentAnswerCommandProblem(ctx, result.Outcome)
|
||||
}
|
||||
response, err := assessmentAttemptResponse(result.Outcome.Response)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("AssessmentHandler.SubmitMyAssessmentAnswer - map response: %w", err)
|
||||
}
|
||||
return &api.AssessmentAttemptHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: response}, nil
|
||||
}
|
||||
|
||||
func (handler *AssessmentHandler) FinalizeMyAssessmentAttempt(
|
||||
ctx context.Context,
|
||||
request *api.AssessmentFinalization,
|
||||
params api.FinalizeMyAssessmentAttemptParams,
|
||||
) (api.FinalizeMyAssessmentAttemptRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.FinalizeMyAssessmentAttemptUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
if request == nil {
|
||||
return (*api.FinalizeMyAssessmentAttemptBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
|
||||
}
|
||||
operations, ok := handler.operations.(interface {
|
||||
FinalizeAttempt(ctx context.Context, command assessmentusecase.FinalizeAssessmentAttemptCommand) (outbound.AssessmentAttemptCommandResult, error)
|
||||
})
|
||||
if !ok {
|
||||
return nil, errors.New("AssessmentHandler.FinalizeMyAssessmentAttempt - finalize operation is unavailable")
|
||||
}
|
||||
result, err := operations.FinalizeAttempt(ctx, assessmentusecase.FinalizeAssessmentAttemptCommand{
|
||||
ActorID: principal.UserID, AttemptID: domain.AssessmentAttemptID(params.AttemptID),
|
||||
ExpectedVersion: int64(request.ExpectedVersion), IdempotencyKey: params.IdempotencyKey,
|
||||
})
|
||||
if err != nil {
|
||||
return assessmentFinalizeFailure(ctx, err)
|
||||
}
|
||||
if result.Outcome.StatusCode != 200 {
|
||||
return assessmentFinalizeCommandProblem(ctx, result.Outcome)
|
||||
}
|
||||
response, err := assessmentAttemptResponse(result.Outcome.Response)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("AssessmentHandler.FinalizeMyAssessmentAttempt - map response: %w", err)
|
||||
}
|
||||
return &api.AssessmentAttemptHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: response}, nil
|
||||
}
|
||||
|
||||
func (handler *AssessmentHandler) GetMyAssessmentResult(
|
||||
ctx context.Context,
|
||||
params api.GetMyAssessmentResultParams,
|
||||
) (api.GetMyAssessmentResultRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.GetMyAssessmentResultUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
operations, ok := handler.operations.(interface {
|
||||
GetMyResult(ctx context.Context, userID uuid.UUID, attemptID domain.AssessmentAttemptID) (assessmentusecase.AssessmentAttemptResult, error)
|
||||
})
|
||||
if !ok {
|
||||
return nil, errors.New("AssessmentHandler.GetMyAssessmentResult - result operation is unavailable")
|
||||
}
|
||||
result, err := operations.GetMyResult(ctx, principal.UserID, domain.AssessmentAttemptID(params.AttemptID))
|
||||
if err != nil {
|
||||
return assessmentResultFailure(ctx, err)
|
||||
}
|
||||
response, err := assessmentResultResponse(result)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("AssessmentHandler.GetMyAssessmentResult - map response: %w", err)
|
||||
}
|
||||
return &api.AssessmentResultHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: response}, nil
|
||||
}
|
||||
|
||||
func assessmentAnswerJSON(answer api.AssessmentAnswer) ([]byte, bool) {
|
||||
encoded, err := answer.MarshalJSON()
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
return encoded, true
|
||||
}
|
||||
|
||||
func assessmentCreateCommand(actorID uuid.UUID, key string, request api.AssessmentAttemptCreate) (assessmentusecase.CreateAttemptCommand, bool) {
|
||||
command := assessmentusecase.CreateAttemptCommand{ActorID: actorID, IdempotencyKey: key}
|
||||
switch request.Type {
|
||||
case api.AssessmentQualifiedAttemptCreateAssessmentAttemptCreate:
|
||||
value, ok := request.GetAssessmentQualifiedAttemptCreate()
|
||||
if !ok {
|
||||
return assessmentusecase.CreateAttemptCommand{}, false
|
||||
}
|
||||
command.Kind = domain.AssessmentAttemptKindRoot
|
||||
command.Specialization = specializationPointer(value.Specialization)
|
||||
command.TargetGrade = gradePointer(value.TargetGrade)
|
||||
command.TaskLanguage = taskLanguagePointer(value.TaskLanguage)
|
||||
case api.AssessmentCorrectiveAttemptCreateAssessmentAttemptCreate:
|
||||
value, ok := request.GetAssessmentCorrectiveAttemptCreate()
|
||||
if !ok {
|
||||
return assessmentusecase.CreateAttemptCommand{}, false
|
||||
}
|
||||
command.Kind = domain.AssessmentAttemptKindCorrective
|
||||
command.Specialization = specializationPointer(value.Specialization)
|
||||
command.TargetGrade = gradePointer(value.TargetGrade)
|
||||
command.TaskLanguage = taskLanguagePointer(value.TaskLanguage)
|
||||
command.RootAttemptID = domain.AssessmentAttemptID(value.RootAttemptID)
|
||||
case api.AssessmentExpressAttemptCreateAssessmentAttemptCreate:
|
||||
if _, ok := request.GetAssessmentExpressAttemptCreate(); !ok {
|
||||
return assessmentusecase.CreateAttemptCommand{}, false
|
||||
}
|
||||
command.Kind = domain.AssessmentAttemptKindDemoExpress
|
||||
default:
|
||||
return assessmentusecase.CreateAttemptCommand{}, false
|
||||
}
|
||||
return command, true
|
||||
}
|
||||
|
||||
func specializationPointer(value api.SpecializationCode) *domain.SpecializationCode {
|
||||
code := domain.SpecializationCode(value)
|
||||
return &code
|
||||
}
|
||||
|
||||
func gradePointer(value api.GradeCode) *domain.GradeCode {
|
||||
code := domain.GradeCode(value)
|
||||
return &code
|
||||
}
|
||||
|
||||
func taskLanguagePointer(value api.NilTaskLanguage) *domain.TaskLanguageCode {
|
||||
language, ok := value.Get()
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
code := domain.TaskLanguageCode(language)
|
||||
return &code
|
||||
}
|
||||
|
||||
func assessmentCreateFailure(ctx context.Context, err error) (api.CreateMyAssessmentAttemptRes, error) {
|
||||
switch {
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptForbidden), errors.Is(err, assessmentusecase.ErrAttemptEmailNotVerified),
|
||||
errors.Is(err, assessmentusecase.ErrAttemptConsentRequired):
|
||||
return (*api.CreateMyAssessmentAttemptForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptKeyReused), errors.Is(err, outbound.ErrAssessmentAttemptIdempotencyConflict):
|
||||
return (*api.CreateMyAssessmentAttemptUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrInvalidAttemptKey):
|
||||
return assessmentCreateInvalidHeader(ctx), nil
|
||||
case errors.Is(err, assessmentusecase.ErrInvalidAttemptRequest), errors.Is(err, domain.ErrInvalidAssessmentAttempt):
|
||||
return assessmentCreateInvalid(ctx, attemptFieldPointer(err)), nil
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
func assessmentAttemptReadFailure(ctx context.Context, err error) (api.GetMyAssessmentAttemptRes, error) {
|
||||
switch {
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptForbidden), errors.Is(err, assessmentusecase.ErrAttemptEmailNotVerified):
|
||||
return (*api.GetMyAssessmentAttemptForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptNotFound), errors.Is(err, outbound.ErrAssessmentAttemptNotFound):
|
||||
return (*api.GetMyAssessmentAttemptNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
func assessmentSessionFailure(ctx context.Context, err error) (api.StartMyAssessmentAttemptSessionRes, error) {
|
||||
switch {
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptForbidden), errors.Is(err, assessmentusecase.ErrAttemptEmailNotVerified),
|
||||
errors.Is(err, assessmentusecase.ErrAttemptConsentRequired):
|
||||
return (*api.StartMyAssessmentAttemptSessionForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptNotFound), errors.Is(err, outbound.ErrAssessmentAttemptNotFound):
|
||||
return (*api.StartMyAssessmentAttemptSessionNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptVersionConflict), errors.Is(err, outbound.ErrAssessmentAttemptVersionConflict),
|
||||
errors.Is(err, domain.ErrAssessmentAttemptVersionConflict):
|
||||
return (*api.StartMyAssessmentAttemptSessionPreconditionFailed)(&problem.New(ctx, api.ProblemCodeVersionConflict).Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptKeyReused), errors.Is(err, outbound.ErrAssessmentAttemptIdempotencyConflict):
|
||||
return (*api.StartMyAssessmentAttemptSessionUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrInvalidAttemptKey):
|
||||
return (*api.StartMyAssessmentAttemptSessionBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationHeader, "/Idempotency-Key").Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrInvalidAttemptRequest), errors.Is(err, domain.ErrInvalidAssessmentAttempt):
|
||||
return (*api.StartMyAssessmentAttemptSessionBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, attemptFieldPointer(err)).Response), nil
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
func assessmentAnswerFailure(ctx context.Context, err error) (api.SubmitMyAssessmentAnswerRes, error) {
|
||||
switch {
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptForbidden), errors.Is(err, assessmentusecase.ErrAttemptEmailNotVerified),
|
||||
errors.Is(err, assessmentusecase.ErrAttemptConsentRequired):
|
||||
return (*api.SubmitMyAssessmentAnswerForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptNotFound), errors.Is(err, outbound.ErrAssessmentAttemptNotFound):
|
||||
return (*api.SubmitMyAssessmentAnswerNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptVersionConflict), errors.Is(err, outbound.ErrAssessmentAttemptVersionConflict),
|
||||
errors.Is(err, domain.ErrAssessmentAttemptVersionConflict):
|
||||
return (*api.SubmitMyAssessmentAnswerPreconditionFailed)(&problem.New(ctx, api.ProblemCodeVersionConflict).Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptStateConflict):
|
||||
return (*api.SubmitMyAssessmentAnswerConflict)(&problem.New(ctx, api.ProblemCodeStateConflict).Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptKeyReused), errors.Is(err, outbound.ErrAssessmentAttemptIdempotencyConflict):
|
||||
return (*api.SubmitMyAssessmentAnswerUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrInvalidAttemptKey):
|
||||
return (*api.SubmitMyAssessmentAnswerBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationHeader, "/Idempotency-Key").Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrInvalidAttemptRequest), errors.Is(err, domain.ErrInvalidAssessmentAttempt):
|
||||
return (*api.SubmitMyAssessmentAnswerBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, attemptFieldPointer(err)).Response), nil
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
func assessmentFinalizeFailure(ctx context.Context, err error) (api.FinalizeMyAssessmentAttemptRes, error) {
|
||||
switch {
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptForbidden), errors.Is(err, assessmentusecase.ErrAttemptEmailNotVerified),
|
||||
errors.Is(err, assessmentusecase.ErrAttemptConsentRequired):
|
||||
return (*api.FinalizeMyAssessmentAttemptForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptNotFound), errors.Is(err, outbound.ErrAssessmentAttemptNotFound):
|
||||
return (*api.FinalizeMyAssessmentAttemptNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptVersionConflict), errors.Is(err, outbound.ErrAssessmentAttemptVersionConflict),
|
||||
errors.Is(err, domain.ErrAssessmentAttemptVersionConflict):
|
||||
return (*api.FinalizeMyAssessmentAttemptPreconditionFailed)(&problem.New(ctx, api.ProblemCodeVersionConflict).Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptStateConflict):
|
||||
return assessmentFinalizeConflictProblem(ctx, nil), nil
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptKeyReused), errors.Is(err, outbound.ErrAssessmentAttemptIdempotencyConflict):
|
||||
return (*api.FinalizeMyAssessmentAttemptUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrInvalidAttemptKey):
|
||||
return (*api.FinalizeMyAssessmentAttemptBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationHeader, "/Idempotency-Key").Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrInvalidAttemptRequest), errors.Is(err, domain.ErrInvalidAssessmentAttempt):
|
||||
return (*api.FinalizeMyAssessmentAttemptBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, attemptFieldPointer(err)).Response), nil
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
func assessmentResultFailure(ctx context.Context, err error) (api.GetMyAssessmentResultRes, error) {
|
||||
switch {
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptForbidden), errors.Is(err, assessmentusecase.ErrAttemptEmailNotVerified):
|
||||
return (*api.GetMyAssessmentResultForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptNotFound), errors.Is(err, outbound.ErrAssessmentAttemptNotFound):
|
||||
return (*api.GetMyAssessmentResultNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptStateConflict):
|
||||
return (*api.GetMyAssessmentResultConflict)(&problem.New(ctx, api.ProblemCodeStateConflict).Response), nil
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
func assessmentAnswerCommandProblem(ctx context.Context, outcome outbound.AssessmentAttemptCommandOutcome) (api.SubmitMyAssessmentAnswerRes, error) {
|
||||
switch outcome.StatusCode {
|
||||
case 404:
|
||||
if outcome.ProblemCode == "not_found" {
|
||||
return (*api.SubmitMyAssessmentAnswerNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
|
||||
}
|
||||
case 409:
|
||||
if outcome.ProblemCode == "state_conflict" {
|
||||
return (*api.SubmitMyAssessmentAnswerConflict)(&problem.New(ctx, api.ProblemCodeStateConflict).Response), nil
|
||||
}
|
||||
}
|
||||
return nil, errors.New("AssessmentHandler.SubmitMyAssessmentAnswer - stored problem outcome is invalid")
|
||||
}
|
||||
|
||||
func assessmentFinalizeCommandProblem(ctx context.Context, outcome outbound.AssessmentAttemptCommandOutcome) (api.FinalizeMyAssessmentAttemptRes, error) {
|
||||
switch outcome.StatusCode {
|
||||
case 404:
|
||||
if outcome.ProblemCode == "not_found" {
|
||||
return (*api.FinalizeMyAssessmentAttemptNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
|
||||
}
|
||||
case 409:
|
||||
if outcome.ProblemCode == "state_conflict" {
|
||||
return assessmentFinalizeConflictProblem(ctx, outcome.PendingItemIDs), nil
|
||||
}
|
||||
}
|
||||
return nil, errors.New("AssessmentHandler.FinalizeMyAssessmentAttempt - stored problem outcome is invalid")
|
||||
}
|
||||
|
||||
func assessmentFinalizeConflictProblem(
|
||||
ctx context.Context,
|
||||
pendingItemIDs []uuid.UUID,
|
||||
) *api.AssessmentFinalizeConflictProblem {
|
||||
base := problem.New(ctx, api.ProblemCodeStateConflict).Response
|
||||
return &api.AssessmentFinalizeConflictProblem{
|
||||
Type: base.Type, Title: base.Title, Status: base.Status,
|
||||
Code: api.AssessmentFinalizeConflictProblemCodeStateConflict,
|
||||
Detail: base.Detail, Instance: base.Instance, TraceID: base.TraceID, Errors: base.Errors,
|
||||
PendingItemIds: append([]uuid.UUID(nil), pendingItemIDs...),
|
||||
}
|
||||
}
|
||||
|
||||
func assessmentResultResponse(result assessmentusecase.AssessmentAttemptResult) (api.AssessmentResult, error) {
|
||||
if result.Attempt.Kind == domain.AssessmentAttemptKindDemoExpress {
|
||||
if result.Outcome != domain.AssessmentAttemptOutcomeDemonstration || result.DecidedAt.IsZero() || result.Summary == "" {
|
||||
return api.AssessmentResult{}, errors.New("express result is incomplete")
|
||||
}
|
||||
return api.NewAssessmentExpressResultAssessmentResult(api.AssessmentExpressResult{
|
||||
AttemptID: result.Attempt.ID.UUID(), Kind: api.AssessmentExpressResultKindDemoExpress,
|
||||
Mode: api.AssessmentExpressResultModeDemoExpress, Versions: assessmentResultVersions(result.Attempt),
|
||||
Outcome: api.AssessmentExpressResultOutcomeDemonstration,
|
||||
CalibrationStatus: api.AssessmentExpressResultCalibrationStatusUncalibrated,
|
||||
Limitations: []api.AssessmentExpressResultLimitationsItem{api.AssessmentExpressResultLimitationsItemDemonstrationOnly},
|
||||
Practices: []api.AssessmentPracticeResult{}, Gaps: []api.AssessmentGap{},
|
||||
Durations: api.AssessmentDurations{ItemsSeconds: assessmentItemsSeconds(result), PracticeSeconds: nilInt32()},
|
||||
NextSteps: []api.AssessmentNextStep{}, Summary: result.Summary, DecidedAt: api.Timestamp(result.DecidedAt),
|
||||
}), nil
|
||||
}
|
||||
if result.Attempt.Kind != domain.AssessmentAttemptKindRoot && result.Attempt.Kind != domain.AssessmentAttemptKindCorrective {
|
||||
return api.AssessmentResult{}, errors.New("real result kind is invalid")
|
||||
}
|
||||
if result.Attempt.Specialization == nil || result.Attempt.TargetGrade == nil || result.DecidedAt.IsZero() {
|
||||
return api.AssessmentResult{}, errors.New("real result track or decision time is incomplete")
|
||||
}
|
||||
fields, err := assessmentRealResultFields(result)
|
||||
if err != nil {
|
||||
return api.AssessmentResult{}, err
|
||||
}
|
||||
if result.Attempt.Kind == domain.AssessmentAttemptKindRoot {
|
||||
return api.NewAssessmentQualifiedResultAssessmentResult(api.AssessmentQualifiedResult{
|
||||
AttemptID: result.Attempt.ID.UUID(), Specialization: api.SpecializationCode(*result.Attempt.Specialization),
|
||||
TargetGrade: api.GradeCode(*result.Attempt.TargetGrade), RootAttemptID: fields.rootAttemptID,
|
||||
ChainDeadline: fields.chainDeadline, TaskLanguage: fields.taskLanguage,
|
||||
Kind: api.AssessmentQualifiedResultKindRoot, Mode: api.AssessmentQualifiedResultMode(result.Attempt.Mode),
|
||||
Versions: assessmentResultVersions(result.Attempt), Outcome: fields.outcome,
|
||||
NotDeterminedReason: fields.reason, ConfirmedGrade: fields.confirmedGrade,
|
||||
PreviousConfirmedGrade: fields.previousGrade, Strength: fields.strength,
|
||||
CalibrationStatus: api.CalibrationStatusUncalibrated, Limitations: fields.limitations,
|
||||
Uncertainty: fields.uncertainty, BasicScore: fields.basicScore, Practices: []api.AssessmentPracticeResult{},
|
||||
Gaps: []api.AssessmentGap{}, Durations: api.AssessmentDurations{ItemsSeconds: assessmentItemsSeconds(result), PracticeSeconds: nilInt32()},
|
||||
NextSteps: []api.AssessmentNextStep{}, DecidedAt: api.Timestamp(result.DecidedAt),
|
||||
}), nil
|
||||
}
|
||||
if result.Attempt.RootAttemptID == nil || result.Attempt.ChainDeadline == nil {
|
||||
return api.AssessmentResult{}, errors.New("corrective result chain is incomplete")
|
||||
}
|
||||
return api.NewAssessmentCorrectiveResultAssessmentResult(api.AssessmentCorrectiveResult{
|
||||
AttemptID: result.Attempt.ID.UUID(), Specialization: api.SpecializationCode(*result.Attempt.Specialization),
|
||||
TargetGrade: api.GradeCode(*result.Attempt.TargetGrade), RootAttemptID: fields.rootAttemptID,
|
||||
ChainDeadline: fields.chainDeadline, TaskLanguage: fields.taskLanguage,
|
||||
Kind: api.AssessmentCorrectiveResultKindCorrective, Mode: api.AssessmentCorrectiveResultMode(result.Attempt.Mode),
|
||||
Versions: assessmentResultVersions(result.Attempt), Outcome: fields.outcome,
|
||||
NotDeterminedReason: fields.reason, ConfirmedGrade: fields.confirmedGrade,
|
||||
PreviousConfirmedGrade: fields.previousGrade, Strength: fields.strength,
|
||||
CalibrationStatus: api.CalibrationStatusUncalibrated, Limitations: fields.limitations,
|
||||
Uncertainty: fields.uncertainty, BasicScore: fields.basicScore, Practices: []api.AssessmentPracticeResult{},
|
||||
Gaps: []api.AssessmentGap{}, Durations: api.AssessmentDurations{ItemsSeconds: assessmentItemsSeconds(result), PracticeSeconds: nilInt32()},
|
||||
NextSteps: []api.AssessmentNextStep{}, DecidedAt: api.Timestamp(result.DecidedAt),
|
||||
}), nil
|
||||
}
|
||||
|
||||
type assessmentRealResultResponseFields struct {
|
||||
rootAttemptID api.NilUUID
|
||||
chainDeadline api.NilTimestamp
|
||||
taskLanguage api.NilTaskLanguage
|
||||
outcome api.AssessmentOutcome
|
||||
reason api.NilAssessmentNotDeterminedReason
|
||||
confirmedGrade api.NilGradeCode
|
||||
previousGrade api.NilGradeCode
|
||||
strength api.NilAssessmentStrength
|
||||
limitations []api.AssessmentLimitation
|
||||
uncertainty api.NilAssessmentUncertainty
|
||||
basicScore api.NilBasicScore
|
||||
}
|
||||
|
||||
func assessmentRealResultFields(result assessmentusecase.AssessmentAttemptResult) (assessmentRealResultResponseFields, error) {
|
||||
fields := assessmentRealResultResponseFields{
|
||||
outcome: api.AssessmentOutcome(result.Outcome), limitations: make([]api.AssessmentLimitation, 0, len(result.Limitations)),
|
||||
}
|
||||
if result.Attempt.Kind == domain.AssessmentAttemptKindCorrective {
|
||||
if result.Attempt.RootAttemptID == nil || result.Attempt.ChainDeadline == nil {
|
||||
return assessmentRealResultResponseFields{}, errors.New("corrective result chain is incomplete")
|
||||
}
|
||||
fields.rootAttemptID.SetTo(result.Attempt.RootAttemptID.UUID())
|
||||
fields.chainDeadline.SetTo(api.Timestamp(*result.Attempt.ChainDeadline))
|
||||
} else {
|
||||
fields.rootAttemptID.SetToNull()
|
||||
fields.chainDeadline.SetToNull()
|
||||
}
|
||||
if result.Attempt.TaskLanguage == nil {
|
||||
fields.taskLanguage.SetToNull()
|
||||
} else {
|
||||
fields.taskLanguage.SetTo(api.TaskLanguage(*result.Attempt.TaskLanguage))
|
||||
}
|
||||
if result.NotDeterminedReason == "" {
|
||||
fields.reason.SetToNull()
|
||||
} else {
|
||||
fields.reason.SetTo(api.AssessmentNotDeterminedReason(result.NotDeterminedReason))
|
||||
}
|
||||
fields.confirmedGrade.SetToNull()
|
||||
fields.previousGrade.SetToNull()
|
||||
fields.strength.SetToNull()
|
||||
fields.uncertainty.SetToNull()
|
||||
if result.BasicScore == nil {
|
||||
fields.basicScore.SetToNull()
|
||||
} else {
|
||||
fields.basicScore.SetTo(api.BasicScore{
|
||||
Points: result.BasicScore.Points, MaxPoints: result.BasicScore.MaxPoints, PassPoints: result.BasicScore.PassPoints,
|
||||
})
|
||||
}
|
||||
for _, limitation := range result.Limitations {
|
||||
fields.limitations = append(fields.limitations, api.AssessmentLimitation(limitation))
|
||||
}
|
||||
return fields, nil
|
||||
}
|
||||
|
||||
func assessmentResultVersions(snapshot domain.AssessmentAttemptPublicSnapshot) api.AssessmentVersions {
|
||||
return api.AssessmentVersions{
|
||||
PolicyVersion: snapshot.PolicyVersion, BankVersion: api.AssessmentVersionLabel(snapshot.BankVersion),
|
||||
AlgorithmVersion: api.AssessmentVersionLabel(snapshot.AlgorithmVersion),
|
||||
}
|
||||
}
|
||||
|
||||
func assessmentItemsSeconds(result assessmentusecase.AssessmentAttemptResult) int32 {
|
||||
seconds := int64(result.DecidedAt.Sub(result.Attempt.StartedAt) / time.Second)
|
||||
if seconds < 0 || seconds > 1<<31-1 {
|
||||
return 0
|
||||
}
|
||||
return int32(seconds)
|
||||
}
|
||||
|
||||
func nilInt32() api.NilInt32 {
|
||||
var value api.NilInt32
|
||||
value.SetToNull()
|
||||
return value
|
||||
}
|
||||
|
||||
func assessmentCreateInvalid(ctx context.Context, pointer string) api.CreateMyAssessmentAttemptRes {
|
||||
return (*api.CreateMyAssessmentAttemptBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, pointer).Response)
|
||||
}
|
||||
|
||||
func assessmentCreateInvalidHeader(ctx context.Context) api.CreateMyAssessmentAttemptRes {
|
||||
return (*api.CreateMyAssessmentAttemptBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationHeader, "/Idempotency-Key").Response)
|
||||
}
|
||||
|
||||
func attemptFieldPointer(err error) string {
|
||||
fieldError, ok := errors.AsType[*assessmentusecase.AttemptFieldError](err)
|
||||
if !ok || fieldError == nil {
|
||||
return ""
|
||||
}
|
||||
return fieldError.Pointer
|
||||
}
|
||||
|
||||
func assessmentAttemptResponse(snapshot domain.AssessmentAttemptPublicSnapshot) (api.AssessmentAttempt, error) {
|
||||
current, err := assessmentCurrentItem(snapshot.CurrentItem)
|
||||
if err != nil {
|
||||
return api.AssessmentAttempt{}, err
|
||||
}
|
||||
fields := assessmentAttemptFields(snapshot, current)
|
||||
switch snapshot.Kind {
|
||||
case domain.AssessmentAttemptKindRoot:
|
||||
return api.NewAssessmentQualifiedAttemptAssessmentAttempt(api.AssessmentQualifiedAttempt{
|
||||
ID: snapshot.ID.UUID(), Version: api.AssessmentAttemptVersion(snapshot.Version),
|
||||
Specialization: fields.specialization, TargetGrade: fields.targetGrade, TaskLanguage: fields.taskLanguage,
|
||||
Kind: api.AssessmentQualifiedAttemptKindRoot, RootAttemptID: fields.rootAttemptID, ChainDeadline: fields.chainDeadline,
|
||||
Mode: api.AssessmentQualifiedAttemptMode(snapshot.Mode), State: api.AssessmentAttemptState(snapshot.State),
|
||||
Versions: fields.versions, StartedAt: fields.startedAt, ExpiresAt: fields.expiresAt,
|
||||
Sessions: fields.sessions, FinishedAt: fields.finishedAt, Progress: fields.progress,
|
||||
CurrentItem: fields.currentItem, Practices: []api.AssessmentPractice{},
|
||||
}), nil
|
||||
case domain.AssessmentAttemptKindCorrective:
|
||||
return api.NewAssessmentCorrectiveAttemptAssessmentAttempt(api.AssessmentCorrectiveAttempt{
|
||||
ID: snapshot.ID.UUID(), Version: api.AssessmentAttemptVersion(snapshot.Version),
|
||||
Specialization: fields.specialization, TargetGrade: fields.targetGrade, TaskLanguage: fields.taskLanguage,
|
||||
Kind: api.AssessmentCorrectiveAttemptKindCorrective, RootAttemptID: fields.rootAttemptID, ChainDeadline: fields.chainDeadline,
|
||||
Mode: api.AssessmentCorrectiveAttemptMode(snapshot.Mode), State: api.AssessmentAttemptState(snapshot.State),
|
||||
Versions: fields.versions, StartedAt: fields.startedAt, ExpiresAt: fields.expiresAt,
|
||||
Sessions: fields.sessions, FinishedAt: fields.finishedAt, Progress: fields.progress,
|
||||
CurrentItem: fields.currentItem, Practices: []api.AssessmentPractice{},
|
||||
}), nil
|
||||
case domain.AssessmentAttemptKindDemoExpress:
|
||||
return api.NewAssessmentExpressAttemptAssessmentAttempt(api.AssessmentExpressAttempt{
|
||||
ID: snapshot.ID.UUID(), Version: api.AssessmentAttemptVersion(snapshot.Version),
|
||||
Specialization: fields.specialization, TargetGrade: fields.targetGrade, TaskLanguage: fields.taskLanguage,
|
||||
Kind: api.AssessmentExpressAttemptKindDemoExpress, RootAttemptID: fields.rootAttemptID, ChainDeadline: fields.chainDeadline,
|
||||
Mode: api.AssessmentExpressAttemptMode(snapshot.Mode), State: api.AssessmentAttemptState(snapshot.State),
|
||||
Versions: fields.versions, StartedAt: fields.startedAt, ExpiresAt: fields.expiresAt,
|
||||
Sessions: fields.sessions, FinishedAt: fields.finishedAt, Progress: fields.progress,
|
||||
CurrentItem: fields.currentItem, Practices: []api.AssessmentPractice{},
|
||||
}), nil
|
||||
default:
|
||||
return api.AssessmentAttempt{}, errors.New("unknown assessment attempt kind")
|
||||
}
|
||||
}
|
||||
|
||||
type assessmentAttemptResponseFields struct {
|
||||
specialization api.NilSpecializationCode
|
||||
targetGrade api.NilGradeCode
|
||||
taskLanguage api.NilTaskLanguage
|
||||
rootAttemptID api.NilUUID
|
||||
chainDeadline api.NilTimestamp
|
||||
versions api.AssessmentVersions
|
||||
startedAt api.Timestamp
|
||||
expiresAt api.Timestamp
|
||||
sessions api.NilAssessmentSessions
|
||||
finishedAt api.NilTimestamp
|
||||
progress api.AssessmentProgress
|
||||
currentItem api.NilAssessmentItem
|
||||
}
|
||||
|
||||
func assessmentAttemptFields(snapshot domain.AssessmentAttemptPublicSnapshot, currentItem api.NilAssessmentItem) assessmentAttemptResponseFields {
|
||||
fields := assessmentAttemptResponseFields{
|
||||
versions: api.AssessmentVersions{
|
||||
PolicyVersion: snapshot.PolicyVersion, BankVersion: api.AssessmentVersionLabel(snapshot.BankVersion),
|
||||
AlgorithmVersion: api.AssessmentVersionLabel(snapshot.AlgorithmVersion),
|
||||
},
|
||||
startedAt: api.Timestamp(snapshot.StartedAt), expiresAt: api.Timestamp(snapshot.ExpiresAt),
|
||||
progress: api.AssessmentProgress{AnsweredItems: snapshot.AnsweredItems, MaxItems: snapshot.MaxItems},
|
||||
currentItem: currentItem,
|
||||
}
|
||||
setAttemptTrackFields(&fields, snapshot)
|
||||
setAttemptSessionFields(&fields, snapshot)
|
||||
setAttemptEndFields(&fields, snapshot)
|
||||
return fields
|
||||
}
|
||||
|
||||
func setAttemptTrackFields(fields *assessmentAttemptResponseFields, snapshot domain.AssessmentAttemptPublicSnapshot) {
|
||||
if snapshot.Specialization == nil {
|
||||
fields.specialization.SetToNull()
|
||||
} else {
|
||||
fields.specialization.SetTo(api.SpecializationCode(*snapshot.Specialization))
|
||||
}
|
||||
if snapshot.TargetGrade == nil {
|
||||
fields.targetGrade.SetToNull()
|
||||
} else {
|
||||
fields.targetGrade.SetTo(api.GradeCode(*snapshot.TargetGrade))
|
||||
}
|
||||
if snapshot.TaskLanguage == nil {
|
||||
fields.taskLanguage.SetToNull()
|
||||
} else {
|
||||
fields.taskLanguage.SetTo(api.TaskLanguage(*snapshot.TaskLanguage))
|
||||
}
|
||||
if snapshot.RootAttemptID == nil {
|
||||
fields.rootAttemptID.SetToNull()
|
||||
} else {
|
||||
fields.rootAttemptID.SetTo(snapshot.RootAttemptID.UUID())
|
||||
}
|
||||
if snapshot.ChainDeadline == nil {
|
||||
fields.chainDeadline.SetToNull()
|
||||
} else {
|
||||
fields.chainDeadline.SetTo(api.Timestamp(*snapshot.ChainDeadline))
|
||||
}
|
||||
}
|
||||
|
||||
func setAttemptSessionFields(fields *assessmentAttemptResponseFields, snapshot domain.AssessmentAttemptPublicSnapshot) {
|
||||
if snapshot.MaxSessions <= 0 {
|
||||
fields.sessions.SetToNull()
|
||||
return
|
||||
}
|
||||
fields.sessions.SetTo(api.AssessmentSessions{
|
||||
Used: snapshot.SessionsUsed, Max: snapshot.MaxSessions, IdleTimeoutSeconds: snapshot.IdleTimeout,
|
||||
})
|
||||
}
|
||||
|
||||
func setAttemptEndFields(fields *assessmentAttemptResponseFields, snapshot domain.AssessmentAttemptPublicSnapshot) {
|
||||
if snapshot.FinishedAt == nil {
|
||||
fields.finishedAt.SetToNull()
|
||||
return
|
||||
}
|
||||
fields.finishedAt.SetTo(api.Timestamp(*snapshot.FinishedAt))
|
||||
}
|
||||
|
||||
func assessmentCurrentItem(item *domain.AssessmentAttemptPublicItem) (api.NilAssessmentItem, error) {
|
||||
var current api.NilAssessmentItem
|
||||
if item == nil {
|
||||
current.SetToNull()
|
||||
return current, nil
|
||||
}
|
||||
content, err := assessmentItemContent(item.Content)
|
||||
if err != nil {
|
||||
return api.NilAssessmentItem{}, err
|
||||
}
|
||||
current.SetTo(api.AssessmentItem{
|
||||
ID: api.AssessmentItemId(item.ID), Sequence: item.Sequence, Prompt: item.Prompt, Content: content,
|
||||
})
|
||||
return current, nil
|
||||
}
|
||||
|
||||
func assessmentItemContent(content domain.AssessmentAttemptPublicItemContent) (api.ItemContent, error) {
|
||||
switch content.Format {
|
||||
case "number":
|
||||
var unit api.NilString
|
||||
if content.Unit == nil {
|
||||
unit.SetToNull()
|
||||
} else {
|
||||
unit.SetTo(*content.Unit)
|
||||
}
|
||||
return api.NewNumberItemContentItemContent(api.NumberItemContent{Format: api.NumberItemContentFormatNumber, Unit: unit}), nil
|
||||
case "order":
|
||||
elements := make([]api.AssessmentOption, 0, len(content.Elements))
|
||||
for _, element := range content.Elements {
|
||||
elements = append(elements, api.AssessmentOption{ID: api.AssessmentOptionId(element.ID), Text: element.Text})
|
||||
}
|
||||
return api.NewOrderItemContentItemContent(api.OrderItemContent{Format: api.OrderItemContentFormatOrder, Elements: elements}), nil
|
||||
default:
|
||||
return api.ItemContent{}, errors.New("unsupported public assessment item format")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
"lincodex/backend/internal/adapter/primary/http/problem"
|
||||
"lincodex/backend/internal/domain"
|
||||
assessmentusecase "lincodex/backend/internal/usecase/assessment"
|
||||
)
|
||||
|
||||
func (handler *AssessmentHandler) GetMyAssessmentAvailability(
|
||||
ctx context.Context,
|
||||
) (api.GetMyAssessmentAvailabilityRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.GetMyAssessmentAvailabilityUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
availability, err := handler.operations.GetMyAssessmentAvailability(ctx, principal.UserID)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptForbidden), errors.Is(err, assessmentusecase.ErrAttemptEmailNotVerified):
|
||||
return (*api.GetMyAssessmentAvailabilityForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrAssessmentAvailabilityNotImplemented):
|
||||
return nil, problem.New(ctx, api.ProblemCodeNotImplemented)
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
response, err := assessmentAvailabilityResponse(availability)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("AssessmentHandler.GetMyAssessmentAvailability - map response: %w", err)
|
||||
}
|
||||
return &api.AssessmentAvailabilityHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: response}, nil
|
||||
}
|
||||
|
||||
func assessmentAvailabilityResponse(
|
||||
availability assessmentusecase.AssessmentAvailability,
|
||||
) (api.AssessmentAvailability, error) {
|
||||
response := api.AssessmentAvailability{Specializations: make([]api.AssessmentSpecializationAvailability, 0, len(availability.Specializations))}
|
||||
for _, item := range availability.Specializations {
|
||||
if !item.Specialization.IsKnown() {
|
||||
return api.AssessmentAvailability{}, errors.New("assessment availability has an unknown specialization")
|
||||
}
|
||||
specialization := api.AssessmentSpecializationAvailability{
|
||||
Specialization: api.SpecializationCode(item.Specialization),
|
||||
Grades: make([]api.AssessmentGradeAvailability, 0, len(item.Grades)),
|
||||
}
|
||||
specialization.ConfirmedGrade.SetToNull()
|
||||
if item.ConfirmedGrade != nil {
|
||||
if !item.ConfirmedGrade.IsKnown() {
|
||||
return api.AssessmentAvailability{}, errors.New("assessment availability has an unknown confirmed grade")
|
||||
}
|
||||
specialization.ConfirmedGrade.SetTo(api.GradeCode(*item.ConfirmedGrade))
|
||||
}
|
||||
specialization.ActiveAttemptID.SetToNull()
|
||||
if item.ActiveAttemptID != nil {
|
||||
if item.ActiveAttemptID.IsZero() {
|
||||
return api.AssessmentAvailability{}, errors.New("assessment availability has an invalid active attempt ID")
|
||||
}
|
||||
specialization.ActiveAttemptID.SetTo(item.ActiveAttemptID.UUID())
|
||||
}
|
||||
for _, grade := range item.Grades {
|
||||
mapped, err := assessmentGradeAvailabilityResponse(grade)
|
||||
if err != nil {
|
||||
return api.AssessmentAvailability{}, err
|
||||
}
|
||||
specialization.Grades = append(specialization.Grades, mapped)
|
||||
}
|
||||
response.Specializations = append(response.Specializations, specialization)
|
||||
}
|
||||
return response, nil
|
||||
}
|
||||
|
||||
func assessmentGradeAvailabilityResponse(
|
||||
grade assessmentusecase.GradeAvailability,
|
||||
) (api.AssessmentGradeAvailability, error) {
|
||||
if !grade.Grade.IsKnown() {
|
||||
return api.AssessmentGradeAvailability{}, errors.New("assessment availability has an unknown grade")
|
||||
}
|
||||
response := api.AssessmentGradeAvailability{Grade: api.GradeCode(grade.Grade)}
|
||||
response.Mode.SetToNull()
|
||||
response.AvailableAt.SetToNull()
|
||||
response.TimeLimitSeconds.SetToNull()
|
||||
response.MaxSessions.SetToNull()
|
||||
response.MaxItems.SetToNull()
|
||||
response.PracticeRequired.SetToNull()
|
||||
status, err := assessmentAvailabilityStatus(grade)
|
||||
if err != nil {
|
||||
return api.AssessmentGradeAvailability{}, err
|
||||
}
|
||||
response.Status = status
|
||||
if err := setAssessmentAvailabilityLimits(&response, grade); err != nil {
|
||||
return api.AssessmentGradeAvailability{}, err
|
||||
}
|
||||
return response, nil
|
||||
}
|
||||
|
||||
func assessmentAvailabilityStatus(
|
||||
grade assessmentusecase.GradeAvailability,
|
||||
) (api.AssessmentGradeAvailabilityStatus, error) {
|
||||
switch grade.Status {
|
||||
case assessmentusecase.AvailabilityStatusAvailable:
|
||||
return api.AssessmentGradeAvailabilityStatusAvailable, nil
|
||||
case assessmentusecase.AvailabilityStatusActiveAttempt:
|
||||
return api.AssessmentGradeAvailabilityStatusActiveAttempt, nil
|
||||
case assessmentusecase.AvailabilityStatusCooldown:
|
||||
if grade.AvailableAt == nil || grade.AvailableAt.IsZero() {
|
||||
return "", errors.New("assessment cooldown has no available time")
|
||||
}
|
||||
return api.AssessmentGradeAvailabilityStatusCooldown, nil
|
||||
case assessmentusecase.AvailabilityStatusInsufficientBank:
|
||||
return api.AssessmentGradeAvailabilityStatusInsufficientBank, nil
|
||||
default:
|
||||
return "", errors.New("assessment availability has an unknown status")
|
||||
}
|
||||
}
|
||||
|
||||
func setAssessmentAvailabilityLimits(
|
||||
response *api.AssessmentGradeAvailability,
|
||||
grade assessmentusecase.GradeAvailability,
|
||||
) error {
|
||||
if grade.Status == assessmentusecase.AvailabilityStatusInsufficientBank {
|
||||
return validateInsufficientBankLimits(grade)
|
||||
}
|
||||
if err := validateAssessmentAttemptLimits(grade); err != nil {
|
||||
return err
|
||||
}
|
||||
if grade.Status == assessmentusecase.AvailabilityStatusCooldown {
|
||||
response.AvailableAt.SetTo(api.Timestamp(grade.AvailableAt.UTC()))
|
||||
}
|
||||
response.Mode.SetTo(api.AssessmentRealMode(*grade.Mode))
|
||||
response.TimeLimitSeconds.SetTo(*grade.TimeLimitSeconds)
|
||||
response.MaxSessions.SetTo(*grade.MaxSessions)
|
||||
response.MaxItems.SetTo(*grade.MaxItems)
|
||||
response.PracticeRequired.SetTo(*grade.PracticeRequired)
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateInsufficientBankLimits(grade assessmentusecase.GradeAvailability) error {
|
||||
if grade.Mode != nil || grade.AvailableAt != nil || grade.TimeLimitSeconds != nil || grade.MaxSessions != nil ||
|
||||
grade.MaxItems != nil || grade.PracticeRequired != nil {
|
||||
return errors.New("insufficient-bank availability contains attempt limits")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateAssessmentAttemptLimits(grade assessmentusecase.GradeAvailability) error {
|
||||
if grade.Mode == nil || *grade.Mode != domain.AssessmentRealModeDemoBasic || grade.TimeLimitSeconds == nil ||
|
||||
*grade.TimeLimitSeconds <= 0 || grade.MaxSessions == nil || *grade.MaxSessions <= 0 || grade.MaxItems == nil ||
|
||||
*grade.MaxItems <= 0 || grade.PracticeRequired == nil {
|
||||
return errors.New("available assessment has incomplete attempt limits")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
"lincodex/backend/internal/domain"
|
||||
assessmentusecase "lincodex/backend/internal/usecase/assessment"
|
||||
)
|
||||
|
||||
func TestGetMyAssessmentAvailabilityMapsReadOnlyCandidateProjection(t *testing.T) {
|
||||
userID := uuid.New()
|
||||
activeAttemptID := domain.AssessmentAttemptID(uuid.New())
|
||||
availableAt := time.Date(2026, time.October, 8, 12, 0, 0, 0, time.UTC)
|
||||
seconds, sessions, items := int32(3600), int32(2), int32(25)
|
||||
mode := domain.AssessmentRealModeDemoBasic
|
||||
practice := false
|
||||
operations := &assessmentOperationsStub{availability: assessmentusecase.AssessmentAvailability{
|
||||
Specializations: []assessmentusecase.SpecializationAvailability{{
|
||||
Specialization: domain.SpecializationCode("backend"), ActiveAttemptID: &activeAttemptID,
|
||||
Grades: []assessmentusecase.GradeAvailability{
|
||||
{Grade: domain.GradeIntern, Status: assessmentusecase.AvailabilityStatusActiveAttempt,
|
||||
Mode: &mode, TimeLimitSeconds: &seconds, MaxSessions: &sessions, MaxItems: &items, PracticeRequired: &practice},
|
||||
{Grade: domain.GradeJunior, Status: assessmentusecase.AvailabilityStatusCooldown,
|
||||
Mode: &mode, AvailableAt: &availableAt, TimeLimitSeconds: &seconds, MaxSessions: &sessions,
|
||||
MaxItems: &items, PracticeRequired: &practice},
|
||||
{Grade: domain.GradeMiddle, Status: assessmentusecase.AvailabilityStatusInsufficientBank},
|
||||
},
|
||||
}},
|
||||
}}
|
||||
handler := NewAssessmentHandler(operations)
|
||||
response, err := handler.GetMyAssessmentAvailability(principalForTest(userID))
|
||||
if err != nil {
|
||||
t.Fatalf("GetMyAssessmentAvailability() error = %v", err)
|
||||
}
|
||||
headers, ok := response.(*api.AssessmentAvailabilityHeaders)
|
||||
if !ok || headers.CacheControl != api.CacheControlNoStoreNoStore || operations.availabilityCalls != 1 ||
|
||||
operations.availabilityUserID != userID {
|
||||
t.Fatalf("availability response = %T %+v, calls=%d user=%s", response, response, operations.availabilityCalls, operations.availabilityUserID)
|
||||
}
|
||||
if len(headers.Response.Specializations) != 1 {
|
||||
t.Fatalf("specializations = %+v", headers.Response.Specializations)
|
||||
}
|
||||
specialization := headers.Response.Specializations[0]
|
||||
if specialization.Specialization != api.SpecializationCodeBackend || !specialization.ConfirmedGrade.IsNull() {
|
||||
t.Fatalf("specialization = %+v", specialization)
|
||||
}
|
||||
if activeID, found := specialization.ActiveAttemptID.Get(); !found || activeID != activeAttemptID.UUID() {
|
||||
t.Fatalf("active attempt ID = %+v, %v", specialization.ActiveAttemptID, found)
|
||||
}
|
||||
if len(specialization.Grades) != 3 {
|
||||
t.Fatalf("grade availability = %+v", specialization.Grades)
|
||||
}
|
||||
if row := specialization.Grades[0]; row.Status != api.AssessmentGradeAvailabilityStatusActiveAttempt ||
|
||||
row.Mode.IsNull() || !row.AvailableAt.IsNull() || row.TimeLimitSeconds.IsNull() {
|
||||
// Active rows carry their mode and limits but never an available_at value.
|
||||
t.Fatalf("active grade projection = %+v", row)
|
||||
}
|
||||
if row := specialization.Grades[1]; row.Status != api.AssessmentGradeAvailabilityStatusCooldown ||
|
||||
row.AvailableAt.IsNull() || row.AvailableAt.Value != api.Timestamp(availableAt) || row.TimeLimitSeconds.IsNull() {
|
||||
t.Fatalf("cooldown grade projection = %+v", row)
|
||||
}
|
||||
if row := specialization.Grades[2]; row.Status != api.AssessmentGradeAvailabilityStatusInsufficientBank ||
|
||||
!row.Mode.IsNull() || !row.TimeLimitSeconds.IsNull() || !row.AvailableAt.IsNull() {
|
||||
t.Fatalf("insufficient-bank projection = %+v", row)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetMyAssessmentAvailabilityMapsAuthAndUnavailableMode(t *testing.T) {
|
||||
operations := &assessmentOperationsStub{availabilityErr: assessmentusecase.ErrAssessmentAvailabilityNotImplemented}
|
||||
handler := NewAssessmentHandler(operations)
|
||||
unauthenticated, err := handler.GetMyAssessmentAvailability(noPrincipalContext())
|
||||
if err != nil {
|
||||
t.Fatalf("unauthenticated availability error = %v", err)
|
||||
}
|
||||
if _, ok := unauthenticated.(*api.GetMyAssessmentAvailabilityUnauthorized); !ok || operations.availabilityCalls != 0 {
|
||||
t.Fatalf("unauthenticated response = %T, calls=%d", unauthenticated, operations.availabilityCalls)
|
||||
}
|
||||
_, err = handler.GetMyAssessmentAvailability(principalForTest(uuid.New()))
|
||||
var statusError *api.ProblemStatusCode
|
||||
if !errors.As(err, &statusError) || statusError.GetStatusCode() != 501 {
|
||||
t.Fatalf("unavailable mode error = %v, want a 501 problem", err)
|
||||
}
|
||||
operations.availabilityErr = assessmentusecase.ErrAttemptForbidden
|
||||
forbidden, err := handler.GetMyAssessmentAvailability(principalForTest(uuid.New()))
|
||||
if err != nil {
|
||||
t.Fatalf("forbidden availability error = %v", err)
|
||||
}
|
||||
if _, ok := forbidden.(*api.GetMyAssessmentAvailabilityForbidden); !ok {
|
||||
t.Fatalf("forbidden response = %T", forbidden)
|
||||
}
|
||||
}
|
||||
|
||||
func noPrincipalContext() context.Context { return context.Background() }
|
||||
@@ -0,0 +1,190 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"math"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
"lincodex/backend/internal/adapter/primary/http/problem"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
assessmentusecase "lincodex/backend/internal/usecase/assessment"
|
||||
)
|
||||
|
||||
type AssessmentSignalOperations interface {
|
||||
RecordSignals(ctx context.Context, command assessmentusecase.RecordSignalsCommand) (domain.AssessmentSignalReceipt, error)
|
||||
}
|
||||
|
||||
// AssessmentSignalHandler maps the typed candidate contract to domain input.
|
||||
// It never logs or returns event details.
|
||||
type AssessmentSignalHandler struct {
|
||||
operations AssessmentSignalOperations
|
||||
}
|
||||
|
||||
func NewAssessmentSignalHandler(operations AssessmentSignalOperations) *AssessmentSignalHandler {
|
||||
if operations == nil {
|
||||
panic("v1.NewAssessmentSignalHandler - assessment signal operations must not be nil")
|
||||
}
|
||||
return &AssessmentSignalHandler{operations: operations}
|
||||
}
|
||||
|
||||
func (handler *Handler) RecordMyAssessmentAttemptSignals(
|
||||
ctx context.Context,
|
||||
request *api.AssessmentSignalBatch,
|
||||
params api.RecordMyAssessmentAttemptSignalsParams,
|
||||
) (api.RecordMyAssessmentAttemptSignalsRes, error) {
|
||||
if handler.assessmentSignals == nil {
|
||||
return handler.UnimplementedHandler.RecordMyAssessmentAttemptSignals(ctx, request, params)
|
||||
}
|
||||
return handler.assessmentSignals.RecordMyAssessmentAttemptSignals(ctx, request, params)
|
||||
}
|
||||
|
||||
func (handler *AssessmentSignalHandler) RecordMyAssessmentAttemptSignals(
|
||||
ctx context.Context,
|
||||
request *api.AssessmentSignalBatch,
|
||||
params api.RecordMyAssessmentAttemptSignalsParams,
|
||||
) (api.RecordMyAssessmentAttemptSignalsRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.RecordMyAssessmentAttemptSignalsUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
if request == nil {
|
||||
return signalInvalidBody(ctx), nil
|
||||
}
|
||||
events, valid := assessmentSignalEvents(request.Events)
|
||||
if !valid {
|
||||
return signalInvalidBody(ctx), nil
|
||||
}
|
||||
receipt, err := handler.operations.RecordSignals(ctx, assessmentusecase.RecordSignalsCommand{
|
||||
ActorID: principal.UserID, AttemptID: domain.AssessmentAttemptID(params.AttemptID),
|
||||
IdempotencyKey: params.IdempotencyKey, Events: events,
|
||||
})
|
||||
if err != nil {
|
||||
return signalFailure(ctx, err)
|
||||
}
|
||||
return &api.AssessmentSignalReceiptHeaders{
|
||||
CacheControl: api.CacheControlNoStoreNoStore,
|
||||
Response: api.AssessmentSignalReceipt{
|
||||
Status: api.AssessmentSignalReceiptStatus(receipt.Status()), AcceptedEvents: receipt.AcceptedEvents(),
|
||||
ReceivedAt: api.Timestamp(receipt.ReceivedAt()),
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func assessmentSignalEvents(requestEvents []api.AssessmentSignalEvent) ([]domain.AssessmentSignalEvent, bool) {
|
||||
if len(requestEvents) == 0 || len(requestEvents) > 50 {
|
||||
return nil, false
|
||||
}
|
||||
events := make([]domain.AssessmentSignalEvent, 0, len(requestEvents))
|
||||
for _, requestEvent := range requestEvents {
|
||||
input, valid := assessmentSignalEventInput(requestEvent)
|
||||
if !valid {
|
||||
return nil, false
|
||||
}
|
||||
event, err := domain.NewAssessmentSignalEvent(input)
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
events = append(events, event)
|
||||
}
|
||||
return events, true
|
||||
}
|
||||
|
||||
func assessmentSignalEventInput(requestEvent api.AssessmentSignalEvent) (domain.AssessmentSignalEventInput, bool) {
|
||||
switch requestEvent.Type {
|
||||
case api.AssessmentFocusLossSignalAssessmentSignalEvent:
|
||||
return assessmentFocusLossInput(requestEvent)
|
||||
case api.AssessmentSignalEventCopyAssessmentSignalEvent,
|
||||
api.AssessmentSignalEventPasteAssessmentSignalEvent,
|
||||
api.AssessmentSignalEventCutAssessmentSignalEvent:
|
||||
return assessmentClipboardInput(requestEvent)
|
||||
case api.AssessmentFullscreenExitSignalAssessmentSignalEvent:
|
||||
return assessmentFullscreenExitInput(requestEvent)
|
||||
default:
|
||||
return domain.AssessmentSignalEventInput{}, false
|
||||
}
|
||||
}
|
||||
|
||||
func assessmentFocusLossInput(requestEvent api.AssessmentSignalEvent) (domain.AssessmentSignalEventInput, bool) {
|
||||
value, ok := requestEvent.GetAssessmentFocusLossSignal()
|
||||
if !ok || value.Kind != api.AssessmentFocusLossSignalKindFocusLoss {
|
||||
return domain.AssessmentSignalEventInput{}, false
|
||||
}
|
||||
duration := value.DurationMs
|
||||
return domain.AssessmentSignalEventInput{
|
||||
Kind: domain.AssessmentSignalFocusLoss, ItemInstanceID: uuid.UUID(value.ItemInstanceID),
|
||||
OccurredAt: time.Time(value.OccurredAt), DurationMS: &duration,
|
||||
}, true
|
||||
}
|
||||
|
||||
func assessmentClipboardInput(requestEvent api.AssessmentSignalEvent) (domain.AssessmentSignalEventInput, bool) {
|
||||
value, ok := requestEvent.GetAssessmentClipboardSignal()
|
||||
if !ok {
|
||||
return domain.AssessmentSignalEventInput{}, false
|
||||
}
|
||||
kind := domain.AssessmentSignalKind(value.Kind)
|
||||
if kind != domain.AssessmentSignalKind(requestEvent.Type) {
|
||||
return domain.AssessmentSignalEventInput{}, false
|
||||
}
|
||||
size := value.SizeBytes
|
||||
return domain.AssessmentSignalEventInput{
|
||||
Kind: kind, ItemInstanceID: uuid.UUID(value.ItemInstanceID),
|
||||
OccurredAt: time.Time(value.OccurredAt), SizeBytes: &size,
|
||||
}, true
|
||||
}
|
||||
|
||||
func assessmentFullscreenExitInput(requestEvent api.AssessmentSignalEvent) (domain.AssessmentSignalEventInput, bool) {
|
||||
value, ok := requestEvent.GetAssessmentFullscreenExitSignal()
|
||||
if !ok || value.Kind != api.AssessmentFullscreenExitSignalKindFullscreenExit {
|
||||
return domain.AssessmentSignalEventInput{}, false
|
||||
}
|
||||
return domain.AssessmentSignalEventInput{
|
||||
Kind: domain.AssessmentSignalFullscreenExit, ItemInstanceID: uuid.UUID(value.ItemInstanceID),
|
||||
OccurredAt: time.Time(value.OccurredAt),
|
||||
}, true
|
||||
}
|
||||
|
||||
func signalInvalidBody(ctx context.Context) *api.RecordMyAssessmentAttemptSignalsBadRequest {
|
||||
return (*api.RecordMyAssessmentAttemptSignalsBadRequest)(
|
||||
&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response,
|
||||
)
|
||||
}
|
||||
|
||||
func signalFailure(ctx context.Context, err error) (api.RecordMyAssessmentAttemptSignalsRes, error) {
|
||||
switch {
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptForbidden), errors.Is(err, assessmentusecase.ErrAttemptEmailNotVerified),
|
||||
errors.Is(err, assessmentusecase.ErrAttemptSignalForbidden), errors.Is(err, assessmentusecase.ErrAttemptSignalConsentRequired):
|
||||
return (*api.RecordMyAssessmentAttemptSignalsForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptNotFound), errors.Is(err, outbound.ErrAssessmentAttemptNotFound):
|
||||
return (*api.RecordMyAssessmentAttemptSignalsNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptSignalStateConflict):
|
||||
return (*api.RecordMyAssessmentAttemptSignalsConflict)(&problem.New(ctx, api.ProblemCodeStateConflict).Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptKeyReused), errors.Is(err, outbound.ErrAssessmentAttemptIdempotencyConflict):
|
||||
return (*api.RecordMyAssessmentAttemptSignalsUnprocessableEntity)(
|
||||
&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response,
|
||||
), nil
|
||||
case errors.Is(err, assessmentusecase.ErrInvalidAttemptKey):
|
||||
return (*api.RecordMyAssessmentAttemptSignalsBadRequest)(
|
||||
&problem.InvalidField(ctx, api.ProblemFieldLocationHeader, "/Idempotency-Key").Response,
|
||||
), nil
|
||||
case errors.Is(err, assessmentusecase.ErrInvalidAttemptSignalRequest), errors.Is(err, domain.ErrInvalidAssessmentSignal):
|
||||
return signalInvalidBody(ctx), nil
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptSignalRateLimited):
|
||||
limited, ok := errors.AsType[*assessmentusecase.SignalRateLimitError](err)
|
||||
if !ok || limited == nil {
|
||||
return nil, err
|
||||
}
|
||||
wait := time.Until(limited.RetryAt)
|
||||
if wait < time.Second {
|
||||
wait = time.Second
|
||||
}
|
||||
seconds := int32(math.Ceil(wait.Seconds()))
|
||||
return problem.RateLimited(ctx, seconds), nil
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
"lincodex/backend/internal/domain"
|
||||
assessmentusecase "lincodex/backend/internal/usecase/assessment"
|
||||
)
|
||||
|
||||
type assessmentSignalOperationsStub struct {
|
||||
command assessmentusecase.RecordSignalsCommand
|
||||
receipt domain.AssessmentSignalReceipt
|
||||
err error
|
||||
calls int
|
||||
}
|
||||
|
||||
func (stub *assessmentSignalOperationsStub) RecordSignals(
|
||||
_ context.Context,
|
||||
command assessmentusecase.RecordSignalsCommand,
|
||||
) (domain.AssessmentSignalReceipt, error) {
|
||||
stub.calls++
|
||||
stub.command = command
|
||||
return stub.receipt, stub.err
|
||||
}
|
||||
|
||||
func TestAssessmentSignalHandlerMapsAllowlistedEventVariants(t *testing.T) {
|
||||
actorID, attemptID, itemID := uuid.New(), uuid.New(), uuid.New()
|
||||
at := api.Timestamp(time.Date(2026, time.October, 7, 12, 0, 0, 123456000, time.UTC))
|
||||
duration, size := int32(4500), int32(32)
|
||||
request := &api.AssessmentSignalBatch{Events: []api.AssessmentSignalEvent{
|
||||
api.NewAssessmentFocusLossSignalAssessmentSignalEvent(api.AssessmentFocusLossSignal{
|
||||
Kind: api.AssessmentFocusLossSignalKindFocusLoss, ItemInstanceID: api.AssessmentItemId(itemID),
|
||||
OccurredAt: at, DurationMs: duration,
|
||||
}),
|
||||
api.NewAssessmentSignalEventCopyAssessmentSignalEvent(api.AssessmentClipboardSignal{
|
||||
Kind: api.AssessmentClipboardSignalKindCopy, ItemInstanceID: api.AssessmentItemId(itemID),
|
||||
OccurredAt: at, SizeBytes: size,
|
||||
}),
|
||||
api.NewAssessmentSignalEventPasteAssessmentSignalEvent(api.AssessmentClipboardSignal{
|
||||
Kind: api.AssessmentClipboardSignalKindPaste, ItemInstanceID: api.AssessmentItemId(itemID),
|
||||
OccurredAt: at, SizeBytes: size,
|
||||
}),
|
||||
api.NewAssessmentSignalEventCutAssessmentSignalEvent(api.AssessmentClipboardSignal{
|
||||
Kind: api.AssessmentClipboardSignalKindCut, ItemInstanceID: api.AssessmentItemId(itemID),
|
||||
OccurredAt: at, SizeBytes: size,
|
||||
}),
|
||||
api.NewAssessmentFullscreenExitSignalAssessmentSignalEvent(api.AssessmentFullscreenExitSignal{
|
||||
Kind: api.AssessmentFullscreenExitSignalKindFullscreenExit, ItemInstanceID: api.AssessmentItemId(itemID),
|
||||
OccurredAt: at,
|
||||
}),
|
||||
}}
|
||||
receipt, err := domain.NewAssessmentSignalReceipt(domain.AssessmentSignalReceiptAccepted, 5, time.Now())
|
||||
if err != nil {
|
||||
t.Fatalf("NewAssessmentSignalReceipt() error = %v", err)
|
||||
}
|
||||
operations := &assessmentSignalOperationsStub{receipt: receipt}
|
||||
handler := NewAssessmentSignalHandler(operations)
|
||||
result, err := handler.RecordMyAssessmentAttemptSignals(principalForTest(actorID), request,
|
||||
api.RecordMyAssessmentAttemptSignalsParams{AttemptID: attemptID, IdempotencyKey: "event-batch"})
|
||||
if err != nil {
|
||||
t.Fatalf("RecordMyAssessmentAttemptSignals() error = %v", err)
|
||||
}
|
||||
response, ok := result.(*api.AssessmentSignalReceiptHeaders)
|
||||
if !ok {
|
||||
t.Fatalf("RecordMyAssessmentAttemptSignals() result = %T, want receipt headers", result)
|
||||
}
|
||||
if response.CacheControl != api.CacheControlNoStoreNoStore || response.Response.AcceptedEvents != 5 ||
|
||||
response.Response.Status != api.AssessmentSignalReceiptStatusAccepted {
|
||||
t.Fatalf("receipt response = %+v", response)
|
||||
}
|
||||
command := operations.command
|
||||
if operations.calls != 1 || command.ActorID != actorID || command.AttemptID != domain.AssessmentAttemptID(attemptID) ||
|
||||
command.IdempotencyKey != "event-batch" || len(command.Events) != 5 {
|
||||
t.Fatalf("record command = %+v, calls %d", command, operations.calls)
|
||||
}
|
||||
wantKinds := []domain.AssessmentSignalKind{
|
||||
domain.AssessmentSignalFocusLoss, domain.AssessmentSignalCopy, domain.AssessmentSignalPaste,
|
||||
domain.AssessmentSignalCut, domain.AssessmentSignalFullscreenExit,
|
||||
}
|
||||
for index, event := range command.Events {
|
||||
if event.Kind() != wantKinds[index] || event.ItemInstanceID() != itemID || !event.OccurredAt().Equal(time.Time(at)) {
|
||||
t.Errorf("event %d = %s / %s / %s", index, event.Kind(), event.ItemInstanceID(), event.OccurredAt())
|
||||
}
|
||||
}
|
||||
if got, ok := command.Events[0].DurationMS(); !ok || got != duration {
|
||||
t.Errorf("focus duration = %d, %v; want %d, true", got, ok, duration)
|
||||
}
|
||||
for _, index := range []int{1, 2, 3} {
|
||||
if got, ok := command.Events[index].SizeBytes(); !ok || got != size {
|
||||
t.Errorf("clipboard size at %d = %d, %v; want %d, true", index, got, ok, size)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAssessmentSignalHandlerMapsAuthorizationAndBusinessProblems(t *testing.T) {
|
||||
for _, testCase := range []struct {
|
||||
name string
|
||||
err error
|
||||
want any
|
||||
}{
|
||||
{name: "forbidden", err: assessmentusecase.ErrAttemptSignalConsentRequired, want: (*api.RecordMyAssessmentAttemptSignalsForbidden)(nil)},
|
||||
{name: "missing attempt", err: assessmentusecase.ErrAttemptNotFound, want: (*api.RecordMyAssessmentAttemptSignalsNotFound)(nil)},
|
||||
{name: "state conflict", err: assessmentusecase.ErrAttemptSignalStateConflict, want: (*api.RecordMyAssessmentAttemptSignalsConflict)(nil)},
|
||||
{name: "key reused", err: assessmentusecase.ErrAttemptKeyReused, want: (*api.RecordMyAssessmentAttemptSignalsUnprocessableEntity)(nil)},
|
||||
{name: "invalid key", err: assessmentusecase.ErrInvalidAttemptKey, want: (*api.RecordMyAssessmentAttemptSignalsBadRequest)(nil)},
|
||||
} {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
result, err := signalFailure(context.Background(), testCase.err)
|
||||
if err != nil {
|
||||
t.Fatalf("signalFailure() error = %v", err)
|
||||
}
|
||||
if result == nil || reflect.TypeOf(result) != reflect.TypeOf(testCase.want) {
|
||||
t.Fatalf("signalFailure() result = %T, want %T", result, testCase.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
result, err := signalFailure(context.Background(), &assessmentusecase.SignalRateLimitError{RetryAt: time.Now().Add(4 * time.Second)})
|
||||
if err != nil {
|
||||
t.Fatalf("signalFailure(rate limit) error = %v", err)
|
||||
}
|
||||
limited, ok := result.(*api.TooManyRequestsHeaders)
|
||||
if !ok {
|
||||
t.Fatalf("signalFailure(rate limit) result = %T", result)
|
||||
}
|
||||
if seconds, present := limited.RetryAfter.Get(); !present || seconds < 1 || seconds > 4 {
|
||||
t.Fatalf("Retry-After = %d, %v; want 1 to 4 seconds", seconds, present)
|
||||
}
|
||||
|
||||
operations := &assessmentSignalOperationsStub{}
|
||||
handler := NewAssessmentSignalHandler(operations)
|
||||
unauthorized, err := handler.RecordMyAssessmentAttemptSignals(context.Background(), &api.AssessmentSignalBatch{}, api.RecordMyAssessmentAttemptSignalsParams{})
|
||||
if err != nil {
|
||||
t.Fatalf("unauthenticated RecordMyAssessmentAttemptSignals() error = %v", err)
|
||||
}
|
||||
if _, ok := unauthorized.(*api.RecordMyAssessmentAttemptSignalsUnauthorized); !ok || operations.calls != 0 {
|
||||
t.Fatalf("unauthenticated result = %T, calls %d", unauthorized, operations.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAssessmentSignalHandlerRejectsWrongVariantAndInternalErrorsPropagate(t *testing.T) {
|
||||
operations := &assessmentSignalOperationsStub{err: errors.New("private storage failure")}
|
||||
handler := NewAssessmentSignalHandler(operations)
|
||||
request := &api.AssessmentSignalBatch{Events: []api.AssessmentSignalEvent{{Type: "unknown"}}}
|
||||
invalid, err := handler.RecordMyAssessmentAttemptSignals(principalForTest(uuid.New()), request,
|
||||
api.RecordMyAssessmentAttemptSignalsParams{AttemptID: uuid.New(), IdempotencyKey: "key"})
|
||||
if err != nil {
|
||||
t.Fatalf("invalid variant error = %v", err)
|
||||
}
|
||||
if _, ok := invalid.(*api.RecordMyAssessmentAttemptSignalsBadRequest); !ok || operations.calls != 0 {
|
||||
t.Fatalf("invalid variant result = %T, calls %d", invalid, operations.calls)
|
||||
}
|
||||
|
||||
request.Events = []api.AssessmentSignalEvent{
|
||||
api.NewAssessmentFullscreenExitSignalAssessmentSignalEvent(api.AssessmentFullscreenExitSignal{
|
||||
Kind: api.AssessmentFullscreenExitSignalKindFullscreenExit, ItemInstanceID: api.AssessmentItemId(uuid.New()),
|
||||
OccurredAt: api.Timestamp(time.Now()),
|
||||
}),
|
||||
}
|
||||
_, err = handler.RecordMyAssessmentAttemptSignals(principalForTest(uuid.New()), request,
|
||||
api.RecordMyAssessmentAttemptSignalsParams{AttemptID: uuid.New(), IdempotencyKey: "key"})
|
||||
if err == nil || err.Error() != "private storage failure" {
|
||||
t.Fatalf("internal error = %v, want sanitized propagation to responder", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
assessmentusecase "lincodex/backend/internal/usecase/assessment"
|
||||
)
|
||||
|
||||
func TestCreateAssessmentAttemptMapsRootAndPublicSnapshot(t *testing.T) {
|
||||
userID := uuid.New()
|
||||
snapshot := assessmentPublicSnapshot()
|
||||
operations := &assessmentOperationsStub{create: outbound.AssessmentAttemptCreateResult{
|
||||
Outcome: outbound.AssessmentAttemptCreateOutcome{StatusCode: 201, Response: snapshot},
|
||||
}}
|
||||
handler := NewAssessmentHandler(operations)
|
||||
request := api.NewAssessmentQualifiedAttemptCreateAssessmentAttemptCreate(api.AssessmentQualifiedAttemptCreate{
|
||||
Kind: api.AssessmentQualifiedAttemptCreateKindRoot, Specialization: "backend", TargetGrade: "junior",
|
||||
TaskLanguage: api.NewNilTaskLanguage(api.TaskLanguage("go")),
|
||||
})
|
||||
response, err := handler.CreateMyAssessmentAttempt(principalForTest(userID), request, api.CreateMyAssessmentAttemptParams{IdempotencyKey: "create-key"})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateMyAssessmentAttempt() error = %v", err)
|
||||
}
|
||||
if operations.createCalls != 1 || operations.createCommand.ActorID != userID || operations.createCommand.Kind != domain.AssessmentAttemptKindRoot ||
|
||||
operations.createCommand.IdempotencyKey != "create-key" || operations.createCommand.Specialization == nil ||
|
||||
*operations.createCommand.Specialization != "backend" || operations.createCommand.TargetGrade == nil ||
|
||||
*operations.createCommand.TargetGrade != "junior" || operations.createCommand.TaskLanguage == nil ||
|
||||
*operations.createCommand.TaskLanguage != "go" {
|
||||
t.Fatalf("CreateAttempt() command = %+v, calls %d", operations.createCommand, operations.createCalls)
|
||||
}
|
||||
headers, ok := response.(*api.AssessmentAttemptHeaders)
|
||||
if !ok || headers.CacheControl != api.CacheControlNoStoreNoStore {
|
||||
t.Fatalf("create response = %T %+v, want no-store headers", response, response)
|
||||
}
|
||||
qualified, ok := headers.Response.GetAssessmentQualifiedAttempt()
|
||||
if !ok || qualified.ID != snapshot.ID.UUID() || qualified.Version != api.AssessmentAttemptVersion(snapshot.Version) ||
|
||||
qualified.CurrentItem.IsNull() || qualified.Progress.MaxItems != snapshot.MaxItems ||
|
||||
qualified.Versions.AlgorithmVersion != api.AssessmentVersionLabel(snapshot.AlgorithmVersion) {
|
||||
t.Fatalf("qualified attempt response = %+v, %v", qualified, ok)
|
||||
}
|
||||
item, ok := qualified.CurrentItem.Get()
|
||||
if !ok || item.Prompt != "Choose the number" || !item.Content.IsNumberItemContent() {
|
||||
t.Fatalf("current item = %+v, %v", item, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateAssessmentAttemptMapsPersistedConflictAndRejectsGuest(t *testing.T) {
|
||||
operations := &assessmentOperationsStub{create: outbound.AssessmentAttemptCreateResult{
|
||||
Outcome: outbound.AssessmentAttemptCreateOutcome{StatusCode: 409, ProblemCode: "state_conflict"},
|
||||
}}
|
||||
handler := NewAssessmentHandler(operations)
|
||||
request := api.NewAssessmentExpressAttemptCreateAssessmentAttemptCreate(api.AssessmentExpressAttemptCreate{
|
||||
Kind: api.AssessmentExpressAttemptCreateKindDemoExpress,
|
||||
})
|
||||
response, err := handler.CreateMyAssessmentAttempt(principalForTest(uuid.New()), request, api.CreateMyAssessmentAttemptParams{IdempotencyKey: "blocked"})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateMyAssessmentAttempt() error = %v", err)
|
||||
}
|
||||
if _, ok := response.(*api.CreateMyAssessmentAttemptConflict); !ok {
|
||||
t.Fatalf("state conflict response = %T, want conflict", response)
|
||||
}
|
||||
if operations.createCommand.Kind != domain.AssessmentAttemptKindDemoExpress || operations.createCommand.Specialization != nil {
|
||||
t.Fatalf("express command = %+v", operations.createCommand)
|
||||
}
|
||||
response, err = handler.CreateMyAssessmentAttempt(context.Background(), request, api.CreateMyAssessmentAttemptParams{IdempotencyKey: "blocked"})
|
||||
if err != nil {
|
||||
t.Fatalf("guest CreateMyAssessmentAttempt() error = %v", err)
|
||||
}
|
||||
if _, ok := response.(*api.CreateMyAssessmentAttemptUnauthorized); !ok || operations.createCalls != 1 {
|
||||
t.Fatalf("guest create response = %T, operations called %d", response, operations.createCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartAndReadAssessmentAttemptUseVerifiedPrincipal(t *testing.T) {
|
||||
userID := uuid.New()
|
||||
snapshot := assessmentPublicSnapshot()
|
||||
operations := &assessmentOperationsStub{
|
||||
read: snapshot,
|
||||
start: outbound.AssessmentAttemptSessionResult{Response: snapshot},
|
||||
}
|
||||
handler := NewAssessmentHandler(operations)
|
||||
ctx := principalForTest(userID)
|
||||
read, err := handler.GetMyAssessmentAttempt(ctx, api.GetMyAssessmentAttemptParams{AttemptID: snapshot.ID.UUID()})
|
||||
if err != nil {
|
||||
t.Fatalf("GetMyAssessmentAttempt() error = %v", err)
|
||||
}
|
||||
if operations.readUserID != userID || operations.readAttemptID != snapshot.ID {
|
||||
t.Fatalf("GetMyAttempt() IDs = %s/%s", operations.readUserID, operations.readAttemptID)
|
||||
}
|
||||
if _, ok := read.(*api.AssessmentAttemptHeaders); !ok {
|
||||
t.Fatalf("read response = %T, want attempt headers", read)
|
||||
}
|
||||
started, err := handler.StartMyAssessmentAttemptSession(ctx, &api.AssessmentAttemptSessionStart{
|
||||
ExpectedVersion: api.AssessmentAttemptVersion(7),
|
||||
}, api.StartMyAssessmentAttemptSessionParams{AttemptID: snapshot.ID.UUID(), IdempotencyKey: "session-key"})
|
||||
if err != nil {
|
||||
t.Fatalf("StartMyAssessmentAttemptSession() error = %v", err)
|
||||
}
|
||||
if operations.startCommand.ActorID != userID || operations.startCommand.AttemptID != snapshot.ID ||
|
||||
operations.startCommand.ExpectedVersion != 7 || operations.startCommand.IdempotencyKey != "session-key" {
|
||||
t.Fatalf("StartSession() command = %+v", operations.startCommand)
|
||||
}
|
||||
if _, ok := started.(*api.AssessmentAttemptHeaders); !ok {
|
||||
t.Fatalf("start response = %T, want attempt headers", started)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAssessmentAttemptFailuresMapWithoutExposingInternalErrors(t *testing.T) {
|
||||
operations := &assessmentOperationsStub{startErr: assessmentusecase.ErrAttemptVersionConflict}
|
||||
handler := NewAssessmentHandler(operations)
|
||||
response, err := handler.StartMyAssessmentAttemptSession(principalForTest(uuid.New()),
|
||||
&api.AssessmentAttemptSessionStart{ExpectedVersion: 3},
|
||||
api.StartMyAssessmentAttemptSessionParams{AttemptID: uuid.New(), IdempotencyKey: "key"})
|
||||
if err != nil {
|
||||
t.Fatalf("StartMyAssessmentAttemptSession() error = %v", err)
|
||||
}
|
||||
problem, ok := response.(*api.StartMyAssessmentAttemptSessionPreconditionFailed)
|
||||
if !ok || api.Problem(*problem).Code != api.ProblemCodeVersionConflict {
|
||||
t.Fatalf("version conflict response = %T %+v", response, response)
|
||||
}
|
||||
|
||||
operations.readErr = assessmentusecase.ErrAttemptNotFound
|
||||
read, err := handler.GetMyAssessmentAttempt(principalForTest(uuid.New()), api.GetMyAssessmentAttemptParams{AttemptID: uuid.New()})
|
||||
if err != nil {
|
||||
t.Fatalf("GetMyAssessmentAttempt() error = %v", err)
|
||||
}
|
||||
if _, ok := read.(*api.GetMyAssessmentAttemptNotFound); !ok {
|
||||
t.Fatalf("missing attempt response = %T", read)
|
||||
}
|
||||
|
||||
operations.createErr = &assessmentusecase.AttemptFieldError{Pointer: "/task_language", Reason: "is not available"}
|
||||
create, err := handler.CreateMyAssessmentAttempt(principalForTest(uuid.New()), api.NewAssessmentQualifiedAttemptCreateAssessmentAttemptCreate(
|
||||
api.AssessmentQualifiedAttemptCreate{Kind: api.AssessmentQualifiedAttemptCreateKindRoot, Specialization: "backend", TargetGrade: "junior"},
|
||||
), api.CreateMyAssessmentAttemptParams{IdempotencyKey: "key"})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateMyAssessmentAttempt() error = %v", err)
|
||||
}
|
||||
badRequest, ok := create.(*api.CreateMyAssessmentAttemptBadRequest)
|
||||
if !ok || len(api.Problem(*badRequest).Errors) != 1 || api.Problem(*badRequest).Errors[0].Pointer != "/task_language" {
|
||||
t.Fatalf("validation response = %T %+v", create, create)
|
||||
}
|
||||
|
||||
operations.startErr = errors.New("private database detail")
|
||||
if _, err := handler.StartMyAssessmentAttemptSession(principalForTest(uuid.New()),
|
||||
&api.AssessmentAttemptSessionStart{ExpectedVersion: 1},
|
||||
api.StartMyAssessmentAttemptSessionParams{AttemptID: uuid.New(), IdempotencyKey: "key"}); err == nil || err.Error() != "private database detail" {
|
||||
t.Fatalf("unexpected internal error mapping = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfirmedAttemptResultDoesNotInferStoredGradeFromTarget(t *testing.T) {
|
||||
result := assessmentusecase.AssessmentAttemptResult{
|
||||
Attempt: domain.AssessmentAttemptPublicSnapshot{
|
||||
Kind: domain.AssessmentAttemptKindRoot, TargetGrade: domainCodePointer(domain.GradeCode("junior")),
|
||||
},
|
||||
Outcome: domain.AssessmentAttemptOutcomeConfirmed,
|
||||
}
|
||||
fields, err := assessmentRealResultFields(result)
|
||||
if err != nil {
|
||||
t.Fatalf("assessmentRealResultFields() error = %v", err)
|
||||
}
|
||||
if !fields.confirmedGrade.IsNull() {
|
||||
t.Fatalf("confirmed grade = %+v, want null until a stored grade decision exists", fields.confirmedGrade)
|
||||
}
|
||||
}
|
||||
|
||||
type assessmentOperationsStub struct {
|
||||
availabilityCalls int
|
||||
availabilityUserID uuid.UUID
|
||||
availability assessmentusecase.AssessmentAvailability
|
||||
availabilityErr error
|
||||
createCalls int
|
||||
createCommand assessmentusecase.CreateAttemptCommand
|
||||
create outbound.AssessmentAttemptCreateResult
|
||||
createErr error
|
||||
read domain.AssessmentAttemptPublicSnapshot
|
||||
readUserID uuid.UUID
|
||||
readAttemptID domain.AssessmentAttemptID
|
||||
readErr error
|
||||
startCommand assessmentusecase.StartAttemptSessionCommand
|
||||
start outbound.AssessmentAttemptSessionResult
|
||||
startErr error
|
||||
}
|
||||
|
||||
func (stub *assessmentOperationsStub) GetMyAssessmentAvailability(
|
||||
_ context.Context,
|
||||
userID uuid.UUID,
|
||||
) (assessmentusecase.AssessmentAvailability, error) {
|
||||
stub.availabilityCalls++
|
||||
stub.availabilityUserID = userID
|
||||
return stub.availability, stub.availabilityErr
|
||||
}
|
||||
|
||||
func (stub *assessmentOperationsStub) CreateAttempt(_ context.Context, command assessmentusecase.CreateAttemptCommand) (outbound.AssessmentAttemptCreateResult, error) {
|
||||
stub.createCalls++
|
||||
stub.createCommand = command
|
||||
return stub.create, stub.createErr
|
||||
}
|
||||
|
||||
func (stub *assessmentOperationsStub) GetMyAttempt(_ context.Context, userID uuid.UUID, attemptID domain.AssessmentAttemptID) (domain.AssessmentAttemptPublicSnapshot, error) {
|
||||
stub.readUserID, stub.readAttemptID = userID, attemptID
|
||||
return stub.read, stub.readErr
|
||||
}
|
||||
|
||||
func (stub *assessmentOperationsStub) StartSession(_ context.Context, command assessmentusecase.StartAttemptSessionCommand) (outbound.AssessmentAttemptSessionResult, error) {
|
||||
stub.startCommand = command
|
||||
return stub.start, stub.startErr
|
||||
}
|
||||
|
||||
func principalForTest(userID uuid.UUID) context.Context {
|
||||
return context.WithValue(context.Background(), principalContextKey{}, Principal{UserID: userID, EmailVerified: true})
|
||||
}
|
||||
|
||||
func assessmentPublicSnapshot() domain.AssessmentAttemptPublicSnapshot {
|
||||
started := time.Date(2026, time.October, 7, 12, 0, 0, 0, time.UTC)
|
||||
return domain.AssessmentAttemptPublicSnapshot{
|
||||
ID: domain.AssessmentAttemptID(uuid.New()), Version: 7, Kind: domain.AssessmentAttemptKindRoot,
|
||||
Mode: domain.AssessmentAttemptModeDemoBasic, State: domain.AssessmentAttemptStateInProgress,
|
||||
Specialization: domainCodePointer(domain.SpecializationCode("backend")), TargetGrade: domainCodePointer(domain.GradeCode("junior")),
|
||||
PolicyVersion: 2, BankVersion: "bank-v1", AlgorithmVersion: "assessment.v1", StartedAt: started,
|
||||
ExpiresAt: started.Add(30 * time.Minute), MaxItems: 10, SessionsUsed: 1, MaxSessions: 2, IdleTimeout: 1800,
|
||||
CurrentItem: &domain.AssessmentAttemptPublicItem{ID: uuid.New(), Sequence: 1, Prompt: "Choose the number",
|
||||
Content: domain.AssessmentAttemptPublicItemContent{Format: "number"}}, Practices: []domain.AssessmentAttemptPublicPractice{},
|
||||
}
|
||||
}
|
||||
|
||||
func domainCodePointer[T ~string](value T) *T {
|
||||
return &value
|
||||
}
|
||||
@@ -0,0 +1,643 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
"lincodex/backend/internal/adapter/primary/http/problem"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
needusecase "lincodex/backend/internal/usecase/need"
|
||||
)
|
||||
|
||||
const (
|
||||
needCursorVersion = 1
|
||||
needCursorBytes = 61
|
||||
defaultNeedLimit = 20
|
||||
maxNeedCursorTime = uint64(253402300799)
|
||||
)
|
||||
|
||||
// NeedOperations are the owner-scoped need reads and commands served by HTTP.
|
||||
type NeedOperations interface {
|
||||
Create(ctx context.Context, command needusecase.CreateCommand) (domain.NeedResponseSnapshot, error)
|
||||
Get(ctx context.Context, actorID, organizationID, needID uuid.UUID) (domain.Need, error)
|
||||
List(ctx context.Context, command needusecase.ListCommand) (outbound.NeedPage, error)
|
||||
Update(ctx context.Context, command needusecase.UpdateCommand) (domain.Need, error)
|
||||
}
|
||||
|
||||
// NeedHandler serves company need routes without trusting membership in a
|
||||
// request body or retaining tenant data between requests.
|
||||
type NeedHandler struct {
|
||||
operations NeedOperations
|
||||
}
|
||||
|
||||
func NewNeedHandler(operations NeedOperations) *NeedHandler {
|
||||
if operations == nil {
|
||||
panic("v1.NewNeedHandler - need operations must not be nil")
|
||||
}
|
||||
return &NeedHandler{operations: operations}
|
||||
}
|
||||
|
||||
func (handler *Handler) ListOrganizationNeeds(ctx context.Context, params api.ListOrganizationNeedsParams) (api.ListOrganizationNeedsRes, error) {
|
||||
if handler.need == nil {
|
||||
return handler.UnimplementedHandler.ListOrganizationNeeds(ctx, params)
|
||||
}
|
||||
return handler.need.ListOrganizationNeeds(ctx, params)
|
||||
}
|
||||
|
||||
func (handler *Handler) CreateOrganizationNeed(ctx context.Context, request *api.NeedCreate, params api.CreateOrganizationNeedParams) (api.CreateOrganizationNeedRes, error) {
|
||||
if handler.need == nil {
|
||||
return handler.UnimplementedHandler.CreateOrganizationNeed(ctx, request, params)
|
||||
}
|
||||
return handler.need.CreateOrganizationNeed(ctx, request, params)
|
||||
}
|
||||
|
||||
func (handler *Handler) GetOrganizationNeed(ctx context.Context, params api.GetOrganizationNeedParams) (api.GetOrganizationNeedRes, error) {
|
||||
if handler.need == nil {
|
||||
return handler.UnimplementedHandler.GetOrganizationNeed(ctx, params)
|
||||
}
|
||||
return handler.need.GetOrganizationNeed(ctx, params)
|
||||
}
|
||||
|
||||
func (handler *Handler) UpdateOrganizationNeed(ctx context.Context, request *api.NeedUpdate, params api.UpdateOrganizationNeedParams) (api.UpdateOrganizationNeedRes, error) {
|
||||
if handler.need == nil {
|
||||
return handler.UnimplementedHandler.UpdateOrganizationNeed(ctx, request, params)
|
||||
}
|
||||
return handler.need.UpdateOrganizationNeed(ctx, request, params)
|
||||
}
|
||||
|
||||
func (handler *NeedHandler) CreateOrganizationNeed(
|
||||
ctx context.Context,
|
||||
request *api.NeedCreate,
|
||||
params api.CreateOrganizationNeedParams,
|
||||
) (api.CreateOrganizationNeedRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.CreateOrganizationNeedUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
if request == nil {
|
||||
return (*api.CreateOrganizationNeedBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
|
||||
}
|
||||
canonical, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("NeedHandler.CreateOrganizationNeed - encode canonical request")
|
||||
}
|
||||
snapshot, err := handler.operations.Create(ctx, needusecase.CreateCommand{
|
||||
ActorID: principal.UserID, OrganizationID: params.OrgID, IdempotencyKey: params.IdempotencyKey,
|
||||
CanonicalBody: canonical, Input: createNeedInput(request),
|
||||
})
|
||||
if err != nil {
|
||||
return needCreateFailure(ctx, err)
|
||||
}
|
||||
return &api.NeedHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: needResponse(snapshot)}, nil
|
||||
}
|
||||
|
||||
func (handler *NeedHandler) GetOrganizationNeed(
|
||||
ctx context.Context,
|
||||
params api.GetOrganizationNeedParams,
|
||||
) (api.GetOrganizationNeedRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.GetOrganizationNeedUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
need, err := handler.operations.Get(ctx, principal.UserID, params.OrgID, params.NeedID)
|
||||
if err != nil {
|
||||
return needReadFailure(ctx, err)
|
||||
}
|
||||
return &api.NeedHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: needResponse(need.ResponseSnapshot())}, nil
|
||||
}
|
||||
|
||||
func (handler *NeedHandler) ListOrganizationNeeds(
|
||||
ctx context.Context,
|
||||
params api.ListOrganizationNeedsParams,
|
||||
) (api.ListOrganizationNeedsRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.ListOrganizationNeedsUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
command, pointer := needListCommand(principal.UserID, params)
|
||||
if pointer != "" {
|
||||
return needListInvalid(ctx, pointer), nil
|
||||
}
|
||||
page, err := handler.operations.List(ctx, command)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, needusecase.ErrForbidden), errors.Is(err, needusecase.ErrEmailNotVerified):
|
||||
return (*api.ListOrganizationNeedsForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
case errors.Is(err, outbound.ErrOrganizationNotFound):
|
||||
return (*api.ListOrganizationNeedsNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
items := make([]api.NeedSummary, 0, len(page.Items))
|
||||
for _, item := range page.Items {
|
||||
items = append(items, needSummaryFromDomain(item))
|
||||
}
|
||||
next := api.NilString{}
|
||||
next.SetToNull()
|
||||
if page.HasMore && len(page.Items) > 0 {
|
||||
cursor, err := encodeNeedCursor(principal.UserID, params.OrgID, outbound.NeedCreationPosition(page.Items[len(page.Items)-1]))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("NeedHandler.ListOrganizationNeeds - encode cursor: %w", err)
|
||||
}
|
||||
next.SetTo(cursor)
|
||||
}
|
||||
return &api.NeedListHeaders{
|
||||
CacheControl: api.CacheControlNoStoreNoStore,
|
||||
Response: api.NeedList{Items: items, Page: api.PageInfo{HasMore: page.HasMore, NextCursor: next}},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (handler *NeedHandler) UpdateOrganizationNeed(
|
||||
ctx context.Context,
|
||||
request *api.NeedUpdate,
|
||||
params api.UpdateOrganizationNeedParams,
|
||||
) (api.UpdateOrganizationNeedRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.UpdateOrganizationNeedUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
if request == nil {
|
||||
return (*api.UpdateOrganizationNeedBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
|
||||
}
|
||||
need, err := handler.operations.Update(ctx, needusecase.UpdateCommand{
|
||||
ActorID: principal.UserID, OrganizationID: params.OrgID, NeedID: params.NeedID, Input: updateNeedInput(request),
|
||||
})
|
||||
if err != nil {
|
||||
return needUpdateFailure(ctx, err)
|
||||
}
|
||||
return &api.NeedHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: needResponse(need.ResponseSnapshot())}, nil
|
||||
}
|
||||
|
||||
func needCreateFailure(ctx context.Context, err error) (api.CreateOrganizationNeedRes, error) {
|
||||
switch {
|
||||
case errors.Is(err, needusecase.ErrForbidden), errors.Is(err, needusecase.ErrEmailNotVerified), errors.Is(err, outbound.ErrOrganizationManagerRequired):
|
||||
return (*api.CreateOrganizationNeedForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
case errors.Is(err, outbound.ErrOrganizationNotFound):
|
||||
return (*api.CreateOrganizationNeedNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
|
||||
case errors.Is(err, needusecase.ErrIdempotencyKeyReused):
|
||||
return (*api.CreateOrganizationNeedUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil
|
||||
case errors.Is(err, needusecase.ErrInvalidIdempotencyKey):
|
||||
return (*api.CreateOrganizationNeedBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationHeader, "/Idempotency-Key").Response), nil
|
||||
case errors.Is(err, needusecase.ErrInvalidRequest), errors.Is(err, domain.ErrInvalidNeed):
|
||||
return (*api.CreateOrganizationNeedBadRequest)(needValidationProblem(ctx, err)), nil
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
func needReadFailure(ctx context.Context, err error) (api.GetOrganizationNeedRes, error) {
|
||||
switch {
|
||||
case errors.Is(err, needusecase.ErrForbidden), errors.Is(err, needusecase.ErrEmailNotVerified), errors.Is(err, outbound.ErrOrganizationManagerRequired):
|
||||
return (*api.GetOrganizationNeedForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
case errors.Is(err, outbound.ErrOrganizationNotFound), errors.Is(err, outbound.ErrNeedNotFound):
|
||||
return (*api.GetOrganizationNeedNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
func needUpdateFailure(ctx context.Context, err error) (api.UpdateOrganizationNeedRes, error) {
|
||||
switch {
|
||||
case errors.Is(err, needusecase.ErrForbidden), errors.Is(err, needusecase.ErrEmailNotVerified), errors.Is(err, outbound.ErrOrganizationManagerRequired):
|
||||
return (*api.UpdateOrganizationNeedForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
case errors.Is(err, outbound.ErrOrganizationNotFound), errors.Is(err, outbound.ErrNeedNotFound):
|
||||
return (*api.UpdateOrganizationNeedNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
|
||||
case errors.Is(err, domain.ErrNeedVersionConflict), errors.Is(err, outbound.ErrNeedVersionConflict):
|
||||
return (*api.UpdateOrganizationNeedPreconditionFailed)(&problem.New(ctx, api.ProblemCodeVersionConflict).Response), nil
|
||||
case errors.Is(err, needusecase.ErrInvalidRequest), errors.Is(err, domain.ErrInvalidNeed):
|
||||
return (*api.UpdateOrganizationNeedBadRequest)(needValidationProblem(ctx, err)), nil
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
func needValidationProblem(ctx context.Context, err error) *api.Problem {
|
||||
field, ok := errors.AsType[*needusecase.ValidationError](err)
|
||||
if !ok {
|
||||
return &problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response
|
||||
}
|
||||
return &problem.InvalidField(ctx, api.ProblemFieldLocationBody, field.Pointer).Response
|
||||
}
|
||||
|
||||
func needListInvalid(ctx context.Context, pointer string) *api.ListOrganizationNeedsBadRequest {
|
||||
return (*api.ListOrganizationNeedsBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationQuery, "/"+pointer).Response)
|
||||
}
|
||||
|
||||
func needListCommand(actorID uuid.UUID, params api.ListOrganizationNeedsParams) (needusecase.ListCommand, string) {
|
||||
limit, ok := params.Limit.Get()
|
||||
if !ok {
|
||||
limit = defaultNeedLimit
|
||||
}
|
||||
if limit < 1 || limit > outbound.MaxNeedPageSize {
|
||||
return needusecase.ListCommand{}, "limit"
|
||||
}
|
||||
command := needusecase.ListCommand{ActorID: actorID, OrganizationID: params.OrgID, Limit: limit}
|
||||
if cursor, ok := params.Cursor.Get(); ok {
|
||||
position, err := decodeNeedCursor(cursor, actorID, params.OrgID)
|
||||
if err != nil {
|
||||
return needusecase.ListCommand{}, "cursor"
|
||||
}
|
||||
command.After = &position
|
||||
}
|
||||
return command, ""
|
||||
}
|
||||
|
||||
func encodeNeedCursor(actorID, organizationID uuid.UUID, position outbound.NeedListPosition) (string, error) {
|
||||
seconds, nanos := position.CreatedAt.Unix(), position.CreatedAt.Nanosecond()
|
||||
if actorID == uuid.Nil || organizationID == uuid.Nil || position.NeedID == uuid.Nil || position.CreatedAt.IsZero() ||
|
||||
position.CreatedAt.Year() < 1 || position.CreatedAt.Year() > 9999 || seconds < 0 || uint64(seconds) > maxNeedCursorTime ||
|
||||
nanos < 0 || nanos >= 1_000_000_000 || nanos%int(time.Microsecond) != 0 {
|
||||
return "", errors.New("need cursor requires an actor, organization, and valid page position")
|
||||
}
|
||||
var value [needCursorBytes]byte
|
||||
value[0] = needCursorVersion
|
||||
copy(value[1:17], actorID[:])
|
||||
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.NeedID[:])
|
||||
return base64.RawURLEncoding.EncodeToString(value[:]), nil
|
||||
}
|
||||
|
||||
func decodeNeedCursor(cursor string, actorID, organizationID uuid.UUID) (outbound.NeedListPosition, error) {
|
||||
value, err := base64.RawURLEncoding.DecodeString(cursor)
|
||||
if err != nil || len(value) != needCursorBytes || actorID == uuid.Nil || organizationID == uuid.Nil ||
|
||||
base64.RawURLEncoding.EncodeToString(value) != cursor || value[0] != needCursorVersion ||
|
||||
uuid.UUID(value[1:17]) != actorID || uuid.UUID(value[17:33]) != organizationID {
|
||||
return outbound.NeedListPosition{}, errors.New("need cursor is invalid")
|
||||
}
|
||||
seconds := binary.BigEndian.Uint64(value[33:41])
|
||||
nanos := binary.BigEndian.Uint32(value[41:45])
|
||||
needID := uuid.UUID(value[45:61])
|
||||
if seconds > uint64(math.MaxInt64) || seconds > maxNeedCursorTime || nanos >= 1_000_000_000 || nanos%1_000 != 0 || needID == uuid.Nil {
|
||||
return outbound.NeedListPosition{}, errors.New("need cursor position is invalid")
|
||||
}
|
||||
createdAt := time.Unix(int64(seconds), int64(nanos)).UTC()
|
||||
if createdAt.IsZero() {
|
||||
return outbound.NeedListPosition{}, errors.New("need cursor timestamp is invalid")
|
||||
}
|
||||
return outbound.NeedListPosition{CreatedAt: createdAt, NeedID: needID}, nil
|
||||
}
|
||||
|
||||
func createNeedInput(request *api.NeedCreate) needusecase.CreateInput {
|
||||
input := needusecase.CreateInput{Title: string(request.Title)}
|
||||
input.VacancyID = uuidField(request.VacancyID.Set, request.VacancyID.Null, request.VacancyID.Value)
|
||||
input.SourceText = stringField(request.SourceText.Set, request.SourceText.Null, string(request.SourceText.Value))
|
||||
input.Specialization = specializationInput(request.Specialization.Set, request.Specialization.Null, request.Specialization.Value)
|
||||
input.Grade = gradeInput(request.Grade.Set, request.Grade.Null, request.Grade.Value)
|
||||
input.Domain = domainInput(request.Domain.Set, request.Domain.Null, request.Domain.Value)
|
||||
input.WorkFormats = workFormatsInput(request.WorkFormats.Set, request.WorkFormats.Null, request.WorkFormats.Value)
|
||||
input.Location = locationInput(request.Location.Set, request.Location.Null, request.Location.Value)
|
||||
input.Salary = salaryInput(request.Salary.Set, request.Salary.Null, request.Salary.Value)
|
||||
input.RequiredSkills = skillInputs(request.RequiredSkills)
|
||||
input.DesiredSkills = skillInputs(request.DesiredSkills)
|
||||
input.Tasks = taskInputs(request.Tasks)
|
||||
return input
|
||||
}
|
||||
|
||||
func updateNeedInput(request *api.NeedUpdate) needusecase.UpdateInput {
|
||||
input := needusecase.UpdateInput{ExpectedVersion: int64(request.ExpectedVersion)}
|
||||
if request.Title.Set {
|
||||
input.Title = needusecase.Field[string]{Set: true, Value: string(request.Title.Value)}
|
||||
}
|
||||
input.VacancyID = uuidField(request.VacancyID.Set, request.VacancyID.Null, request.VacancyID.Value)
|
||||
input.SourceText = stringField(request.SourceText.Set, request.SourceText.Null, string(request.SourceText.Value))
|
||||
input.Specialization = specializationInput(request.Specialization.Set, request.Specialization.Null, request.Specialization.Value)
|
||||
input.Grade = gradeInput(request.Grade.Set, request.Grade.Null, request.Grade.Value)
|
||||
input.Domain = domainInput(request.Domain.Set, request.Domain.Null, request.Domain.Value)
|
||||
input.WorkFormats = workFormatsInput(request.WorkFormats.Set, request.WorkFormats.Null, request.WorkFormats.Value)
|
||||
input.Location = locationInput(request.Location.Set, request.Location.Null, request.Location.Value)
|
||||
input.Salary = salaryInput(request.Salary.Set, request.Salary.Null, request.Salary.Value)
|
||||
input.RequiredSkills = skillInputs(request.RequiredSkills)
|
||||
input.DesiredSkills = skillInputs(request.DesiredSkills)
|
||||
input.Tasks = taskInputs(request.Tasks)
|
||||
return input
|
||||
}
|
||||
|
||||
func uuidField(set, null bool, value uuid.UUID) needusecase.Field[uuid.UUID] {
|
||||
return needusecase.Field[uuid.UUID]{Set: set, Null: null, Value: value}
|
||||
}
|
||||
|
||||
func stringField(set, null bool, value string) needusecase.Field[string] {
|
||||
return needusecase.Field[string]{Set: set, Null: null, Value: value}
|
||||
}
|
||||
|
||||
func specializationInput(set, null bool, value api.NeedSpecializationInput) needusecase.Field[needusecase.Decision[domain.SpecializationCode]] {
|
||||
return needusecase.Field[needusecase.Decision[domain.SpecializationCode]]{
|
||||
Set: set, Null: null, Value: needusecase.Decision[domain.SpecializationCode]{Value: domain.SpecializationCode(value.Value), Status: domain.NeedValueStatus(value.Status)},
|
||||
}
|
||||
}
|
||||
|
||||
func gradeInput(set, null bool, value api.NeedGradeInput) needusecase.Field[needusecase.Decision[domain.GradeCode]] {
|
||||
return needusecase.Field[needusecase.Decision[domain.GradeCode]]{
|
||||
Set: set, Null: null, Value: needusecase.Decision[domain.GradeCode]{Value: domain.GradeCode(value.Value), Status: domain.NeedValueStatus(value.Status)},
|
||||
}
|
||||
}
|
||||
|
||||
func domainInput(set, null bool, value api.NeedDomainInput) needusecase.Field[needusecase.Decision[string]] {
|
||||
return needusecase.Field[needusecase.Decision[string]]{
|
||||
Set: set, Null: null, Value: needusecase.Decision[string]{Value: string(value.Value), Status: domain.NeedValueStatus(value.Status)},
|
||||
}
|
||||
}
|
||||
|
||||
func workFormatsInput(set, null bool, value api.NeedWorkFormatsInput) needusecase.Field[needusecase.Decision[[]domain.NeedWorkFormat]] {
|
||||
formats := make([]domain.NeedWorkFormat, 0, len(value.Value))
|
||||
for _, format := range value.Value {
|
||||
formats = append(formats, domain.NeedWorkFormat(format))
|
||||
}
|
||||
return needusecase.Field[needusecase.Decision[[]domain.NeedWorkFormat]]{
|
||||
Set: set, Null: null, Value: needusecase.Decision[[]domain.NeedWorkFormat]{Value: formats, Status: domain.NeedValueStatus(value.Status)},
|
||||
}
|
||||
}
|
||||
|
||||
func locationInput(set, null bool, value api.NeedLocationInput) needusecase.Field[needusecase.Decision[string]] {
|
||||
return needusecase.Field[needusecase.Decision[string]]{
|
||||
Set: set, Null: null, Value: needusecase.Decision[string]{Value: string(value.Value), Status: domain.NeedValueStatus(value.Status)},
|
||||
}
|
||||
}
|
||||
|
||||
func salaryInput(set, null bool, value api.NeedSalaryInput) needusecase.Field[needusecase.Decision[domain.NeedSalaryRange]] {
|
||||
rangeValue := domain.NeedSalaryRange{
|
||||
SalaryFrom: int64(value.Value.SalaryFrom), SalaryTo: int64(value.Value.SalaryTo),
|
||||
Currency: string(value.Value.Currency), Period: string(value.Value.Period), TaxBasis: string(value.Value.TaxBasis),
|
||||
}
|
||||
return needusecase.Field[needusecase.Decision[domain.NeedSalaryRange]]{
|
||||
Set: set, Null: null, Value: needusecase.Decision[domain.NeedSalaryRange]{Value: rangeValue, Status: domain.NeedValueStatus(value.Status)},
|
||||
}
|
||||
}
|
||||
|
||||
func skillInputs(values []api.NeedSkillInput) []needusecase.SkillInput {
|
||||
if values == nil {
|
||||
return nil
|
||||
}
|
||||
result := make([]needusecase.SkillInput, 0, len(values))
|
||||
for _, value := range values {
|
||||
result = append(result, needusecase.SkillInput{Name: string(value.Name), Status: domain.NeedItemStatus(value.Status)})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func taskInputs(values []api.NeedTaskInput) []needusecase.TaskInput {
|
||||
if values == nil {
|
||||
return nil
|
||||
}
|
||||
result := make([]needusecase.TaskInput, 0, len(values))
|
||||
for _, value := range values {
|
||||
result = append(result, needusecase.TaskInput{Text: string(value.Text), Status: domain.NeedItemStatus(value.Status)})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func needResponse(snapshot domain.NeedResponseSnapshot) api.Need {
|
||||
needSnapshot := snapshot.Need
|
||||
return api.Need{
|
||||
ID: needSnapshot.ID, OrganizationID: needSnapshot.OrganizationID,
|
||||
VacancyID: needNullableUUID(needSnapshot.VacancyID), Title: api.NeedTitle(needSnapshot.Title),
|
||||
SourceText: needNullableSourceText(needSnapshot.SourceText), Version: api.NeedVersion(needSnapshot.Version),
|
||||
RequirementsVersion: api.NeedVersion(needSnapshot.RequirementsVersion),
|
||||
Requirements: needRequirements(needSnapshot.Requirements), Readiness: needReadiness(snapshot.Readiness),
|
||||
Recommendations: needRecommendations(snapshot.Recommendations),
|
||||
CreatedAt: api.Timestamp(needSnapshot.CreatedAt), UpdatedAt: api.Timestamp(needSnapshot.UpdatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func needSummaryFromDomain(need domain.Need) api.NeedSummary {
|
||||
snapshot := need.Snapshot()
|
||||
return api.NeedSummary{
|
||||
ID: snapshot.ID, VacancyID: needNullableUUID(snapshot.VacancyID), Title: api.NeedTitle(snapshot.Title),
|
||||
Version: api.NeedVersion(snapshot.Version), Specialization: needSpecialization(snapshot.Requirements.Specialization),
|
||||
Grade: needGrade(snapshot.Requirements.Grade), Readiness: needReadiness(need.Readiness()),
|
||||
CreatedAt: api.Timestamp(snapshot.CreatedAt), UpdatedAt: api.Timestamp(snapshot.UpdatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func needRequirements(requirements domain.NeedRequirements) api.NeedRequirementSet {
|
||||
return api.NeedRequirementSet{
|
||||
Specialization: needSpecialization(requirements.Specialization), Grade: needGrade(requirements.Grade),
|
||||
RequiredSkills: needSkills(requirements.RequiredSkills), DesiredSkills: needSkills(requirements.DesiredSkills),
|
||||
Tasks: needTasks(requirements.Tasks), Domain: needDomain(requirements.Domain),
|
||||
WorkFormats: needWorkFormats(requirements.WorkFormats), Location: needLocation(requirements.Location),
|
||||
Salary: needSalary(requirements.Salary),
|
||||
}
|
||||
}
|
||||
|
||||
func needSpecialization(value domain.NeedValue[domain.SpecializationCode]) api.NeedSpecialization {
|
||||
result := api.NeedSpecialization{Status: api.NeedValueStatus(value.Status), Source: needNullableSource(value.Source)}
|
||||
if value.Value == nil {
|
||||
result.Value.SetToNull()
|
||||
} else {
|
||||
result.Value.SetTo(api.SpecializationCode(*value.Value))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func needGrade(value domain.NeedValue[domain.GradeCode]) api.NeedGrade {
|
||||
result := api.NeedGrade{Status: api.NeedValueStatus(value.Status), Source: needNullableSource(value.Source)}
|
||||
if value.Value == nil {
|
||||
result.Value.SetToNull()
|
||||
} else {
|
||||
result.Value.SetTo(api.GradeCode(*value.Value))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func needDomain(value domain.NeedValue[string]) api.NeedDomain {
|
||||
result := api.NeedDomain{Status: api.NeedValueStatus(value.Status), Source: needNullableSource(value.Source)}
|
||||
if value.Value == nil {
|
||||
result.Value.SetToNull()
|
||||
} else {
|
||||
result.Value.SetTo(api.NeedDomainName(*value.Value))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func needLocation(value domain.NeedValue[string]) api.NeedLocation {
|
||||
result := api.NeedLocation{Status: api.NeedValueStatus(value.Status), Source: needNullableSource(value.Source)}
|
||||
if value.Value == nil {
|
||||
result.Value.SetToNull()
|
||||
} else {
|
||||
result.Value.SetTo(api.NeedLocationName(*value.Value))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func needWorkFormats(value domain.NeedValue[[]domain.NeedWorkFormat]) api.NeedWorkFormats {
|
||||
result := api.NeedWorkFormats{Status: api.NeedValueStatus(value.Status), Source: needNullableSource(value.Source)}
|
||||
if value.Value == nil {
|
||||
result.Value = nil
|
||||
return result
|
||||
}
|
||||
result.Value = make([]api.WorkFormat, 0, len(*value.Value))
|
||||
for _, format := range *value.Value {
|
||||
result.Value = append(result.Value, api.WorkFormat(format))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func needSalary(value domain.NeedValue[domain.NeedSalaryRange]) api.NeedSalary {
|
||||
result := api.NeedSalary{Status: api.NeedValueStatus(value.Status), Source: needNullableSource(value.Source)}
|
||||
if value.Value == nil {
|
||||
result.Value.SetToNull()
|
||||
return result
|
||||
}
|
||||
rangeValue := api.SalaryRange{
|
||||
SalaryFrom: api.RubAmount(value.Value.SalaryFrom), SalaryTo: api.RubAmount(value.Value.SalaryTo),
|
||||
Currency: api.CurrencyCode(value.Value.Currency), Period: api.SalaryPeriod(value.Value.Period),
|
||||
TaxBasis: api.SalaryTaxBasis(value.Value.TaxBasis),
|
||||
}
|
||||
result.Value.SetTo(rangeValue)
|
||||
return result
|
||||
}
|
||||
|
||||
func needSkills(values []domain.NeedSkill) []api.NeedSkill {
|
||||
result := make([]api.NeedSkill, 0, len(values))
|
||||
for _, value := range values {
|
||||
item := api.NeedSkill{Name: api.SkillName(value.Name), Status: api.NeedItemStatus(value.Status), Source: needValueSource(value.Source)}
|
||||
if value.TaxonomyCode == nil {
|
||||
item.TaxonomyCode.SetToNull()
|
||||
} else {
|
||||
item.TaxonomyCode.SetTo(api.SkillTaxonomyCode(*value.TaxonomyCode))
|
||||
}
|
||||
result = append(result, item)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func needTasks(values []domain.NeedTask) []api.NeedTask {
|
||||
result := make([]api.NeedTask, 0, len(values))
|
||||
for _, value := range values {
|
||||
result = append(result, api.NeedTask{Text: api.NeedTaskText(value.Text), Status: api.NeedItemStatus(value.Status), Source: needValueSource(value.Source)})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func needReadiness(readiness domain.NeedReadinessReport) api.NeedReadinessReport {
|
||||
missing := make([]api.NeedMissingField, 0, len(readiness.MissingFields))
|
||||
for _, field := range readiness.MissingFields {
|
||||
missing = append(missing, api.NeedMissingField{
|
||||
Field: api.NeedFieldName(field.Field), Reason: api.NeedMissingReason(field.Reason), Question: field.Question,
|
||||
})
|
||||
}
|
||||
return api.NeedReadinessReport{Status: api.NeedReadinessStatus(readiness.Status), MissingFields: missing}
|
||||
}
|
||||
|
||||
func needRecommendations(recommendations domain.NeedCategoryRecommendations) api.NeedCategoryRecommendations {
|
||||
result := api.NeedCategoryRecommendations{
|
||||
Status: api.NeedRecommendationStatus(recommendations.Status),
|
||||
RequirementsVersion: api.NeedVersion(recommendations.RequirementsVersion),
|
||||
Categories: make([]api.NeedCategoryRecommendation, 0, len(recommendations.Categories)),
|
||||
}
|
||||
if recommendations.PolicyVersion == nil {
|
||||
result.PolicyVersion.SetToNull()
|
||||
} else {
|
||||
result.PolicyVersion.SetTo(*recommendations.PolicyVersion)
|
||||
}
|
||||
if recommendations.AlgorithmVersion == nil {
|
||||
result.AlgorithmVersion.SetToNull()
|
||||
} else {
|
||||
result.AlgorithmVersion.SetTo(api.NeedVersionLabel(*recommendations.AlgorithmVersion))
|
||||
}
|
||||
if recommendations.ComputedAt == nil {
|
||||
result.ComputedAt.SetToNull()
|
||||
} else {
|
||||
result.ComputedAt.SetTo(api.Timestamp(*recommendations.ComputedAt))
|
||||
}
|
||||
for _, category := range recommendations.Categories {
|
||||
result.Categories = append(result.Categories, needCategoryRecommendation(category))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func needCategoryRecommendation(value domain.NeedCategoryRecommendation) api.NeedCategoryRecommendation {
|
||||
result := api.NeedCategoryRecommendation{
|
||||
Specialization: api.SpecializationCode(value.Specialization), Grade: api.GradeCode(value.Grade),
|
||||
SkillOverlap: api.NeedSkillOverlap{Share: value.SkillOverlap.Share},
|
||||
Money: api.NeedMoneyFit{Status: api.NeedMoneyStatus(value.Money.Status)}, Supply: api.NeedSupplyBand(value.Supply),
|
||||
}
|
||||
if value.Score == nil {
|
||||
result.Score.SetToNull()
|
||||
} else {
|
||||
result.Score.SetTo(*value.Score)
|
||||
}
|
||||
if value.Money.Share == nil {
|
||||
result.Money.Share.SetToNull()
|
||||
} else {
|
||||
result.Money.Share.SetTo(*value.Money.Share)
|
||||
}
|
||||
result.SkillOverlap.CoveredSkills = needSkillNames(value.SkillOverlap.CoveredSkills)
|
||||
result.SkillOverlap.UncoveredSkills = needSkillNames(value.SkillOverlap.UncoveredSkills)
|
||||
return result
|
||||
}
|
||||
|
||||
func needSkillNames(values []string) []api.SkillName {
|
||||
result := make([]api.SkillName, 0, len(values))
|
||||
for _, value := range values {
|
||||
result = append(result, api.SkillName(value))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func needValueSource(value domain.NeedValueSource) api.NeedValueSource {
|
||||
result := api.NeedValueSource{Origin: api.NeedValueOrigin(value.Origin)}
|
||||
setNeedSourceOptionals(&result, value)
|
||||
return result
|
||||
}
|
||||
|
||||
func needNullableSource(value *domain.NeedValueSource) api.NilNeedValueSource {
|
||||
var result api.NilNeedValueSource
|
||||
if value == nil {
|
||||
result.SetToNull()
|
||||
return result
|
||||
}
|
||||
result.SetTo(needValueSource(*value))
|
||||
return result
|
||||
}
|
||||
|
||||
func setNeedSourceOptionals(result *api.NeedValueSource, value domain.NeedValueSource) {
|
||||
if value.Quote == nil {
|
||||
result.Quote.SetToNull()
|
||||
} else {
|
||||
result.Quote.SetTo(api.NeedSourceQuote(*value.Quote))
|
||||
}
|
||||
if value.ExtractedInVersion == nil {
|
||||
result.ExtractedInVersion.SetToNull()
|
||||
} else {
|
||||
result.ExtractedInVersion.SetTo(api.NeedVersion(*value.ExtractedInVersion))
|
||||
}
|
||||
if value.ExtractionVersion == nil {
|
||||
result.ExtractionVersion.SetToNull()
|
||||
} else {
|
||||
result.ExtractionVersion.SetTo(api.NeedVersionLabel(*value.ExtractionVersion))
|
||||
}
|
||||
}
|
||||
|
||||
func needNullableUUID(value *uuid.UUID) api.NilUUID {
|
||||
var result api.NilUUID
|
||||
if value == nil {
|
||||
result.SetToNull()
|
||||
} else {
|
||||
result.SetTo(*value)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func needNullableSourceText(value *string) api.NilNeedSourceText {
|
||||
var result api.NilNeedSourceText
|
||||
if value == nil {
|
||||
result.SetToNull()
|
||||
} else {
|
||||
result.SetTo(api.NeedSourceText(*value))
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
func TestNeedCreateMappingPreservesAbsenceNullAndEmptyLists(t *testing.T) {
|
||||
request := &api.NeedCreate{Title: api.NeedTitle("Payments backend"), RequiredSkills: []api.NeedSkillInput{}}
|
||||
request.SourceText.SetTo(api.NeedSourceText("Requirements: Go"))
|
||||
request.VacancyID.SetToNull()
|
||||
|
||||
input := createNeedInput(request)
|
||||
if input.Title != "Payments backend" || !input.SourceText.Set || input.SourceText.Null || input.SourceText.Value != "Requirements: Go" {
|
||||
t.Fatalf("create mapping lost title or source text: %+v", input)
|
||||
}
|
||||
if !input.VacancyID.Set || !input.VacancyID.Null {
|
||||
t.Fatalf("explicit null vacancy mapped as %+v", input.VacancyID)
|
||||
}
|
||||
if input.Grade.Set || input.Specialization.Set || input.RequiredSkills == nil || len(input.RequiredSkills) != 0 || input.DesiredSkills != nil {
|
||||
t.Fatalf("create mapping did not distinguish absent fields from an empty list: %+v", input)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNeedUpdateMappingPreservesFieldPresenceAndListReplacement(t *testing.T) {
|
||||
request := &api.NeedUpdate{ExpectedVersion: 4, RequiredSkills: []api.NeedSkillInput{}}
|
||||
request.Title.SetTo(api.NeedTitle("Platform backend"))
|
||||
request.SourceText.SetToNull()
|
||||
|
||||
input := updateNeedInput(request)
|
||||
if input.ExpectedVersion != 4 || !input.Title.Set || input.Title.Null || input.Title.Value != "Platform backend" {
|
||||
t.Fatalf("update mapping lost expected version or title: %+v", input)
|
||||
}
|
||||
if !input.SourceText.Set || !input.SourceText.Null || input.RequiredSkills == nil || len(input.RequiredSkills) != 0 || input.DesiredSkills != nil {
|
||||
t.Fatalf("update mapping did not preserve null and list replacement: %+v", input)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNeedResponseDoesNotExposePrivateSuppressionState(t *testing.T) {
|
||||
createdAt := time.Date(2026, time.October, 7, 10, 0, 0, 0, time.UTC)
|
||||
need, err := domain.NewNeed(domain.NeedSnapshot{
|
||||
ID: uuid.Must(uuid.NewV7()), OrganizationID: uuid.Must(uuid.NewV7()), Title: "Payments backend",
|
||||
Version: 1, RequirementsVersion: 1, Requirements: domain.EmptyNeedRequirements(),
|
||||
RejectedSuggestions: []domain.NeedRejectedSuggestion{{Field: domain.NeedRejectedSkills, Value: "postgresql"}},
|
||||
CreatedAt: createdAt, UpdatedAt: createdAt,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewNeed() error = %v", err)
|
||||
}
|
||||
encoded, err := json.Marshal(needResponse(need.ResponseSnapshot()))
|
||||
if err != nil {
|
||||
t.Fatalf("marshal public need: %v", err)
|
||||
}
|
||||
if strings.Contains(string(encoded), "rejected_suggestions") || strings.Contains(string(encoded), "postgresql") {
|
||||
t.Fatalf("public need exposed private suppression state: %s", encoded)
|
||||
}
|
||||
if !strings.Contains(string(encoded), `"recommendations":{"status":"not_available"`) {
|
||||
t.Fatalf("need response did not report the unavailable calculator honestly: %s", encoded)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNeedCursorIsBoundToActorAndOrganization(t *testing.T) {
|
||||
actorID := uuid.Must(uuid.NewV7())
|
||||
organizationID := uuid.Must(uuid.NewV7())
|
||||
position := outbound.NeedListPosition{
|
||||
CreatedAt: time.Date(2026, time.October, 7, 10, 0, 0, 123456000, time.UTC),
|
||||
NeedID: uuid.Must(uuid.NewV7()),
|
||||
}
|
||||
cursor, err := encodeNeedCursor(actorID, organizationID, position)
|
||||
if err != nil {
|
||||
t.Fatalf("encodeNeedCursor() error = %v", err)
|
||||
}
|
||||
decoded, err := decodeNeedCursor(cursor, actorID, organizationID)
|
||||
if err != nil || decoded.NeedID != position.NeedID || !decoded.CreatedAt.Equal(position.CreatedAt) {
|
||||
t.Fatalf("decodeNeedCursor() = %+v, %v, want %+v", decoded, err, position)
|
||||
}
|
||||
if _, err := decodeNeedCursor(cursor, uuid.Must(uuid.NewV7()), organizationID); err == nil {
|
||||
t.Fatal("decodeNeedCursor() accepted a cursor from another actor")
|
||||
}
|
||||
if _, err := decodeNeedCursor(cursor, actorID, uuid.Must(uuid.NewV7())); err == nil {
|
||||
t.Fatal("decodeNeedCursor() accepted a cursor from another organization")
|
||||
}
|
||||
|
||||
encoded, err := base64.RawURLEncoding.DecodeString(cursor)
|
||||
if err != nil {
|
||||
t.Fatalf("decode cursor bytes: %v", err)
|
||||
}
|
||||
encoded[33] = 0x80
|
||||
invalidTimestamp := base64.RawURLEncoding.EncodeToString(encoded)
|
||||
if _, err := decodeNeedCursor(invalidTimestamp, actorID, organizationID); err == nil {
|
||||
t.Fatal("decodeNeedCursor() accepted an out-of-range timestamp")
|
||||
}
|
||||
encoded, err = base64.RawURLEncoding.DecodeString(cursor)
|
||||
if err != nil {
|
||||
t.Fatalf("decode cursor bytes: %v", err)
|
||||
}
|
||||
binary.BigEndian.PutUint64(encoded[33:41], maxNeedCursorTime+1)
|
||||
outsideDateTime := base64.RawURLEncoding.EncodeToString(encoded)
|
||||
if _, err := decodeNeedCursor(outsideDateTime, actorID, organizationID); err == nil {
|
||||
t.Fatal("decodeNeedCursor() accepted a timestamp outside the contract date-time range")
|
||||
}
|
||||
encoded, err = base64.RawURLEncoding.DecodeString(cursor)
|
||||
if err != nil {
|
||||
t.Fatalf("decode cursor bytes: %v", err)
|
||||
}
|
||||
binary.BigEndian.PutUint32(encoded[41:45], 123456001)
|
||||
subMicrosecond := base64.RawURLEncoding.EncodeToString(encoded)
|
||||
if _, err := decodeNeedCursor(subMicrosecond, actorID, organizationID); err == nil {
|
||||
t.Fatal("decodeNeedCursor() accepted precision that PostgreSQL cannot preserve")
|
||||
}
|
||||
if _, err := encodeNeedCursor(actorID, organizationID, outbound.NeedListPosition{
|
||||
CreatedAt: time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC), NeedID: position.NeedID,
|
||||
}); err == nil {
|
||||
t.Fatal("encodeNeedCursor() accepted a timestamp outside the contract date-time range")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,657 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
"lincodex/backend/internal/adapter/primary/http/problem"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/usecase/candidateprivacy"
|
||||
"lincodex/backend/internal/usecase/candidateview"
|
||||
)
|
||||
|
||||
const (
|
||||
privacyCursorVersion = 1
|
||||
privacyCursorBytes = 46
|
||||
defaultPrivacyLimit = 20
|
||||
privacyCursorEvents = 1
|
||||
privacyCursorHidden = 2
|
||||
privacyCursorAccess = 3
|
||||
)
|
||||
|
||||
// CandidateViewOperations serves private previews, owner access history, and
|
||||
// organization-scoped anonymous card reads.
|
||||
type CandidateViewOperations interface {
|
||||
GetOrganizationCard(ctx context.Context, actorID, organizationID uuid.UUID, handle string) (domain.AnonymousCandidateViewDTO, error)
|
||||
GetMyCardPreview(ctx context.Context, actorID uuid.UUID) (candidateview.PreviewResult, error)
|
||||
ListMyCardAccessHistory(ctx context.Context, query outbound.CandidateCardAccessListQuery) (outbound.CandidateCardAccessListPage, error)
|
||||
}
|
||||
|
||||
// CandidatePrivacyOperations serves candidate-owned publication and privacy
|
||||
// settings.
|
||||
type CandidatePrivacyOperations interface {
|
||||
GetMyPrivacySettings(ctx context.Context, userID uuid.UUID) (outbound.CandidatePrivacySettings, error)
|
||||
SetMyPublication(ctx context.Context, userID uuid.UUID, expectedVersion int64, state domain.PublicationState, fields []domain.CardField) (domain.Publication, error)
|
||||
SetMySearchStatus(ctx context.Context, userID uuid.UUID, expectedVersion int64, value domain.SearchStatusValue) (domain.SearchStatus, time.Time, error)
|
||||
ListMyPrivacyHistory(ctx context.Context, query outbound.CandidatePrivacyEventListQuery) (outbound.CandidatePrivacyEventPage, error)
|
||||
ListMyHiddenOrganizations(ctx context.Context, query outbound.HiddenOrganizationListQuery) (outbound.HiddenOrganizationPage, error)
|
||||
HideOrganization(ctx context.Context, userID, organizationID uuid.UUID) (outbound.HiddenOrganizationRecord, error)
|
||||
UnhideOrganization(ctx context.Context, userID, organizationID uuid.UUID) error
|
||||
}
|
||||
|
||||
// PrivacyHandler binds the privacy read and settings use cases to the v1 API.
|
||||
type PrivacyHandler struct {
|
||||
views CandidateViewOperations
|
||||
settings CandidatePrivacyOperations
|
||||
publicOrigin string
|
||||
}
|
||||
|
||||
func NewPrivacyHandler(views CandidateViewOperations, settings CandidatePrivacyOperations, publicOrigin string) *PrivacyHandler {
|
||||
if views == nil || settings == nil {
|
||||
panic("v1.NewPrivacyHandler - view and settings operations must not be nil")
|
||||
}
|
||||
return &PrivacyHandler{views: views, settings: settings, publicOrigin: publicOrigin}
|
||||
}
|
||||
|
||||
func (handler *Handler) GetMyCardPreview(ctx context.Context) (api.GetMyCardPreviewRes, error) {
|
||||
if handler.privacy == nil {
|
||||
return handler.UnimplementedHandler.GetMyCardPreview(ctx)
|
||||
}
|
||||
return handler.privacy.GetMyCardPreview(ctx)
|
||||
}
|
||||
|
||||
func (handler *Handler) GetMyPrivacySettings(ctx context.Context) (api.GetMyPrivacySettingsRes, error) {
|
||||
if handler.privacy == nil {
|
||||
return handler.UnimplementedHandler.GetMyPrivacySettings(ctx)
|
||||
}
|
||||
return handler.privacy.GetMyPrivacySettings(ctx)
|
||||
}
|
||||
|
||||
func (handler *Handler) GetOrganizationCandidateCard(ctx context.Context, params api.GetOrganizationCandidateCardParams) (api.GetOrganizationCandidateCardRes, error) {
|
||||
if handler.privacy == nil {
|
||||
return handler.UnimplementedHandler.GetOrganizationCandidateCard(ctx, params)
|
||||
}
|
||||
return handler.privacy.GetOrganizationCandidateCard(ctx, params)
|
||||
}
|
||||
|
||||
func (handler *Handler) HideOrganization(ctx context.Context, params api.HideOrganizationParams) (api.HideOrganizationRes, error) {
|
||||
if handler.privacy == nil {
|
||||
return handler.UnimplementedHandler.HideOrganization(ctx, params)
|
||||
}
|
||||
return handler.privacy.HideOrganization(ctx, params)
|
||||
}
|
||||
|
||||
func (handler *Handler) ListMyCardAccessHistory(ctx context.Context, params api.ListMyCardAccessHistoryParams) (api.ListMyCardAccessHistoryRes, error) {
|
||||
if handler.privacy == nil {
|
||||
return handler.UnimplementedHandler.ListMyCardAccessHistory(ctx, params)
|
||||
}
|
||||
return handler.privacy.ListMyCardAccessHistory(ctx, params)
|
||||
}
|
||||
|
||||
func (handler *Handler) ListMyHiddenOrganizations(ctx context.Context, params api.ListMyHiddenOrganizationsParams) (api.ListMyHiddenOrganizationsRes, error) {
|
||||
if handler.privacy == nil {
|
||||
return handler.UnimplementedHandler.ListMyHiddenOrganizations(ctx, params)
|
||||
}
|
||||
return handler.privacy.ListMyHiddenOrganizations(ctx, params)
|
||||
}
|
||||
|
||||
func (handler *Handler) ListMyPrivacyHistory(ctx context.Context, params api.ListMyPrivacyHistoryParams) (api.ListMyPrivacyHistoryRes, error) {
|
||||
if handler.privacy == nil {
|
||||
return handler.UnimplementedHandler.ListMyPrivacyHistory(ctx, params)
|
||||
}
|
||||
return handler.privacy.ListMyPrivacyHistory(ctx, params)
|
||||
}
|
||||
|
||||
func (handler *Handler) SetMyPublication(ctx context.Context, request *api.PublicationUpdate) (api.SetMyPublicationRes, error) {
|
||||
if handler.privacy == nil {
|
||||
return handler.UnimplementedHandler.SetMyPublication(ctx, request)
|
||||
}
|
||||
return handler.privacy.SetMyPublication(ctx, request)
|
||||
}
|
||||
|
||||
func (handler *Handler) SetMySearchStatus(ctx context.Context, request *api.SearchStatusUpdate) (api.SetMySearchStatusRes, error) {
|
||||
if handler.privacy == nil {
|
||||
return handler.UnimplementedHandler.SetMySearchStatus(ctx, request)
|
||||
}
|
||||
return handler.privacy.SetMySearchStatus(ctx, request)
|
||||
}
|
||||
|
||||
func (handler *Handler) UnhideOrganization(ctx context.Context, params api.UnhideOrganizationParams) (api.UnhideOrganizationRes, error) {
|
||||
if handler.privacy == nil {
|
||||
return handler.UnimplementedHandler.UnhideOrganization(ctx, params)
|
||||
}
|
||||
return handler.privacy.UnhideOrganization(ctx, params)
|
||||
}
|
||||
|
||||
func (handler *PrivacyHandler) GetMyCardPreview(ctx context.Context) (api.GetMyCardPreviewRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.GetMyCardPreviewUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
preview, err := handler.views.GetMyCardPreview(ctx, principal.UserID)
|
||||
if err != nil {
|
||||
if errors.Is(err, candidateview.ErrForbidden) {
|
||||
return (*api.GetMyCardPreviewForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &api.CardPreviewHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: cardPreviewResponse(preview)}, nil
|
||||
}
|
||||
|
||||
func (handler *PrivacyHandler) GetMyPrivacySettings(ctx context.Context) (api.GetMyPrivacySettingsRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.GetMyPrivacySettingsUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
settings, err := handler.settings.GetMyPrivacySettings(ctx, principal.UserID)
|
||||
if err != nil {
|
||||
if errors.Is(err, candidateprivacy.ErrForbidden) || errors.Is(err, candidateprivacy.ErrEmailNotVerified) {
|
||||
return (*api.GetMyPrivacySettingsForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &api.PrivacySettingsHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: privacySettingsResponse(settings)}, nil
|
||||
}
|
||||
|
||||
func (handler *PrivacyHandler) GetOrganizationCandidateCard(ctx context.Context, params api.GetOrganizationCandidateCardParams) (api.GetOrganizationCandidateCardRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.GetOrganizationCandidateCardUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
view, err := handler.views.GetOrganizationCard(ctx, principal.UserID, params.OrgID, string(params.CandidateHandle))
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, candidateview.ErrForbidden):
|
||||
return (*api.GetOrganizationCandidateCardForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
case errors.Is(err, candidateview.ErrCandidateCardNotFound), errors.Is(err, outbound.ErrOrganizationNotFound):
|
||||
return (*api.GetOrganizationCandidateCardNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
|
||||
case errors.Is(err, candidateview.ErrInvalidCandidateHandle):
|
||||
return (*api.GetOrganizationCandidateCardBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationPath, "/candidate_handle").Response), nil
|
||||
}
|
||||
if limited, ok := candidateViewRateLimited(ctx, err); ok {
|
||||
return limited, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &api.AnonymousCardContentHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: anonymousCardResponse(view)}, nil
|
||||
}
|
||||
|
||||
func (handler *PrivacyHandler) ListMyCardAccessHistory(ctx context.Context, params api.ListMyCardAccessHistoryParams) (api.ListMyCardAccessHistoryRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.ListMyCardAccessHistoryUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
limit, cursor, pointer := privacyPageParams(params.Limit, params.Cursor, principal.UserID, privacyCursorAccess)
|
||||
if pointer != "" {
|
||||
return (*api.ListMyCardAccessHistoryBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationQuery, "/"+pointer).Response), nil
|
||||
}
|
||||
var after *outbound.CandidateCardAccessPosition
|
||||
if cursor != nil {
|
||||
position := outbound.CandidateCardAccessPosition{OccurredAt: cursor.at, ID: cursor.id}
|
||||
after = &position
|
||||
}
|
||||
page, err := handler.views.ListMyCardAccessHistory(ctx, outbound.CandidateCardAccessListQuery{CandidateID: principal.UserID, After: after, Limit: limit})
|
||||
if err != nil {
|
||||
if errors.Is(err, candidateview.ErrForbidden) || errors.Is(err, candidateprivacy.ErrForbidden) {
|
||||
return (*api.ListMyCardAccessHistoryForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
items := make([]api.CardAccess, 0, len(page.Items))
|
||||
for _, access := range page.Items {
|
||||
organization := api.NilPrivacyOrganization{}
|
||||
if name := page.OrganizationNames[access.OrganizationID()]; name != "" {
|
||||
organization.SetTo(api.PrivacyOrganization{ID: access.OrganizationID(), Name: name})
|
||||
} else {
|
||||
organization.SetToNull()
|
||||
}
|
||||
items = append(items, api.CardAccess{
|
||||
ID: access.ID(), Kind: api.CardAccessKind(access.Kind()), OccurredAt: api.Timestamp(access.OccurredAt()), Organization: organization,
|
||||
})
|
||||
}
|
||||
next, err := privacyNextCursor(page.HasMore, len(page.Items), func() (string, error) {
|
||||
last := page.Items[len(page.Items)-1]
|
||||
return encodePrivacyCursor(principal.UserID, privacyCursorAccess, last.OccurredAt(), last.ID())
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("PrivacyHandler.ListMyCardAccessHistory - encode cursor: %w", err)
|
||||
}
|
||||
return &api.CardAccessListHeaders{
|
||||
CacheControl: api.CacheControlNoStoreNoStore,
|
||||
Response: api.CardAccessList{Items: items, Page: api.PageInfo{HasMore: page.HasMore, NextCursor: next}},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (handler *PrivacyHandler) ListMyHiddenOrganizations(ctx context.Context, params api.ListMyHiddenOrganizationsParams) (api.ListMyHiddenOrganizationsRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.ListMyHiddenOrganizationsUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
limit, cursor, pointer := privacyPageParams(params.Limit, params.Cursor, principal.UserID, privacyCursorHidden)
|
||||
if pointer != "" {
|
||||
return (*api.ListMyHiddenOrganizationsBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationQuery, "/"+pointer).Response), nil
|
||||
}
|
||||
var after *outbound.HiddenOrganizationPosition
|
||||
if cursor != nil {
|
||||
position := outbound.HiddenOrganizationPosition{HiddenAt: cursor.at, OrganizationID: cursor.id}
|
||||
after = &position
|
||||
}
|
||||
page, err := handler.settings.ListMyHiddenOrganizations(ctx, outbound.HiddenOrganizationListQuery{UserID: principal.UserID, After: after, Limit: limit})
|
||||
if err != nil {
|
||||
if errors.Is(err, candidateprivacy.ErrForbidden) || errors.Is(err, candidateprivacy.ErrEmailNotVerified) {
|
||||
return (*api.ListMyHiddenOrganizationsForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
items := make([]api.HiddenOrganization, 0, len(page.Items))
|
||||
for _, item := range page.Items {
|
||||
items = append(items, hiddenOrganizationResponse(item))
|
||||
}
|
||||
next, err := privacyNextCursor(page.HasMore, len(page.Items), func() (string, error) {
|
||||
last := page.Items[len(page.Items)-1]
|
||||
return encodePrivacyCursor(principal.UserID, privacyCursorHidden, last.HiddenAt, last.OrganizationID)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("PrivacyHandler.ListMyHiddenOrganizations - encode cursor: %w", err)
|
||||
}
|
||||
return &api.HiddenOrganizationListHeaders{
|
||||
CacheControl: api.CacheControlNoStoreNoStore,
|
||||
Response: api.HiddenOrganizationList{Items: items, Page: api.PageInfo{HasMore: page.HasMore, NextCursor: next}},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (handler *PrivacyHandler) ListMyPrivacyHistory(ctx context.Context, params api.ListMyPrivacyHistoryParams) (api.ListMyPrivacyHistoryRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.ListMyPrivacyHistoryUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
limit, cursor, pointer := privacyPageParams(params.Limit, params.Cursor, principal.UserID, privacyCursorEvents)
|
||||
if pointer != "" {
|
||||
return (*api.ListMyPrivacyHistoryBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationQuery, "/"+pointer).Response), nil
|
||||
}
|
||||
var after *outbound.CandidatePrivacyEventPosition
|
||||
if cursor != nil {
|
||||
position := outbound.CandidatePrivacyEventPosition{OccurredAt: cursor.at, ID: cursor.id}
|
||||
after = &position
|
||||
}
|
||||
page, err := handler.settings.ListMyPrivacyHistory(ctx, outbound.CandidatePrivacyEventListQuery{UserID: principal.UserID, After: after, Limit: limit})
|
||||
if err != nil {
|
||||
if errors.Is(err, candidateprivacy.ErrForbidden) || errors.Is(err, candidateprivacy.ErrEmailNotVerified) {
|
||||
return (*api.ListMyPrivacyHistoryForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
items := make([]api.PrivacyEvent, 0, len(page.Items))
|
||||
for _, item := range page.Items {
|
||||
items = append(items, privacyEventResponse(item))
|
||||
}
|
||||
next, err := privacyNextCursor(page.HasMore, len(page.Items), func() (string, error) {
|
||||
last := page.Items[len(page.Items)-1]
|
||||
return encodePrivacyCursor(principal.UserID, privacyCursorEvents, last.OccurredAt, last.ID)
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("PrivacyHandler.ListMyPrivacyHistory - encode cursor: %w", err)
|
||||
}
|
||||
return &api.PrivacyEventListHeaders{
|
||||
CacheControl: api.CacheControlNoStoreNoStore,
|
||||
Response: api.PrivacyEventList{Items: items, Page: api.PageInfo{HasMore: page.HasMore, NextCursor: next}},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (handler *PrivacyHandler) SetMyPublication(ctx context.Context, request *api.PublicationUpdate) (api.SetMyPublicationRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.SetMyPublicationUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
if !originAllowed(ctx, handler.publicOrigin) {
|
||||
return (*api.SetMyPublicationForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil
|
||||
}
|
||||
if request == nil {
|
||||
return (*api.SetMyPublicationBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
|
||||
}
|
||||
fields := make([]domain.CardField, 0, len(request.Fields))
|
||||
for _, field := range request.Fields {
|
||||
fields = append(fields, domain.CardField(field))
|
||||
}
|
||||
publication, err := handler.settings.SetMyPublication(ctx, principal.UserID, int64(request.ExpectedVersion), domain.PublicationState(request.State), fields)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, candidateprivacy.ErrForbidden), errors.Is(err, candidateprivacy.ErrEmailNotVerified):
|
||||
return (*api.SetMyPublicationForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
case errors.Is(err, domain.ErrVisibilityVersionConflict):
|
||||
return (*api.SetMyPublicationPreconditionFailed)(&problem.New(ctx, api.ProblemCodeVersionConflict).Response), nil
|
||||
case errors.Is(err, domain.ErrPublicationConsentRequired):
|
||||
return (*api.SetMyPublicationConflict)(privacyStateConflict(ctx, api.ProblemFieldLocationBody, "/state", "consent_required")), nil
|
||||
case errors.Is(err, domain.ErrInvalidVisibility):
|
||||
return (*api.SetMyPublicationBadRequest)(&privacyVisibilityInvalid(ctx, err).Response), nil
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return &api.PublicationHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: publicationResponse(publication)}, nil
|
||||
}
|
||||
|
||||
func (handler *PrivacyHandler) SetMySearchStatus(ctx context.Context, request *api.SearchStatusUpdate) (api.SetMySearchStatusRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.SetMySearchStatusUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
if !originAllowed(ctx, handler.publicOrigin) {
|
||||
return (*api.SetMySearchStatusForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil
|
||||
}
|
||||
if request == nil {
|
||||
return (*api.SetMySearchStatusBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
|
||||
}
|
||||
status, asOf, err := handler.settings.SetMySearchStatus(ctx, principal.UserID, int64(request.ExpectedVersion), domain.SearchStatusValue(request.Value))
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, candidateprivacy.ErrForbidden), errors.Is(err, candidateprivacy.ErrEmailNotVerified):
|
||||
return (*api.SetMySearchStatusForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
case errors.Is(err, domain.ErrVisibilityVersionConflict):
|
||||
return (*api.SetMySearchStatusPreconditionFailed)(&problem.New(ctx, api.ProblemCodeVersionConflict).Response), nil
|
||||
case errors.Is(err, domain.ErrInvalidVisibility):
|
||||
return (*api.SetMySearchStatusBadRequest)(&privacyVisibilityInvalid(ctx, err).Response), nil
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return &api.SearchStatusHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: searchStatusResponse(status, asOf)}, nil
|
||||
}
|
||||
|
||||
func (handler *PrivacyHandler) HideOrganization(ctx context.Context, params api.HideOrganizationParams) (api.HideOrganizationRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.HideOrganizationUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
if !originAllowed(ctx, handler.publicOrigin) {
|
||||
return (*api.HideOrganizationForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil
|
||||
}
|
||||
hidden, err := handler.settings.HideOrganization(ctx, principal.UserID, params.OrgID)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, candidateprivacy.ErrForbidden), errors.Is(err, candidateprivacy.ErrEmailNotVerified):
|
||||
return (*api.HideOrganizationForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
case errors.Is(err, outbound.ErrCandidatePrivacyOrganizationNotVisible), errors.Is(err, outbound.ErrOrganizationNotFound):
|
||||
return (*api.HideOrganizationNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
|
||||
case errors.Is(err, outbound.ErrCandidateHiddenOrganizationLimit):
|
||||
return (*api.HideOrganizationConflict)(privacyStateConflict(ctx, api.ProblemFieldLocationPath, "/org_id", "limit_reached")), nil
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return &api.HiddenOrganizationHeaders{CacheControl: api.CacheControlNoStoreNoStore, Response: hiddenOrganizationResponse(hidden)}, nil
|
||||
}
|
||||
|
||||
func (handler *PrivacyHandler) UnhideOrganization(ctx context.Context, params api.UnhideOrganizationParams) (api.UnhideOrganizationRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.UnhideOrganizationUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
if !originAllowed(ctx, handler.publicOrigin) {
|
||||
return (*api.UnhideOrganizationForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil
|
||||
}
|
||||
if err := handler.settings.UnhideOrganization(ctx, principal.UserID, params.OrgID); err != nil {
|
||||
if errors.Is(err, candidateprivacy.ErrForbidden) || errors.Is(err, candidateprivacy.ErrEmailNotVerified) {
|
||||
return (*api.UnhideOrganizationForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &api.UnhideOrganizationNoContent{CacheControl: api.CacheControlNoStoreNoStore}, nil
|
||||
}
|
||||
|
||||
type privacyCursor struct {
|
||||
at time.Time
|
||||
id uuid.UUID
|
||||
}
|
||||
|
||||
func privacyPageParams(limit api.OptInt32, cursor api.OptString, owner uuid.UUID, kind byte) (int32, *privacyCursor, string) {
|
||||
pageLimit, set := limit.Get()
|
||||
if !set {
|
||||
pageLimit = defaultPrivacyLimit
|
||||
}
|
||||
if pageLimit < 1 || pageLimit > outbound.MaxPrivacyPageSize {
|
||||
return 0, nil, "limit"
|
||||
}
|
||||
value, set := cursor.Get()
|
||||
if !set {
|
||||
return pageLimit, nil, ""
|
||||
}
|
||||
position, err := decodePrivacyCursor(value, owner, kind)
|
||||
if err != nil {
|
||||
return 0, nil, "cursor"
|
||||
}
|
||||
return pageLimit, &position, ""
|
||||
}
|
||||
|
||||
func encodePrivacyCursor(owner uuid.UUID, kind byte, at time.Time, id uuid.UUID) (string, error) {
|
||||
at = at.UTC()
|
||||
seconds, nanos := at.Unix(), at.Nanosecond()
|
||||
if owner == uuid.Nil || id == uuid.Nil || kind < privacyCursorEvents || kind > privacyCursorAccess || at.IsZero() ||
|
||||
at.Year() < 1 || at.Year() > 9999 || nanos < 0 || nanos >= 1_000_000_000 || nanos%1_000 != 0 {
|
||||
return "", errors.New("privacy cursor requires an owner and valid page position")
|
||||
}
|
||||
var value [privacyCursorBytes]byte
|
||||
value[0], value[1] = privacyCursorVersion, kind
|
||||
copy(value[2:18], owner[:])
|
||||
writePrivacyCursorSeconds(value[18:26], seconds)
|
||||
binary.BigEndian.PutUint32(value[26:30], uint32(nanos))
|
||||
copy(value[30:46], id[:])
|
||||
return base64.RawURLEncoding.EncodeToString(value[:]), nil
|
||||
}
|
||||
|
||||
func decodePrivacyCursor(cursor string, owner uuid.UUID, kind byte) (privacyCursor, error) {
|
||||
value, err := base64.RawURLEncoding.DecodeString(cursor)
|
||||
if err != nil || len(value) != privacyCursorBytes || owner == uuid.Nil ||
|
||||
base64.RawURLEncoding.EncodeToString(value) != cursor || value[0] != privacyCursorVersion || value[1] != kind ||
|
||||
uuid.UUID(value[2:18]) != owner {
|
||||
return privacyCursor{}, errors.New("privacy cursor is invalid")
|
||||
}
|
||||
seconds := decodePrivacyCursorSeconds(value[18:26])
|
||||
nanos := binary.BigEndian.Uint32(value[26:30])
|
||||
id := uuid.UUID(value[30:46])
|
||||
if nanos >= 1_000_000_000 || nanos%1_000 != 0 || id == uuid.Nil {
|
||||
return privacyCursor{}, errors.New("privacy cursor position is invalid")
|
||||
}
|
||||
at := time.Unix(seconds, int64(nanos)).UTC()
|
||||
if at.IsZero() || at.Year() < 1 || at.Year() > 9999 {
|
||||
return privacyCursor{}, errors.New("privacy cursor timestamp is invalid")
|
||||
}
|
||||
return privacyCursor{at: at, id: id}, nil
|
||||
}
|
||||
|
||||
func writePrivacyCursorSeconds(encoded []byte, seconds int64) {
|
||||
encoded[0] = byte((seconds >> 56) & 0xff)
|
||||
encoded[1] = byte((seconds >> 48) & 0xff)
|
||||
encoded[2] = byte((seconds >> 40) & 0xff)
|
||||
encoded[3] = byte((seconds >> 32) & 0xff)
|
||||
encoded[4] = byte((seconds >> 24) & 0xff)
|
||||
encoded[5] = byte((seconds >> 16) & 0xff)
|
||||
encoded[6] = byte((seconds >> 8) & 0xff)
|
||||
encoded[7] = byte(seconds & 0xff)
|
||||
}
|
||||
|
||||
func decodePrivacyCursorSeconds(encoded []byte) int64 {
|
||||
high := int64(binary.BigEndian.Uint32(encoded[:4]))
|
||||
low := int64(binary.BigEndian.Uint32(encoded[4:]))
|
||||
return high<<32 | low
|
||||
}
|
||||
|
||||
func privacyNextCursor(hasMore bool, itemCount int, encode func() (string, error)) (api.NilString, error) {
|
||||
var next api.NilString
|
||||
next.SetToNull()
|
||||
if !hasMore {
|
||||
return next, nil
|
||||
}
|
||||
if itemCount == 0 {
|
||||
return api.NilString{}, errors.New("privacy page has_more without items")
|
||||
}
|
||||
if hasMore {
|
||||
cursor, err := encode()
|
||||
if err != nil {
|
||||
return api.NilString{}, err
|
||||
}
|
||||
next.SetTo(cursor)
|
||||
}
|
||||
return next, nil
|
||||
}
|
||||
|
||||
func cardPreviewResponse(preview candidateview.PreviewResult) api.CardPreview {
|
||||
state := api.PublicationStateClosed
|
||||
if preview.Published {
|
||||
state = api.PublicationStatePublished
|
||||
}
|
||||
fields := make(api.CardFieldSet, 0, len(preview.Fields.Fields()))
|
||||
for _, field := range preview.Fields.Fields() {
|
||||
fields = append(fields, api.CardField(field))
|
||||
}
|
||||
card := api.NilAnonymousCardContent{}
|
||||
if preview.Card == nil {
|
||||
card.SetToNull()
|
||||
} else {
|
||||
card.SetTo(anonymousCardResponse(*preview.Card))
|
||||
}
|
||||
return api.CardPreview{State: state, Fields: fields, Card: card, GeneratedAt: api.Timestamp(preview.GeneratedAt)}
|
||||
}
|
||||
|
||||
func anonymousCardResponse(view domain.AnonymousCandidateViewDTO) api.AnonymousCardContent {
|
||||
content := api.AnonymousCardContent{Pseudonym: view.Pseudonym}
|
||||
for _, category := range view.Categories {
|
||||
content.Categories = append(content.Categories, api.CardCategory{
|
||||
Specialization: api.SpecializationCode(category.Specialization), Grade: api.GradeCode(category.Grade),
|
||||
Strength: api.CardCategoryStrength(category.Strength),
|
||||
})
|
||||
}
|
||||
for _, skill := range view.Skills {
|
||||
content.Stack = append(content.Stack, api.AnonymousCardContentStackItem(skill))
|
||||
}
|
||||
for _, assessment := range view.SelfAssessment {
|
||||
grade := api.OptNilGradeCode{}
|
||||
if assessment.DeclaredGrade == nil {
|
||||
grade.SetToNull()
|
||||
} else {
|
||||
grade.SetTo(api.GradeCode(*assessment.DeclaredGrade))
|
||||
}
|
||||
content.SelfAssessment = append(content.SelfAssessment, api.CardSelfAssessment{
|
||||
Specialization: api.SpecializationCode(assessment.Specialization),
|
||||
ConfirmationStatus: api.CardSelfAssessmentConfirmationStatus(assessment.ConfirmationStatus),
|
||||
DeclaredGrade: grade,
|
||||
})
|
||||
}
|
||||
content.ExperienceBand.SetToNull()
|
||||
if view.ExperienceBand != nil {
|
||||
content.ExperienceBand.SetTo(api.CandidateExperienceBand(*view.ExperienceBand))
|
||||
}
|
||||
for _, format := range view.WorkFormats {
|
||||
content.WorkFormats = append(content.WorkFormats, api.CandidateWorkFormat(format))
|
||||
}
|
||||
content.SalaryCompatibility.SetToNull()
|
||||
if view.SalaryCompatibility != nil {
|
||||
content.SalaryCompatibility.SetTo(api.CandidateSalaryCompatibility(*view.SalaryCompatibility))
|
||||
}
|
||||
return content
|
||||
}
|
||||
|
||||
func privacySettingsResponse(settings outbound.CandidatePrivacySettings) api.PrivacySettings {
|
||||
return api.PrivacySettings{
|
||||
Publication: publicationResponse(settings.Publication),
|
||||
SearchStatus: searchStatusResponse(settings.SearchStatus, settings.AsOf),
|
||||
HiddenOrganizationsTotal: int(settings.HiddenCount),
|
||||
}
|
||||
}
|
||||
|
||||
func publicationResponse(publication domain.Publication) api.Publication {
|
||||
response := api.Publication{State: api.PublicationState(publication.State()), Version: api.PublicationVersion(publication.Version())}
|
||||
response.ClosedReason.SetToNull()
|
||||
if reason := publication.ClosedReason(); reason != "" {
|
||||
response.ClosedReason.SetTo(api.PublicationClosedReason(reason))
|
||||
}
|
||||
response.ConsentID.SetToNull()
|
||||
if consentID := publication.ConsentRecordID(); consentID != uuid.Nil {
|
||||
response.ConsentID.SetTo(consentID)
|
||||
}
|
||||
response.PublishedAt.SetToNull()
|
||||
if publishedAt := publication.PublishedAt(); !publishedAt.IsZero() {
|
||||
response.PublishedAt.SetTo(api.Timestamp(publishedAt))
|
||||
}
|
||||
for _, field := range publication.Fields().Fields() {
|
||||
response.Fields = append(response.Fields, api.CardField(field))
|
||||
}
|
||||
if response.Fields == nil {
|
||||
response.Fields = api.CardFieldSet{}
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
func searchStatusResponse(status domain.SearchStatus, asOf time.Time) api.SearchStatus {
|
||||
response := api.SearchStatus{Value: api.SearchStatusValue(status.Effective(asOf)), Lapsed: status.Lapsed(asOf), Version: api.SearchStatusVersion(status.Version())}
|
||||
response.ConfirmedAt.SetToNull()
|
||||
if confirmedAt := status.ConfirmedAt(); !confirmedAt.IsZero() {
|
||||
response.ConfirmedAt.SetTo(api.Timestamp(confirmedAt))
|
||||
}
|
||||
response.LapsesAt.SetToNull()
|
||||
if lapsesAt := status.LapsesAt(); !lapsesAt.IsZero() {
|
||||
response.LapsesAt.SetTo(api.Timestamp(lapsesAt))
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
func privacyEventResponse(event outbound.CandidatePrivacyEventRecord) api.PrivacyEvent {
|
||||
response := api.PrivacyEvent{ID: event.ID, Kind: api.PrivacyEventKind(event.Kind), OccurredAt: api.Timestamp(event.OccurredAt)}
|
||||
if event.Fields == nil {
|
||||
response.Fields = nil
|
||||
} else {
|
||||
response.Fields = make(api.CardFieldSet, 0, len(event.Fields.Fields()))
|
||||
for _, field := range event.Fields.Fields() {
|
||||
response.Fields = append(response.Fields, api.CardField(field))
|
||||
}
|
||||
}
|
||||
response.ConsentID.SetToNull()
|
||||
if event.ConsentRecordID != uuid.Nil {
|
||||
response.ConsentID.SetTo(event.ConsentRecordID)
|
||||
}
|
||||
response.Organization.SetToNull()
|
||||
if event.OrganizationID != uuid.Nil && event.OrganizationName != "" {
|
||||
response.Organization.SetTo(api.PrivacyOrganization{ID: event.OrganizationID, Name: event.OrganizationName})
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
func hiddenOrganizationResponse(hidden outbound.HiddenOrganizationRecord) api.HiddenOrganization {
|
||||
return api.HiddenOrganization{
|
||||
Organization: api.PrivacyOrganization{ID: hidden.OrganizationID, Name: hidden.OrganizationName},
|
||||
HiddenAt: api.Timestamp(hidden.HiddenAt),
|
||||
}
|
||||
}
|
||||
|
||||
func privacyVisibilityInvalid(ctx context.Context, err error) *api.ProblemStatusCode {
|
||||
field, ok := errors.AsType[*domain.VisibilityFieldError](err)
|
||||
if !ok {
|
||||
return problem.InvalidField(ctx, api.ProblemFieldLocationBody, "")
|
||||
}
|
||||
return problem.InvalidField(ctx, api.ProblemFieldLocationBody, field.Pointer)
|
||||
}
|
||||
|
||||
func privacyStateConflict(ctx context.Context, location api.ProblemFieldLocation, pointer, code string) *api.Problem {
|
||||
response := problem.New(ctx, api.ProblemCodeStateConflict).Response
|
||||
response.Errors = []api.ProblemFieldError{{
|
||||
In: location, Pointer: pointer, Code: code,
|
||||
Message: "The requested setting cannot be applied in the current state.",
|
||||
}}
|
||||
return &response
|
||||
}
|
||||
|
||||
func candidateViewRateLimited(ctx context.Context, err error) (*api.TooManyRequestsHeaders, bool) {
|
||||
limited, ok := errors.AsType[*candidateview.RateLimitedError](err)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
return problem.RateLimited(ctx, wholeSeconds(time.Until(limited.RetryAt))), true
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
httpmiddleware "lincodex/backend/internal/adapter/primary/http/middleware"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/usecase/candidateview"
|
||||
)
|
||||
|
||||
func TestPrivacyGetOrganizationCandidateCardMapsClosedProjection(t *testing.T) {
|
||||
userID, organizationID := uuid.New(), uuid.New()
|
||||
view := domain.AnonymousCandidateViewDTO{
|
||||
Pseudonym: "cv1_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
||||
Categories: []domain.CandidateViewCategory{{
|
||||
Specialization: domain.SpecializationBackend, Grade: domain.GradeJunior, Strength: domain.CandidateViewStrengthStrong,
|
||||
}},
|
||||
Skills: []domain.CandidateViewSkillCode{"go"},
|
||||
SelfAssessment: []domain.CandidateViewSelfAssessment{{
|
||||
Specialization: domain.SpecializationBackend, ConfirmationStatus: domain.CandidateViewConfirmationUnconfirmed,
|
||||
}},
|
||||
}
|
||||
views := &privacyViewStub{card: view}
|
||||
handler := NewPrivacyHandler(views, &privacySettingsStub{}, "https://app.example.test")
|
||||
ctx := privacyHTTPContext(userID, "")
|
||||
|
||||
response, err := handler.GetOrganizationCandidateCard(ctx, api.GetOrganizationCandidateCardParams{
|
||||
OrgID: organizationID, CandidateHandle: api.CandidateHandle(view.Pseudonym),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("GetOrganizationCandidateCard() error = %v", err)
|
||||
}
|
||||
body, ok := response.(*api.AnonymousCardContentHeaders)
|
||||
if !ok {
|
||||
t.Fatalf("GetOrganizationCandidateCard() response = %T, want AnonymousCardContentHeaders", response)
|
||||
}
|
||||
if body.CacheControl != api.CacheControlNoStoreNoStore || body.Response.Pseudonym != view.Pseudonym ||
|
||||
len(body.Response.Categories) != 1 || body.Response.Categories[0].Strength != api.CardCategoryStrengthStrong ||
|
||||
len(body.Response.Stack) != 1 || body.Response.Stack[0] != "go" ||
|
||||
len(body.Response.SelfAssessment) != 1 || body.Response.SelfAssessment[0].ConfirmationStatus != api.CardSelfAssessmentConfirmationStatusUnconfirmed {
|
||||
t.Fatalf("anonymous content mapping = %+v", body)
|
||||
}
|
||||
if views.actorID != userID || views.organizationID != organizationID || views.handle != view.Pseudonym {
|
||||
t.Fatalf("read scope = actor %s organization %s handle %q", views.actorID, views.organizationID, views.handle)
|
||||
}
|
||||
if strings.Contains(view.String(), userID.String()) {
|
||||
t.Fatal("anonymous view string exposed the internal account ID")
|
||||
}
|
||||
|
||||
views.err = &candidateview.RateLimitedError{RetryAt: time.Now().Add(2 * time.Second)}
|
||||
limited, err := handler.GetOrganizationCandidateCard(ctx, api.GetOrganizationCandidateCardParams{
|
||||
OrgID: organizationID, CandidateHandle: api.CandidateHandle(view.Pseudonym),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("rate-limited GetOrganizationCandidateCard() error = %v", err)
|
||||
}
|
||||
limitedBody, ok := limited.(*api.TooManyRequestsHeaders)
|
||||
if !ok || !limitedBody.RetryAfter.IsSet() || limitedBody.RetryAfter.Value < 1 {
|
||||
t.Fatalf("rate-limit response = %#v, want 429 and Retry-After", limited)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrivacyPublicationMapsConsentConflictAndVersionErrors(t *testing.T) {
|
||||
userID := uuid.New()
|
||||
settings := &privacySettingsStub{publicationErr: domain.ErrPublicationConsentRequired}
|
||||
handler := NewPrivacyHandler(&privacyViewStub{}, settings, "https://app.example.test")
|
||||
ctx := privacyHTTPContext(userID, "https://app.example.test")
|
||||
request := &api.PublicationUpdate{ExpectedVersion: 0, State: api.PublicationStatePublished, Fields: []api.CardField{api.CardFieldStack}}
|
||||
|
||||
response, err := handler.SetMyPublication(ctx, request)
|
||||
if err != nil {
|
||||
t.Fatalf("SetMyPublication() error = %v", err)
|
||||
}
|
||||
conflict, ok := response.(*api.SetMyPublicationConflict)
|
||||
if !ok || conflict.Code != api.ProblemCodeStateConflict || len(conflict.Errors) != 1 ||
|
||||
conflict.Errors[0].Pointer != "/state" || conflict.Errors[0].Code != "consent_required" {
|
||||
t.Fatalf("publication consent response = %#v, want a scoped consent_required conflict", response)
|
||||
}
|
||||
if settings.userID != userID || settings.publicationExpectedVersion != 0 || settings.publicationState != domain.PublicationPublished ||
|
||||
len(settings.publicationFields) != 1 || settings.publicationFields[0] != domain.CardFieldStack {
|
||||
t.Fatalf("publication command = actor %s version %d state %q fields %v", settings.userID, settings.publicationExpectedVersion, settings.publicationState, settings.publicationFields)
|
||||
}
|
||||
|
||||
settings.publicationErr = domain.ErrVisibilityVersionConflict
|
||||
response, err = handler.SetMyPublication(ctx, request)
|
||||
if err != nil {
|
||||
t.Fatalf("stale SetMyPublication() error = %v", err)
|
||||
}
|
||||
precondition, ok := response.(*api.SetMyPublicationPreconditionFailed)
|
||||
if !ok || precondition.Code != api.ProblemCodeVersionConflict {
|
||||
t.Fatalf("publication version response = %#v, want 412 version_conflict", response)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrivacyListsRejectForeignAndMalformedCursorsBeforeRead(t *testing.T) {
|
||||
ownerID := uuid.New()
|
||||
views := &privacyViewStub{}
|
||||
handler := NewPrivacyHandler(views, &privacySettingsStub{}, "https://app.example.test")
|
||||
ctx := privacyHTTPContext(ownerID, "")
|
||||
|
||||
encoded, err := encodePrivacyCursor(ownerID, privacyCursorAccess, time.Date(2026, 10, 7, 12, 0, 0, 123000, time.UTC), uuid.New())
|
||||
if err != nil {
|
||||
t.Fatalf("encodePrivacyCursor() error = %v", err)
|
||||
}
|
||||
if _, err := decodePrivacyCursor(encoded, uuid.New(), privacyCursorAccess); err == nil {
|
||||
t.Fatal("decodePrivacyCursor() accepted a cursor belonging to another owner")
|
||||
}
|
||||
if _, err := decodePrivacyCursor(encoded, ownerID, privacyCursorEvents); err == nil {
|
||||
t.Fatal("decodePrivacyCursor() accepted a cursor from another listing")
|
||||
}
|
||||
|
||||
response, err := handler.ListMyCardAccessHistory(ctx, api.ListMyCardAccessHistoryParams{Cursor: api.NewOptString("malformed")})
|
||||
if err != nil {
|
||||
t.Fatalf("invalid-cursor list error = %v", err)
|
||||
}
|
||||
badCursor, ok := response.(*api.ListMyCardAccessHistoryBadRequest)
|
||||
if !ok || badCursor.Code != api.ProblemCodeValidationFailed || views.accessCalls != 0 {
|
||||
t.Fatalf("invalid cursor response = %#v, read calls = %d", response, views.accessCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrivacyCursorRoundTripsSignedTimestampBoundaries(t *testing.T) {
|
||||
ownerID := uuid.MustParse("00112233-4455-6677-8899-aabbccddeeff")
|
||||
recordID := uuid.MustParse("ffeeddcc-bbaa-9988-7766-554433221100")
|
||||
times := map[string]time.Time{
|
||||
"current positive time": time.Date(2026, 10, 7, 12, 34, 56, 123456000, time.UTC),
|
||||
"before unix epoch": time.Unix(-1, 123456000).UTC(),
|
||||
"end of year 9999": time.Date(9999, 12, 31, 23, 59, 59, 999999000, time.UTC),
|
||||
}
|
||||
for name, want := range times {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
cursor, err := encodePrivacyCursor(ownerID, privacyCursorAccess, want, recordID)
|
||||
if err != nil {
|
||||
t.Fatalf("encodePrivacyCursor() error = %v", err)
|
||||
}
|
||||
got, err := decodePrivacyCursor(cursor, ownerID, privacyCursorAccess)
|
||||
if err != nil {
|
||||
t.Fatalf("decodePrivacyCursor() error = %v", err)
|
||||
}
|
||||
if !got.at.Equal(want) || got.id != recordID {
|
||||
t.Fatalf("decoded cursor = (%s, %s), want (%s, %s)", got.at, got.id, want, recordID)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrivacyCursorAcceptsExistingVersionOneToken(t *testing.T) {
|
||||
const legacyCursor = "AQMAESIzRFVmd4iZqrvM3e7___________8HW8oA_-7dzLuqmYh3ZlVEMyIRAA"
|
||||
ownerID := uuid.MustParse("00112233-4455-6677-8899-aabbccddeeff")
|
||||
wantID := uuid.MustParse("ffeeddcc-bbaa-9988-7766-554433221100")
|
||||
wantTime := time.Unix(-1, 123456000).UTC()
|
||||
|
||||
got, err := decodePrivacyCursor(legacyCursor, ownerID, privacyCursorAccess)
|
||||
if err != nil {
|
||||
t.Fatalf("decodePrivacyCursor(existing token) error = %v", err)
|
||||
}
|
||||
if !got.at.Equal(wantTime) || got.id != wantID {
|
||||
t.Fatalf("decoded legacy cursor = (%s, %s), want (%s, %s)", got.at, got.id, wantTime, wantID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrivacyWriteRejectsOriginBeforeCallingSettings(t *testing.T) {
|
||||
userID := uuid.New()
|
||||
settings := &privacySettingsStub{}
|
||||
handler := NewPrivacyHandler(&privacyViewStub{}, settings, "https://app.example.test")
|
||||
request := &api.SearchStatusUpdate{ExpectedVersion: 0, Value: api.SearchStatusValueLooking}
|
||||
|
||||
response, err := handler.SetMySearchStatus(privacyHTTPContext(userID, "https://attacker.example.test"), request)
|
||||
if err != nil {
|
||||
t.Fatalf("SetMySearchStatus() error = %v", err)
|
||||
}
|
||||
forbidden, ok := response.(*api.SetMySearchStatusForbidden)
|
||||
if !ok || forbidden.Code != api.ProblemCodeCsrfCheckFailed || settings.searchCalls != 0 {
|
||||
t.Fatalf("cross-origin response = %#v, search calls = %d", response, settings.searchCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrivacyMappingKeepsNullAndEmptyPublicationFieldsDistinct(t *testing.T) {
|
||||
userID := uuid.New()
|
||||
closed, err := domain.NewPublication(userID)
|
||||
if err != nil {
|
||||
t.Fatalf("NewPublication() error = %v", err)
|
||||
}
|
||||
response := publicationResponse(closed)
|
||||
if response.State != api.PublicationStateClosed || response.Version != 0 || response.ClosedReason.IsNull() ||
|
||||
response.ClosedReason.Value != api.PublicationClosedReasonNeverPublished || response.Fields == nil || len(response.Fields) != 0 ||
|
||||
!response.ConsentID.IsNull() || !response.PublishedAt.IsNull() {
|
||||
t.Fatalf("closed publication response = %+v", response)
|
||||
}
|
||||
|
||||
search, err := domain.NewSearchStatus(userID)
|
||||
if err != nil {
|
||||
t.Fatalf("NewSearchStatus() error = %v", err)
|
||||
}
|
||||
searchResponse := searchStatusResponse(search, time.Now())
|
||||
if searchResponse.Value != api.SearchStatusValueNotLooking || searchResponse.Lapsed || !searchResponse.ConfirmedAt.IsNull() || !searchResponse.LapsesAt.IsNull() {
|
||||
t.Fatalf("initial search status response = %+v", searchResponse)
|
||||
}
|
||||
}
|
||||
|
||||
func privacyHTTPContext(userID uuid.UUID, origin string) context.Context {
|
||||
request := httptest.NewRequest(http.MethodGet, "https://app.example.test/", nil)
|
||||
if origin != "" {
|
||||
request.Header.Set("Origin", origin)
|
||||
}
|
||||
capture := &privacyRequestContextCapture{}
|
||||
httpmiddleware.SessionRequestMetadata()(capture).ServeHTTP(httptest.NewRecorder(), request)
|
||||
return context.WithValue(capture.context, principalContextKey{}, Principal{UserID: userID, EmailVerified: true})
|
||||
}
|
||||
|
||||
type privacyRequestContextCapture struct{ context context.Context }
|
||||
|
||||
func (capture *privacyRequestContextCapture) ServeHTTP(_ http.ResponseWriter, request *http.Request) {
|
||||
// The middleware supplies the request context that carries origin metadata.
|
||||
capture.context = request.Context()
|
||||
}
|
||||
|
||||
type privacyViewStub struct {
|
||||
card domain.AnonymousCandidateViewDTO
|
||||
preview candidateview.PreviewResult
|
||||
access outbound.CandidateCardAccessListPage
|
||||
err error
|
||||
actorID uuid.UUID
|
||||
organizationID uuid.UUID
|
||||
handle string
|
||||
accessCalls int
|
||||
}
|
||||
|
||||
func (stub *privacyViewStub) GetOrganizationCard(_ context.Context, actorID, organizationID uuid.UUID, handle string) (domain.AnonymousCandidateViewDTO, error) {
|
||||
stub.actorID, stub.organizationID, stub.handle = actorID, organizationID, handle
|
||||
return stub.card, stub.err
|
||||
}
|
||||
|
||||
func (stub *privacyViewStub) GetMyCardPreview(context.Context, uuid.UUID) (candidateview.PreviewResult, error) {
|
||||
return stub.preview, stub.err
|
||||
}
|
||||
|
||||
func (stub *privacyViewStub) ListMyCardAccessHistory(context.Context, outbound.CandidateCardAccessListQuery) (outbound.CandidateCardAccessListPage, error) {
|
||||
stub.accessCalls++
|
||||
return stub.access, stub.err
|
||||
}
|
||||
|
||||
type privacySettingsStub struct {
|
||||
settings outbound.CandidatePrivacySettings
|
||||
publication domain.Publication
|
||||
publicationErr error
|
||||
userID uuid.UUID
|
||||
publicationExpectedVersion int64
|
||||
publicationState domain.PublicationState
|
||||
publicationFields []domain.CardField
|
||||
searchCalls int
|
||||
err error
|
||||
}
|
||||
|
||||
func (stub *privacySettingsStub) GetMyPrivacySettings(context.Context, uuid.UUID) (outbound.CandidatePrivacySettings, error) {
|
||||
return stub.settings, stub.err
|
||||
}
|
||||
|
||||
func (stub *privacySettingsStub) SetMyPublication(_ context.Context, userID uuid.UUID, expectedVersion int64, state domain.PublicationState, fields []domain.CardField) (domain.Publication, error) {
|
||||
stub.userID = userID
|
||||
stub.publicationExpectedVersion, stub.publicationState = expectedVersion, state
|
||||
stub.publicationFields = append([]domain.CardField(nil), fields...)
|
||||
return stub.publication, stub.publicationErr
|
||||
}
|
||||
|
||||
func (stub *privacySettingsStub) SetMySearchStatus(context.Context, uuid.UUID, int64, domain.SearchStatusValue) (domain.SearchStatus, time.Time, error) {
|
||||
stub.searchCalls++
|
||||
return domain.SearchStatus{}, time.Time{}, stub.err
|
||||
}
|
||||
|
||||
func (stub *privacySettingsStub) ListMyPrivacyHistory(context.Context, outbound.CandidatePrivacyEventListQuery) (outbound.CandidatePrivacyEventPage, error) {
|
||||
return outbound.CandidatePrivacyEventPage{}, stub.err
|
||||
}
|
||||
|
||||
func (stub *privacySettingsStub) ListMyHiddenOrganizations(context.Context, outbound.HiddenOrganizationListQuery) (outbound.HiddenOrganizationPage, error) {
|
||||
return outbound.HiddenOrganizationPage{}, stub.err
|
||||
}
|
||||
|
||||
func (stub *privacySettingsStub) HideOrganization(context.Context, uuid.UUID, uuid.UUID) (outbound.HiddenOrganizationRecord, error) {
|
||||
return outbound.HiddenOrganizationRecord{}, stub.err
|
||||
}
|
||||
|
||||
func (stub *privacySettingsStub) UnhideOrganization(context.Context, uuid.UUID, uuid.UUID) error {
|
||||
return stub.err
|
||||
}
|
||||
@@ -0,0 +1,489 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
"lincodex/backend/internal/adapter/primary/http/problem"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
supportcase "lincodex/backend/internal/usecase/supportcase"
|
||||
)
|
||||
|
||||
const (
|
||||
supportCaseCursorVersion = 1
|
||||
supportCaseCursorBytes = 45
|
||||
defaultSupportCaseLimit = 20
|
||||
maxSupportCaseCursorUnixSeconds = uint64(253_402_300_799)
|
||||
)
|
||||
|
||||
// SupportOperations serves owner-scoped support-case creation and reads.
|
||||
type SupportOperations interface {
|
||||
Create(ctx context.Context, command supportcase.CreateCommand) (supportcase.CreateResult, error)
|
||||
GetMyCase(ctx context.Context, ownerID uuid.UUID, id domain.SupportCaseID) (domain.SupportCase, error)
|
||||
ListMyCases(ctx context.Context, command supportcase.ListCommand) (outbound.SupportCaseListPage, error)
|
||||
}
|
||||
|
||||
// SupportHandler serves support-case operations without accepting an owner
|
||||
// identity from the request body or path.
|
||||
type SupportHandler struct {
|
||||
operations SupportOperations
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func NewSupportHandler(operations SupportOperations) *SupportHandler {
|
||||
if operations == nil {
|
||||
panic("v1.NewSupportHandler - support operations must not be nil")
|
||||
}
|
||||
return &SupportHandler{operations: operations, now: time.Now}
|
||||
}
|
||||
|
||||
func (handler *Handler) CreateMySupportCase(
|
||||
ctx context.Context,
|
||||
request api.SupportCaseCreate,
|
||||
params api.CreateMySupportCaseParams,
|
||||
) (api.CreateMySupportCaseRes, error) {
|
||||
if handler.support == nil {
|
||||
return handler.UnimplementedHandler.CreateMySupportCase(ctx, request, params)
|
||||
}
|
||||
return handler.support.CreateMySupportCase(ctx, request, params)
|
||||
}
|
||||
|
||||
func (handler *Handler) GetMySupportCase(
|
||||
ctx context.Context,
|
||||
params api.GetMySupportCaseParams,
|
||||
) (api.GetMySupportCaseRes, error) {
|
||||
if handler.support == nil {
|
||||
return handler.UnimplementedHandler.GetMySupportCase(ctx, params)
|
||||
}
|
||||
return handler.support.GetMySupportCase(ctx, params)
|
||||
}
|
||||
|
||||
func (handler *Handler) ListMySupportCases(
|
||||
ctx context.Context,
|
||||
params api.ListMySupportCasesParams,
|
||||
) (api.ListMySupportCasesRes, error) {
|
||||
if handler.support == nil {
|
||||
return handler.UnimplementedHandler.ListMySupportCases(ctx, params)
|
||||
}
|
||||
return handler.support.ListMySupportCases(ctx, params)
|
||||
}
|
||||
|
||||
func (handler *SupportHandler) CreateMySupportCase(
|
||||
ctx context.Context,
|
||||
request api.SupportCaseCreate,
|
||||
params api.CreateMySupportCaseParams,
|
||||
) (api.CreateMySupportCaseRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.CreateMySupportCaseUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
canonicalBody, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("SupportHandler.CreateMySupportCase - encode canonical request")
|
||||
}
|
||||
command, valid := supportCaseCreateCommand(request)
|
||||
if !valid {
|
||||
return (*api.CreateMySupportCaseBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
|
||||
}
|
||||
command.ActorID = principal.UserID
|
||||
command.IdempotencyKey = params.IdempotencyKey
|
||||
command.CanonicalBody = canonicalBody
|
||||
result, err := handler.operations.Create(ctx, command)
|
||||
if err != nil {
|
||||
return supportCaseCreateFailure(ctx, err)
|
||||
}
|
||||
response, err := supportCaseResponse(result.Case, result.TargetLate)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("SupportHandler.CreateMySupportCase - map case: %w", err)
|
||||
}
|
||||
return &api.SupportCaseHeaders{
|
||||
CacheControl: api.CacheControlNoStoreNoStore,
|
||||
Response: response,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (handler *SupportHandler) GetMySupportCase(
|
||||
ctx context.Context,
|
||||
params api.GetMySupportCaseParams,
|
||||
) (api.GetMySupportCaseRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.GetMySupportCaseUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
supportCase, err := handler.operations.GetMyCase(ctx, principal.UserID, domain.SupportCaseID(params.CaseID))
|
||||
if err != nil {
|
||||
return supportCaseReadFailure(ctx, err)
|
||||
}
|
||||
late := supportCase.ResponseTarget().IsLate(handler.now().UTC())
|
||||
response, err := supportCaseResponse(supportCase, late)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("SupportHandler.GetMySupportCase - map case: %w", err)
|
||||
}
|
||||
return &api.SupportCaseHeaders{
|
||||
CacheControl: api.CacheControlNoStoreNoStore,
|
||||
Response: response,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (handler *SupportHandler) ListMySupportCases(
|
||||
ctx context.Context,
|
||||
params api.ListMySupportCasesParams,
|
||||
) (api.ListMySupportCasesRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.ListMySupportCasesUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
command, pointer := supportCaseListCommand(principal.UserID, params)
|
||||
if pointer != "" {
|
||||
return supportCaseListInvalid(ctx, pointer), nil
|
||||
}
|
||||
page, err := handler.operations.ListMyCases(ctx, command)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, supportcase.ErrForbidden), errors.Is(err, supportcase.ErrEmailNotVerified),
|
||||
errors.Is(err, outbound.ErrUserNotFound):
|
||||
return (*api.ListMySupportCasesUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
items := make([]api.SupportCaseSummary, 0, len(page.Items))
|
||||
for _, item := range page.Items {
|
||||
late := supportResponseTargetLate(item.ResponseTarget, handler.now().UTC())
|
||||
summary, err := supportCaseSummaryResponse(item, late)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("SupportHandler.ListMySupportCases - map summary: %w", err)
|
||||
}
|
||||
items = append(items, summary)
|
||||
}
|
||||
next := api.NilString{}
|
||||
next.SetToNull()
|
||||
if page.HasMore && len(page.Items) > 0 {
|
||||
cursor, err := encodeSupportCaseCursor(principal.UserID, outbound.SupportCasePositionOf(page.Items[len(page.Items)-1]))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("SupportHandler.ListMySupportCases - encode cursor: %w", err)
|
||||
}
|
||||
next.SetTo(cursor)
|
||||
}
|
||||
return &api.SupportCaseListHeaders{
|
||||
CacheControl: api.CacheControlNoStoreNoStore,
|
||||
Response: api.SupportCaseList{
|
||||
Items: items,
|
||||
Page: api.PageInfo{HasMore: page.HasMore, NextCursor: next},
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func supportCaseCreateCommand(request api.SupportCaseCreate) (supportcase.CreateCommand, bool) {
|
||||
var command supportcase.CreateCommand
|
||||
switch request.Type {
|
||||
case api.SupportCaseCreateSupportSupportCaseCreate:
|
||||
value := request.SupportCaseCreateSupport
|
||||
command.Type = domain.SupportCaseTypeSupport
|
||||
command.Description = string(value.Description)
|
||||
if object, ok := value.Object.Get(); ok {
|
||||
command.Object = &domain.SupportCaseReference{Type: domain.SupportCaseObjectType(object.Type), ID: object.ID}
|
||||
}
|
||||
if target, ok := value.AssessmentTarget.Get(); ok {
|
||||
command.AssessmentTarget = &domain.SupportCaseAssessmentTarget{
|
||||
Specialization: domain.SpecializationCode(target.Specialization), Grade: domain.GradeCode(target.Grade),
|
||||
}
|
||||
}
|
||||
case api.SupportCaseCreateComplaintSupportCaseCreate:
|
||||
value := request.SupportCaseCreateComplaint
|
||||
command.Type = domain.SupportCaseTypeComplaint
|
||||
command.Description = string(value.Description)
|
||||
command.ComplaintReason = supportComplaintReasonPointer(domain.SupportCaseComplaintReason(value.ComplaintReason))
|
||||
command.Object = &domain.SupportCaseReference{Type: domain.SupportCaseObjectType(value.Object.Type), ID: value.Object.ID}
|
||||
case api.SupportCaseCreateGradeAppealSupportCaseCreate:
|
||||
value := request.SupportCaseCreateGradeAppeal
|
||||
command.Type = domain.SupportCaseTypeGradeAppeal
|
||||
command.Description = string(value.Description)
|
||||
command.Object = &domain.SupportCaseReference{Type: domain.SupportCaseObjectType(value.Object.Type), ID: value.Object.ID}
|
||||
case api.SupportCaseCreateAnticheatAppealSupportCaseCreate:
|
||||
value := request.SupportCaseCreateAnticheatAppeal
|
||||
command.Type = domain.SupportCaseTypeAnticheatAppeal
|
||||
command.Description = string(value.Description)
|
||||
command.Object = &domain.SupportCaseReference{Type: domain.SupportCaseObjectType(value.Object.Type), ID: value.Object.ID}
|
||||
case api.SupportCaseCreateManualAssessmentSupportCaseCreate:
|
||||
value := request.SupportCaseCreateManualAssessment
|
||||
command.Type = domain.SupportCaseTypeManualAssessment
|
||||
command.Description = string(value.Description)
|
||||
command.AssessmentTarget = &domain.SupportCaseAssessmentTarget{
|
||||
Specialization: domain.SpecializationCode(value.AssessmentTarget.Specialization),
|
||||
Grade: domain.GradeCode(value.AssessmentTarget.Grade),
|
||||
}
|
||||
if object, ok := value.Object.Get(); ok {
|
||||
command.Object = &domain.SupportCaseReference{Type: domain.SupportCaseObjectType(object.Type), ID: object.ID}
|
||||
}
|
||||
default:
|
||||
return supportcase.CreateCommand{}, false
|
||||
}
|
||||
return command, true
|
||||
}
|
||||
|
||||
func supportCaseCreateFailure(ctx context.Context, err error) (api.CreateMySupportCaseRes, error) {
|
||||
switch {
|
||||
case errors.Is(err, supportcase.ErrForbidden), errors.Is(err, supportcase.ErrEmailNotVerified):
|
||||
return (*api.CreateMySupportCaseForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
case errors.Is(err, outbound.ErrUserNotFound):
|
||||
return (*api.CreateMySupportCaseUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
case errors.Is(err, outbound.ErrSupportCaseNotFound):
|
||||
return (*api.CreateMySupportCaseNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
|
||||
case errors.Is(err, supportcase.ErrStateConflict), errors.Is(err, outbound.ErrSupportCaseConflict):
|
||||
return (*api.CreateMySupportCaseConflict)(&problem.New(ctx, api.ProblemCodeStateConflict).Response), nil
|
||||
case errors.Is(err, supportcase.ErrIdempotencyKeyReused):
|
||||
return (*api.CreateMySupportCaseUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil
|
||||
case errors.Is(err, supportcase.ErrInvalidIdempotencyKey):
|
||||
return (*api.CreateMySupportCaseBadRequest)(
|
||||
&problem.InvalidField(ctx, api.ProblemFieldLocationHeader, "/Idempotency-Key").Response,
|
||||
), nil
|
||||
case errors.Is(err, supportcase.ErrRateLimited):
|
||||
limited, ok := errors.AsType[*supportcase.RateLimitedError](err)
|
||||
if !ok || limited == nil {
|
||||
return nil, errors.New("SupportHandler.CreateMySupportCase - rate limit error has no retry interval")
|
||||
}
|
||||
return problem.RateLimited(ctx, wholeSeconds(limited.RetryAfter)), nil
|
||||
case errors.Is(err, supportcase.ErrInvalidCreateRequest), errors.Is(err, domain.ErrInvalidSupportCase):
|
||||
fieldError, ok := errors.AsType[*domain.SupportCaseFieldError](err)
|
||||
if !ok {
|
||||
return (*api.CreateMySupportCaseBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationBody, "").Response), nil
|
||||
}
|
||||
return (*api.CreateMySupportCaseBadRequest)(
|
||||
&problem.InvalidField(ctx, api.ProblemFieldLocationBody, fieldError.Pointer).Response,
|
||||
), nil
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
func supportCaseReadFailure(ctx context.Context, err error) (api.GetMySupportCaseRes, error) {
|
||||
switch {
|
||||
case errors.Is(err, supportcase.ErrForbidden), errors.Is(err, supportcase.ErrEmailNotVerified),
|
||||
errors.Is(err, outbound.ErrUserNotFound):
|
||||
return (*api.GetMySupportCaseUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
case errors.Is(err, outbound.ErrSupportCaseNotFound):
|
||||
return (*api.GetMySupportCaseNotFound)(&problem.New(ctx, api.ProblemCodeNotFound).Response), nil
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
func supportCaseListCommand(actorID uuid.UUID, params api.ListMySupportCasesParams) (supportcase.ListCommand, string) {
|
||||
limit, ok := params.Limit.Get()
|
||||
if !ok {
|
||||
limit = defaultSupportCaseLimit
|
||||
}
|
||||
if limit < 1 || limit > outbound.MaxSupportCasePageSize {
|
||||
return supportcase.ListCommand{}, "limit"
|
||||
}
|
||||
command := supportcase.ListCommand{ActorID: actorID, Limit: limit}
|
||||
if cursor, ok := params.Cursor.Get(); ok {
|
||||
position, err := decodeSupportCaseCursor(cursor, actorID)
|
||||
if err != nil {
|
||||
return supportcase.ListCommand{}, "cursor"
|
||||
}
|
||||
command.After = &position
|
||||
}
|
||||
return command, ""
|
||||
}
|
||||
|
||||
func supportCaseListInvalid(ctx context.Context, pointer string) *api.ListMySupportCasesBadRequest {
|
||||
return (*api.ListMySupportCasesBadRequest)(
|
||||
&problem.InvalidField(ctx, api.ProblemFieldLocationQuery, "/"+pointer).Response,
|
||||
)
|
||||
}
|
||||
|
||||
func encodeSupportCaseCursor(actorID uuid.UUID, position outbound.SupportCaseListPosition) (string, error) {
|
||||
seconds, nanos := position.CreatedAt.Unix(), position.CreatedAt.Nanosecond()
|
||||
if actorID == uuid.Nil || position.ID.IsZero() || !validSupportCaseCursorTime(position.CreatedAt) ||
|
||||
seconds < 0 || nanos < 0 || nanos >= 1_000_000_000 {
|
||||
return "", errors.New("support case cursor requires an actor and a valid position")
|
||||
}
|
||||
var value [supportCaseCursorBytes]byte
|
||||
value[0] = supportCaseCursorVersion
|
||||
copy(value[1:17], actorID[:])
|
||||
binary.BigEndian.PutUint64(value[17:25], uint64(seconds))
|
||||
binary.BigEndian.PutUint32(value[25:29], uint32(nanos))
|
||||
caseID := position.ID.UUID()
|
||||
copy(value[29:45], caseID[:])
|
||||
return base64.RawURLEncoding.EncodeToString(value[:]), nil
|
||||
}
|
||||
|
||||
func decodeSupportCaseCursor(cursor string, actorID uuid.UUID) (outbound.SupportCaseListPosition, error) {
|
||||
value, err := base64.RawURLEncoding.DecodeString(cursor)
|
||||
if err != nil || len(value) != supportCaseCursorBytes || actorID == uuid.Nil ||
|
||||
base64.RawURLEncoding.EncodeToString(value) != cursor || value[0] != supportCaseCursorVersion ||
|
||||
uuid.UUID(value[1:17]) != actorID {
|
||||
return outbound.SupportCaseListPosition{}, errors.New("support case cursor is invalid")
|
||||
}
|
||||
nanos := binary.BigEndian.Uint32(value[25:29])
|
||||
caseID := uuid.UUID(value[29:45])
|
||||
seconds := binary.BigEndian.Uint64(value[17:25])
|
||||
if nanos >= 1_000_000_000 || caseID == uuid.Nil || seconds > maxSupportCaseCursorUnixSeconds {
|
||||
return outbound.SupportCaseListPosition{}, errors.New("support case cursor position is invalid")
|
||||
}
|
||||
createdAt := time.Unix(int64(seconds), int64(nanos)).UTC()
|
||||
if !validSupportCaseCursorTime(createdAt) {
|
||||
return outbound.SupportCaseListPosition{}, errors.New("support case cursor timestamp is invalid")
|
||||
}
|
||||
return outbound.SupportCaseListPosition{CreatedAt: createdAt, ID: domain.SupportCaseID(caseID)}, nil
|
||||
}
|
||||
|
||||
func validSupportCaseCursorTime(value time.Time) bool {
|
||||
utc := value.UTC()
|
||||
return !value.IsZero() && utc.Year() >= 1 && utc.Year() <= 9999 && value.Unix() >= 0 &&
|
||||
value.Nanosecond()%int(time.Microsecond) == 0
|
||||
}
|
||||
|
||||
func supportCaseResponse(supportCase domain.SupportCase, targetLate bool) (api.SupportCase, error) {
|
||||
snapshot := supportCase.Snapshot()
|
||||
target, err := checkedSupportResponseTarget(snapshot.ResponseTarget, targetLate)
|
||||
if err != nil {
|
||||
return api.SupportCase{}, err
|
||||
}
|
||||
response := api.SupportCase{
|
||||
ID: snapshot.ID.UUID(), Number: api.SupportCaseNumber(snapshot.Number),
|
||||
Type: api.SupportCaseType(snapshot.Type), Status: api.SupportCaseStatus(snapshot.Status),
|
||||
Description: api.SupportCaseDescription(snapshot.Description),
|
||||
ResponseTarget: target,
|
||||
History: make([]api.SupportCaseEvent, 0, len(snapshot.History)),
|
||||
CreatedAt: api.Timestamp(snapshot.CreatedAt), UpdatedAt: api.Timestamp(snapshot.UpdatedAt),
|
||||
}
|
||||
response.Object = supportCaseObject(snapshot.Object)
|
||||
response.AssessmentTarget = supportCaseAssessmentTarget(snapshot.AssessmentTarget)
|
||||
response.ComplaintReason = supportCaseComplaintReason(snapshot.ComplaintReason)
|
||||
response.RubricVersion = supportCaseInt32(snapshot.RubricVersion)
|
||||
response.Decision = supportCaseDecision(snapshot.Decision)
|
||||
for _, event := range snapshot.History {
|
||||
response.History = append(response.History, supportCaseEvent(event))
|
||||
}
|
||||
return response, nil
|
||||
}
|
||||
|
||||
func supportCaseSummaryResponse(summary domain.SupportCaseSummary, targetLate bool) (api.SupportCaseSummary, error) {
|
||||
target, err := checkedSupportResponseTarget(summary.ResponseTarget, targetLate)
|
||||
if err != nil {
|
||||
return api.SupportCaseSummary{}, err
|
||||
}
|
||||
response := api.SupportCaseSummary{
|
||||
ID: summary.ID.UUID(), Number: api.SupportCaseNumber(summary.Number),
|
||||
Type: api.SupportCaseType(summary.Type), Status: api.SupportCaseStatus(summary.Status),
|
||||
Object: supportCaseObject(summary.Object), AssessmentTarget: supportCaseAssessmentTarget(summary.AssessmentTarget),
|
||||
ResponseTarget: target, CreatedAt: api.Timestamp(summary.CreatedAt), UpdatedAt: api.Timestamp(summary.UpdatedAt),
|
||||
}
|
||||
if summary.DecisionOutcome == nil {
|
||||
response.DecisionOutcome.SetToNull()
|
||||
} else {
|
||||
response.DecisionOutcome.SetTo(api.SupportCaseDecisionOutcome(*summary.DecisionOutcome))
|
||||
}
|
||||
return response, nil
|
||||
}
|
||||
|
||||
func checkedSupportResponseTarget(snapshot domain.SupportResponseTargetSnapshot, late bool) (api.SupportResponseTarget, error) {
|
||||
if _, err := domain.NewSupportResponseTarget(snapshot); err != nil {
|
||||
return api.SupportResponseTarget{}, err
|
||||
}
|
||||
response := api.SupportResponseTarget{
|
||||
Kind: api.SupportResponseTargetKindOperationalGoal,
|
||||
BusinessDays: int32(snapshot.BusinessDays), DueAt: api.Timestamp(snapshot.DueAt),
|
||||
Late: late, PolicyVersion: snapshot.PolicyVersion,
|
||||
}
|
||||
if snapshot.AnsweredAt == nil {
|
||||
response.AnsweredAt.SetToNull()
|
||||
} else {
|
||||
response.AnsweredAt.SetTo(api.Timestamp(*snapshot.AnsweredAt))
|
||||
}
|
||||
return response, nil
|
||||
}
|
||||
|
||||
func supportResponseTargetLate(snapshot domain.SupportResponseTargetSnapshot, at time.Time) bool {
|
||||
target, err := domain.NewSupportResponseTarget(snapshot)
|
||||
return err == nil && target.IsLate(at)
|
||||
}
|
||||
|
||||
func supportCaseObject(reference *domain.SupportCaseReference) api.NilSupportCaseObjectReference {
|
||||
var result api.NilSupportCaseObjectReference
|
||||
if reference == nil {
|
||||
result.SetToNull()
|
||||
return result
|
||||
}
|
||||
result.SetTo(api.SupportCaseObjectReference{Type: api.SupportCaseObjectType(reference.Type), ID: reference.ID})
|
||||
return result
|
||||
}
|
||||
|
||||
func supportCaseAssessmentTarget(target *domain.SupportCaseAssessmentTarget) api.NilSupportCaseAssessmentTarget {
|
||||
var result api.NilSupportCaseAssessmentTarget
|
||||
if target == nil {
|
||||
result.SetToNull()
|
||||
return result
|
||||
}
|
||||
result.SetTo(api.SupportCaseAssessmentTarget{
|
||||
Specialization: api.SpecializationCode(target.Specialization), Grade: api.GradeCode(target.Grade),
|
||||
})
|
||||
return result
|
||||
}
|
||||
|
||||
func supportCaseComplaintReason(reason *domain.SupportCaseComplaintReason) api.NilSupportCaseComplaintReason {
|
||||
var result api.NilSupportCaseComplaintReason
|
||||
if reason == nil {
|
||||
result.SetToNull()
|
||||
return result
|
||||
}
|
||||
result.SetTo(api.SupportCaseComplaintReason(*reason))
|
||||
return result
|
||||
}
|
||||
|
||||
func supportCaseInt32(value *int32) api.NilInt32 {
|
||||
var result api.NilInt32
|
||||
if value == nil {
|
||||
result.SetToNull()
|
||||
return result
|
||||
}
|
||||
result.SetTo(*value)
|
||||
return result
|
||||
}
|
||||
|
||||
func supportCaseDecision(decision *domain.SupportCaseDecisionSnapshot) api.NilSupportCaseDecision {
|
||||
var result api.NilSupportCaseDecision
|
||||
if decision == nil {
|
||||
result.SetToNull()
|
||||
return result
|
||||
}
|
||||
result.SetTo(api.SupportCaseDecision{
|
||||
Outcome: api.SupportCaseDecisionOutcome(decision.Outcome),
|
||||
Reason: api.SupportCasePublicText(decision.Reason), DecidedAt: api.Timestamp(decision.DecidedAt),
|
||||
})
|
||||
return result
|
||||
}
|
||||
|
||||
func supportCaseEvent(event domain.SupportCaseEventSnapshot) api.SupportCaseEvent {
|
||||
result := api.SupportCaseEvent{
|
||||
Sequence: event.Sequence, Kind: api.SupportCaseEventKind(event.Kind),
|
||||
Actor: api.SupportCaseActorKind(event.Actor), OccurredAt: api.Timestamp(event.OccurredAt),
|
||||
}
|
||||
if event.Status == nil {
|
||||
result.Status.SetToNull()
|
||||
} else {
|
||||
result.Status.SetTo(api.SupportCaseStatus(*event.Status))
|
||||
}
|
||||
if event.Message == nil {
|
||||
result.Message.SetToNull()
|
||||
} else {
|
||||
result.Message.SetTo(api.SupportCasePublicText(*event.Message))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func supportComplaintReasonPointer(value domain.SupportCaseComplaintReason) *domain.SupportCaseComplaintReason {
|
||||
return &value
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
supportcase "lincodex/backend/internal/usecase/supportcase"
|
||||
)
|
||||
|
||||
func TestSupportCaseCreateCommandMapsManualRequestWithoutPriorAttempt(t *testing.T) {
|
||||
request := api.SupportCaseCreate{
|
||||
Type: api.SupportCaseCreateManualAssessmentSupportCaseCreate,
|
||||
SupportCaseCreateManualAssessment: api.SupportCaseCreateManualAssessment{
|
||||
Type: api.SupportCaseCreateManualAssessmentTypeManualAssessment,
|
||||
Description: api.SupportCaseDescription("Please assess my Go skills."),
|
||||
AssessmentTarget: api.SupportCaseAssessmentTarget{
|
||||
Specialization: api.SpecializationCodeBackend,
|
||||
Grade: api.GradeCodeJunior,
|
||||
},
|
||||
},
|
||||
}
|
||||
command, valid := supportCaseCreateCommand(request)
|
||||
if !valid || command.Type != domain.SupportCaseTypeManualAssessment || command.Description != "Please assess my Go skills." ||
|
||||
command.AssessmentTarget == nil || command.AssessmentTarget.Specialization != domain.SpecializationBackend ||
|
||||
command.AssessmentTarget.Grade != domain.GradeJunior || command.Object != nil {
|
||||
t.Fatalf("supportCaseCreateCommand() = %+v, %v; want a standalone manual-assessment request", command, valid)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSupportCaseCursorIsBoundToOwnerAndStoredPrecision(t *testing.T) {
|
||||
ownerID := uuid.Must(uuid.NewV7())
|
||||
position := outbound.SupportCaseListPosition{
|
||||
CreatedAt: time.Date(2026, time.October, 7, 10, 0, 0, 123456000, time.UTC),
|
||||
ID: domain.SupportCaseID(uuid.Must(uuid.NewV7())),
|
||||
}
|
||||
cursor, err := encodeSupportCaseCursor(ownerID, position)
|
||||
if err != nil {
|
||||
t.Fatalf("encodeSupportCaseCursor() error = %v", err)
|
||||
}
|
||||
decoded, err := decodeSupportCaseCursor(cursor, ownerID)
|
||||
if err != nil || decoded.ID != position.ID || !decoded.CreatedAt.Equal(position.CreatedAt) {
|
||||
t.Fatalf("decodeSupportCaseCursor() = %+v, %v, want %+v", decoded, err, position)
|
||||
}
|
||||
if _, err := decodeSupportCaseCursor(cursor, uuid.Must(uuid.NewV7())); err == nil {
|
||||
t.Fatal("decodeSupportCaseCursor() accepted a cursor from another owner")
|
||||
}
|
||||
if _, err := encodeSupportCaseCursor(ownerID, outbound.SupportCaseListPosition{
|
||||
CreatedAt: position.CreatedAt.Add(time.Nanosecond), ID: position.ID,
|
||||
}); err == nil {
|
||||
t.Fatal("encodeSupportCaseCursor() accepted precision PostgreSQL cannot preserve")
|
||||
}
|
||||
for _, invalidTime := range []time.Time{
|
||||
time.Unix(-1, 0).UTC(),
|
||||
time.Date(10000, time.January, 1, 0, 0, 0, 0, time.UTC),
|
||||
} {
|
||||
if _, err := encodeSupportCaseCursor(ownerID, outbound.SupportCaseListPosition{CreatedAt: invalidTime, ID: position.ID}); err == nil {
|
||||
t.Errorf("encodeSupportCaseCursor() accepted unsupported time %v", invalidTime)
|
||||
}
|
||||
}
|
||||
for name, mutate := range map[string]func([]byte){
|
||||
"out-of-range year": func(value []byte) {
|
||||
binary.BigEndian.PutUint64(value[17:25], uint64(time.Date(10000, time.January, 1, 0, 0, 0, 0, time.UTC).Unix()))
|
||||
},
|
||||
"sub-microsecond precision": func(value []byte) {
|
||||
binary.BigEndian.PutUint32(value[25:29], 1)
|
||||
},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
value, err := base64.RawURLEncoding.DecodeString(cursor)
|
||||
if err != nil {
|
||||
t.Fatalf("DecodeString() error = %v", err)
|
||||
}
|
||||
mutate(value)
|
||||
invalid := base64.RawURLEncoding.EncodeToString(value)
|
||||
if _, err := decodeSupportCaseCursor(invalid, ownerID); err == nil {
|
||||
t.Fatal("decodeSupportCaseCursor() accepted an unsupported position")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSupportCaseRateLimitErrorPreservesRetryAfter(t *testing.T) {
|
||||
result, err := supportCaseCreateFailure(principalTestContext(), &supportcase.RateLimitedError{
|
||||
RetryAfter: 1500 * time.Millisecond,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("supportCaseCreateFailure() error = %v", err)
|
||||
}
|
||||
response, ok := result.(*api.TooManyRequestsHeaders)
|
||||
if !ok {
|
||||
t.Fatalf("supportCaseCreateFailure() result = %T, want *TooManyRequestsHeaders", result)
|
||||
}
|
||||
if seconds, present := response.RetryAfter.Get(); !present || seconds != 2 {
|
||||
t.Fatalf("Retry-After = %d, %v; want 2 seconds", seconds, present)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSupportCaseReadAuthorizationFailuresUseDocumented401(t *testing.T) {
|
||||
for _, operation := range []string{"get", "list"} {
|
||||
for _, failure := range []error{supportcase.ErrForbidden, supportcase.ErrEmailNotVerified} {
|
||||
t.Run(operation+"/"+failure.Error(), func(t *testing.T) {
|
||||
operations := &supportOperationsStub{getError: failure, listError: failure}
|
||||
handler := NewSupportHandler(operations)
|
||||
if operation == "get" {
|
||||
result, err := handler.GetMySupportCase(principalTestContext(), api.GetMySupportCaseParams{CaseID: uuid.Must(uuid.NewV7())})
|
||||
if err != nil {
|
||||
t.Fatalf("GetMySupportCase() error = %v", err)
|
||||
}
|
||||
if _, ok := result.(*api.GetMySupportCaseUnauthorized); !ok {
|
||||
t.Fatalf("GetMySupportCase() result = %T, want documented 401", result)
|
||||
}
|
||||
return
|
||||
}
|
||||
result, err := handler.ListMySupportCases(principalTestContext(), api.ListMySupportCasesParams{})
|
||||
if err != nil {
|
||||
t.Fatalf("ListMySupportCases() error = %v", err)
|
||||
}
|
||||
if _, ok := result.(*api.ListMySupportCasesUnauthorized); !ok {
|
||||
t.Fatalf("ListMySupportCases() result = %T, want documented 401", result)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSupportCaseHandlerBindsCreateToPrincipalAndReturnsNoStore(t *testing.T) {
|
||||
ctx := principalTestContext()
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
t.Fatal("principalTestContext() did not set a principal")
|
||||
}
|
||||
createdAt := time.Date(2026, time.October, 7, 10, 0, 0, 0, time.UTC)
|
||||
responseTarget, err := domain.DemoSupportPolicy().ResponseTarget(domain.SupportCaseTypeSupport, 4, createdAt)
|
||||
if err != nil {
|
||||
t.Fatalf("ResponseTarget() error = %v", err)
|
||||
}
|
||||
supportCase, err := domain.NewSupportCase(domain.NewSupportCaseInput{
|
||||
Number: "SC-2026-000123", OwnerID: principal.UserID, Type: domain.SupportCaseTypeSupport,
|
||||
Description: "Please help with my account.", ResponseTarget: responseTarget, CreatedAt: createdAt,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewSupportCase() error = %v", err)
|
||||
}
|
||||
operations := &supportOperationsStub{createResult: supportcase.CreateResult{Case: supportCase}}
|
||||
handler := NewSupportHandler(operations)
|
||||
request := api.SupportCaseCreate{
|
||||
Type: api.SupportCaseCreateSupportSupportCaseCreate,
|
||||
SupportCaseCreateSupport: api.SupportCaseCreateSupport{
|
||||
Type: api.SupportCaseCreateSupportTypeSupport,
|
||||
Description: api.SupportCaseDescription("Please help with my account."),
|
||||
},
|
||||
}
|
||||
result, err := handler.CreateMySupportCase(ctx, request, api.CreateMySupportCaseParams{IdempotencyKey: "support-key-1"})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateMySupportCase() error = %v", err)
|
||||
}
|
||||
response, ok := result.(*api.SupportCaseHeaders)
|
||||
if !ok {
|
||||
t.Fatalf("CreateMySupportCase() result type = %T, want *SupportCaseHeaders", result)
|
||||
}
|
||||
if response.CacheControl != api.CacheControlNoStoreNoStore || response.Response.ID != supportCase.ID().UUID() ||
|
||||
response.Response.Type != api.SupportCaseTypeSupport || response.Response.Description != "Please help with my account." {
|
||||
t.Fatalf("CreateMySupportCase() response = %+v", response)
|
||||
}
|
||||
if operations.createCommand.ActorID != principal.UserID || operations.createCommand.IdempotencyKey != "support-key-1" ||
|
||||
operations.createCommand.Description != "Please help with my account." || len(operations.createCommand.CanonicalBody) == 0 {
|
||||
t.Fatalf("create command did not preserve authenticated scope and body: %+v", operations.createCommand)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSupportCaseHandlerRejectsMissingPrincipalBeforeCallingOperations(t *testing.T) {
|
||||
operations := &supportOperationsStub{}
|
||||
handler := NewSupportHandler(operations)
|
||||
_, err := handler.GetMySupportCase(context.Background(), api.GetMySupportCaseParams{CaseID: uuid.Must(uuid.NewV7())})
|
||||
if err != nil {
|
||||
t.Fatalf("GetMySupportCase() error = %v", err)
|
||||
}
|
||||
if operations.getCalls != 0 {
|
||||
t.Fatalf("operations.GetMyCase calls = %d, want none", operations.getCalls)
|
||||
}
|
||||
}
|
||||
|
||||
type supportOperationsStub struct {
|
||||
createCommand supportcase.CreateCommand
|
||||
createResult supportcase.CreateResult
|
||||
createError error
|
||||
getResult domain.SupportCase
|
||||
getError error
|
||||
getCalls int
|
||||
listPage outbound.SupportCaseListPage
|
||||
listError error
|
||||
}
|
||||
|
||||
func (stub *supportOperationsStub) Create(_ context.Context, command supportcase.CreateCommand) (supportcase.CreateResult, error) {
|
||||
stub.createCommand = command
|
||||
return stub.createResult, stub.createError
|
||||
}
|
||||
|
||||
func (stub *supportOperationsStub) GetMyCase(_ context.Context, _ uuid.UUID, _ domain.SupportCaseID) (domain.SupportCase, error) {
|
||||
stub.getCalls++
|
||||
return stub.getResult, stub.getError
|
||||
}
|
||||
|
||||
func (stub *supportOperationsStub) ListMyCases(_ context.Context, _ supportcase.ListCommand) (outbound.SupportCaseListPage, error) {
|
||||
return stub.listPage, stub.listError
|
||||
}
|
||||
|
||||
var _ SupportOperations = (*supportOperationsStub)(nil)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,183 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
func (repository assessmentAttemptRepository) GetAvailabilityActiveAttempt(
|
||||
ctx context.Context,
|
||||
userID uuid.UUID,
|
||||
specialization domain.SpecializationCode,
|
||||
) (outbound.AssessmentActiveAttemptSummary, bool, error) {
|
||||
const location = "assessmentAttemptRepository.GetAvailabilityActiveAttempt"
|
||||
if userID == uuid.Nil || !specialization.IsKnown() {
|
||||
return outbound.AssessmentActiveAttemptSummary{}, false, fmt.Errorf("%s - candidate track is invalid: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
row, err := repository.queries.GetAssessmentAvailabilityActiveAttempt(ctx, sqlc.GetAssessmentAvailabilityActiveAttemptParams{
|
||||
UserID: pgUUID(userID), Specialization: pgText(string(specialization)),
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return outbound.AssessmentActiveAttemptSummary{}, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return outbound.AssessmentActiveAttemptSummary{}, false, fmt.Errorf("%s - read active attempt: %w", location, mapAssessmentAttemptError(err))
|
||||
}
|
||||
if !row.ID.Valid || row.ID.Bytes == uuid.Nil || !row.ExpiresAt.Valid {
|
||||
return outbound.AssessmentActiveAttemptSummary{}, false, fmt.Errorf("%s - active attempt summary is invalid", location)
|
||||
}
|
||||
return outbound.AssessmentActiveAttemptSummary{
|
||||
ID: domain.AssessmentAttemptID(row.ID.Bytes), ExpiresAt: row.ExpiresAt.Time,
|
||||
}, true, nil
|
||||
}
|
||||
|
||||
func (repository assessmentAttemptRepository) ListAvailabilityRootSummaries(
|
||||
ctx context.Context,
|
||||
userID uuid.UUID,
|
||||
specialization domain.SpecializationCode,
|
||||
since time.Time,
|
||||
) ([]outbound.AssessmentRootAvailabilitySummary, error) {
|
||||
const location = "assessmentAttemptRepository.ListAvailabilityRootSummaries"
|
||||
if userID == uuid.Nil || !specialization.IsKnown() || since.IsZero() {
|
||||
return nil, fmt.Errorf("%s - candidate track and horizon are invalid: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
rows, err := repository.queries.ListAssessmentAvailabilityRootSummaries(ctx, sqlc.ListAssessmentAvailabilityRootSummariesParams{
|
||||
UserID: pgUUID(userID), Specialization: pgText(string(specialization)), Since: pgTime(since),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - read root summaries: %w", location, mapAssessmentAttemptError(err))
|
||||
}
|
||||
summaries := make([]outbound.AssessmentRootAvailabilitySummary, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
summary, err := restoreAvailabilityRootSummary(row)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - restore root summary: %w", location, err)
|
||||
}
|
||||
summaries = append(summaries, summary)
|
||||
}
|
||||
return summaries, nil
|
||||
}
|
||||
|
||||
func restoreAvailabilityRootSummary(
|
||||
row sqlc.ListAssessmentAvailabilityRootSummariesRow,
|
||||
) (outbound.AssessmentRootAvailabilitySummary, error) {
|
||||
if !validAvailabilityRootSummary(row) {
|
||||
return outbound.AssessmentRootAvailabilitySummary{}, errors.New("stored assessment root summary is invalid")
|
||||
}
|
||||
rootGrade := domain.GradeCode(row.RootTargetGrade.String)
|
||||
latestGrade := domain.GradeCode(row.LatestTargetGrade.String)
|
||||
return outbound.AssessmentRootAvailabilitySummary{
|
||||
RootTargetGrade: rootGrade, RootCreatedAt: row.RootCreatedAt.Time,
|
||||
RootUpdatedAt: row.RootUpdatedAt.Time, RootExpiresAt: row.RootExpiresAt.Time,
|
||||
RootState: domain.AssessmentAttemptState(row.RootState), RootOutcome: domain.AssessmentAttemptOutcome(row.RootOutcome.String),
|
||||
RootChainDeadline: row.RootChainDeadline.Time, LatestTargetGrade: latestGrade,
|
||||
LatestUpdatedAt: row.LatestUpdatedAt.Time, LatestExpiresAt: row.LatestExpiresAt.Time,
|
||||
LatestState: domain.AssessmentAttemptState(row.LatestState), LatestOutcome: domain.AssessmentAttemptOutcome(row.LatestOutcome.String),
|
||||
LatestChainDeadline: row.LatestChainDeadline.Time, LatestPlatformError: row.LatestPlatformError,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func validAvailabilityRootSummary(row sqlc.ListAssessmentAvailabilityRootSummariesRow) bool {
|
||||
rootGrade, latestGrade := domain.GradeCode(row.RootTargetGrade.String), domain.GradeCode(row.LatestTargetGrade.String)
|
||||
return row.RootTargetGrade.Valid && rootGrade.IsKnown() && row.LatestTargetGrade.Valid && latestGrade.IsKnown() &&
|
||||
row.RootCreatedAt.Valid && row.RootUpdatedAt.Valid && row.RootExpiresAt.Valid && row.RootChainDeadline.Valid &&
|
||||
row.LatestUpdatedAt.Valid && row.LatestExpiresAt.Valid && row.LatestChainDeadline.Valid &&
|
||||
validAvailabilityAttemptState(row.RootState) && validAvailabilityAttemptState(row.LatestState) &&
|
||||
validAvailabilityOutcome(row.RootOutcome) && validAvailabilityOutcome(row.LatestOutcome)
|
||||
}
|
||||
|
||||
func (repository assessmentAttemptRepository) GetRootQuotaSnapshot(
|
||||
ctx context.Context,
|
||||
userID uuid.UUID,
|
||||
since, asOf time.Time,
|
||||
window time.Duration,
|
||||
maxAttempts int32,
|
||||
) (outbound.AssessmentRootQuotaSnapshot, error) {
|
||||
const location = "assessmentAttemptRepository.GetRootQuotaSnapshot"
|
||||
if userID == uuid.Nil || since.IsZero() || asOf.IsZero() || !asOf.After(since) || window <= 0 ||
|
||||
maxAttempts < 1 || window%time.Second != 0 {
|
||||
return outbound.AssessmentRootQuotaSnapshot{}, fmt.Errorf("%s - candidate and quota window are invalid: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
seconds := window.Seconds()
|
||||
if math.IsInf(seconds, 0) || math.IsNaN(seconds) {
|
||||
return outbound.AssessmentRootQuotaSnapshot{}, fmt.Errorf("%s - quota window exceeds supported precision: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
row, err := repository.queries.GetAssessmentRootQuotaAvailability(ctx, sqlc.GetAssessmentRootQuotaAvailabilityParams{
|
||||
MaxAttempts: int64(maxAttempts), WindowSeconds: seconds, UserID: pgUUID(userID),
|
||||
Since: pgTime(since), AsOf: pgTime(asOf),
|
||||
})
|
||||
if err != nil {
|
||||
return outbound.AssessmentRootQuotaSnapshot{}, fmt.Errorf("%s - read root quota: %w", location, mapAssessmentAttemptError(err))
|
||||
}
|
||||
if row.AttemptCount < 0 || row.AttemptCount > math.MaxInt32 {
|
||||
return outbound.AssessmentRootQuotaSnapshot{}, fmt.Errorf("%s - root quota count is outside the supported range", location)
|
||||
}
|
||||
snapshot := outbound.AssessmentRootQuotaSnapshot{Count: int32(row.AttemptCount)}
|
||||
if row.AvailableAt.Valid {
|
||||
availableAt := row.AvailableAt.Time
|
||||
snapshot.AvailableAt = &availableAt
|
||||
}
|
||||
return snapshot, nil
|
||||
}
|
||||
|
||||
func (repository assessmentAttemptRepository) ListDisclosedFamilyKeys(
|
||||
ctx context.Context,
|
||||
userID uuid.UUID,
|
||||
since time.Time,
|
||||
) ([]domain.AssessmentFamilyKey, error) {
|
||||
const location = "assessmentAttemptRepository.ListDisclosedFamilyKeys"
|
||||
if userID == uuid.Nil || since.IsZero() {
|
||||
return nil, fmt.Errorf("%s - candidate and disclosure horizon are invalid: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
rows, err := repository.queries.ListAssessmentDisclosedFamilyKeys(ctx, sqlc.ListAssessmentDisclosedFamilyKeysParams{
|
||||
UserID: pgUUID(userID), Since: pgTime(since),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - read disclosed family keys: %w", location, mapAssessmentAttemptError(err))
|
||||
}
|
||||
keys := make([]domain.AssessmentFamilyKey, 0, len(rows))
|
||||
for _, storedKey := range rows {
|
||||
key, err := domain.ParseAssessmentFamilyKey(storedKey)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - stored family key is invalid: %w", location, err)
|
||||
}
|
||||
keys = append(keys, key)
|
||||
}
|
||||
return keys, nil
|
||||
}
|
||||
|
||||
func validAvailabilityAttemptState(state string) bool {
|
||||
switch domain.AssessmentAttemptState(state) {
|
||||
case domain.AssessmentAttemptStateInProgress, domain.AssessmentAttemptStatePracticePending,
|
||||
domain.AssessmentAttemptStateAdditionalPracticePending, domain.AssessmentAttemptStateReadyToFinalize,
|
||||
domain.AssessmentAttemptStateCompleted, domain.AssessmentAttemptStateExpired,
|
||||
domain.AssessmentAttemptStateInsufficientBank:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func validAvailabilityOutcome(outcome pgtype.Text) bool {
|
||||
if !outcome.Valid {
|
||||
return true
|
||||
}
|
||||
switch domain.AssessmentAttemptOutcome(outcome.String) {
|
||||
case domain.AssessmentAttemptOutcomeConfirmed, domain.AssessmentAttemptOutcomeNotConfirmed,
|
||||
domain.AssessmentAttemptOutcomeNotDetermined, domain.AssessmentAttemptOutcomeDemonstration:
|
||||
return domain.AssessmentAttemptOutcome(outcome.String) != domain.AssessmentAttemptOutcomeDemonstration
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
)
|
||||
|
||||
type assessmentAttemptResultDocument struct {
|
||||
SchemaVersion int32 `json:"schema_version"`
|
||||
Attempt assessmentAttemptPublicResultDocument `json:"attempt"`
|
||||
Pins assessmentAttemptResultPinsDocument `json:"pins"`
|
||||
Outcome domain.AssessmentAttemptOutcome `json:"outcome"`
|
||||
NotDeterminedReason string `json:"not_determined_reason,omitempty"`
|
||||
BasicScore *domain.AssessmentBasicScore `json:"basic_score,omitempty"`
|
||||
Rationale domain.AssessmentAttemptDecisionRationale `json:"rationale"`
|
||||
Limitations []string `json:"limitations"`
|
||||
Summary string `json:"summary,omitempty"`
|
||||
DecidedAt time.Time `json:"decided_at"`
|
||||
}
|
||||
|
||||
type assessmentAttemptPublicResultDocument struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Version int64 `json:"version"`
|
||||
Kind domain.AssessmentAttemptKind `json:"kind"`
|
||||
Mode domain.AssessmentAttemptMode `json:"mode"`
|
||||
State domain.AssessmentAttemptState `json:"state"`
|
||||
Specialization *domain.SpecializationCode `json:"specialization"`
|
||||
TargetGrade *domain.GradeCode `json:"target_grade"`
|
||||
TaskLanguage *domain.TaskLanguageCode `json:"task_language"`
|
||||
RootAttemptID *uuid.UUID `json:"root_attempt_id,omitempty"`
|
||||
ChainDeadline *time.Time `json:"chain_deadline,omitempty"`
|
||||
PolicyVersion int32 `json:"policy_version"`
|
||||
BankVersion string `json:"bank_version"`
|
||||
AlgorithmVersion string `json:"algorithm_version"`
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
FinishedAt *time.Time `json:"finished_at"`
|
||||
MaxItems int32 `json:"max_items"`
|
||||
AnsweredItems int32 `json:"answered_items"`
|
||||
SessionsUsed int32 `json:"sessions_used"`
|
||||
MaxSessions int32 `json:"max_sessions"`
|
||||
IdleTimeout int32 `json:"idle_timeout_seconds"`
|
||||
CurrentItem *domain.AssessmentAttemptPublicItem `json:"current_item"`
|
||||
Practices []domain.AssessmentAttemptPublicPractice `json:"practices"`
|
||||
}
|
||||
|
||||
type assessmentAttemptResultPinsDocument struct {
|
||||
ProductPolicyVersionID uuid.UUID `json:"product_policy_version_id"`
|
||||
ProductPolicyVersion int32 `json:"product_policy_version"`
|
||||
GradingPolicyVersionID *uuid.UUID `json:"grading_policy_version_id,omitempty"`
|
||||
OpeningID *uuid.UUID `json:"opening_id,omitempty"`
|
||||
OpeningManifestHash *string `json:"opening_manifest_sha256,omitempty"`
|
||||
TrainingBindingID *uuid.UUID `json:"training_binding_id,omitempty"`
|
||||
TrainingManifestHash *string `json:"training_manifest_sha256,omitempty"`
|
||||
BankVersion string `json:"bank_version"`
|
||||
AlgorithmVersion string `json:"algorithm_version"`
|
||||
}
|
||||
|
||||
func marshalAssessmentAttemptResultDocument(result domain.AssessmentAttemptResultSnapshot) ([]byte, error) {
|
||||
const location = "postgres.marshalAssessmentAttemptResultDocument"
|
||||
validated, err := domain.RestoreAssessmentAttemptResultSnapshot(result)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - validate result: %w", location, err)
|
||||
}
|
||||
document := assessmentAttemptResultDocumentFromSnapshot(validated)
|
||||
encoded, err := json.Marshal(document)
|
||||
if err != nil || len(encoded) > 65536 {
|
||||
return nil, fmt.Errorf("%s - encode bounded result: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
return encoded, nil
|
||||
}
|
||||
|
||||
func decodeAssessmentAttemptResultDocument(encoded []byte) (domain.AssessmentAttemptResultSnapshot, error) {
|
||||
const location = "postgres.decodeAssessmentAttemptResultDocument"
|
||||
if len(encoded) == 0 || len(encoded) > 65536 || !json.Valid(encoded) {
|
||||
return domain.AssessmentAttemptResultSnapshot{}, fmt.Errorf("%s - stored document is invalid: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewReader(encoded))
|
||||
decoder.DisallowUnknownFields()
|
||||
var document assessmentAttemptResultDocument
|
||||
if err := decoder.Decode(&document); err != nil {
|
||||
return domain.AssessmentAttemptResultSnapshot{}, fmt.Errorf("%s - decode stored document: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
var extra any
|
||||
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
|
||||
return domain.AssessmentAttemptResultSnapshot{}, fmt.Errorf("%s - stored document has trailing data: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
result, err := assessmentAttemptResultSnapshotFromDocument(document)
|
||||
if err != nil {
|
||||
return domain.AssessmentAttemptResultSnapshot{}, fmt.Errorf("%s - restore version pins: %w", location, err)
|
||||
}
|
||||
validated, err := domain.RestoreAssessmentAttemptResultSnapshot(result)
|
||||
if err != nil {
|
||||
return domain.AssessmentAttemptResultSnapshot{}, fmt.Errorf("%s - validate stored result: %w", location, err)
|
||||
}
|
||||
return validated, nil
|
||||
}
|
||||
|
||||
func assessmentAttemptResultDocumentFromSnapshot(
|
||||
result domain.AssessmentAttemptResultSnapshot,
|
||||
) assessmentAttemptResultDocument {
|
||||
attempt := result.Attempt
|
||||
documentAttempt := assessmentAttemptPublicResultDocument{
|
||||
ID: attempt.ID.UUID(), Version: attempt.Version, Kind: attempt.Kind, Mode: attempt.Mode,
|
||||
State: attempt.State, Specialization: attempt.Specialization, TargetGrade: attempt.TargetGrade,
|
||||
TaskLanguage: attempt.TaskLanguage, ChainDeadline: attempt.ChainDeadline,
|
||||
PolicyVersion: attempt.PolicyVersion, BankVersion: attempt.BankVersion,
|
||||
AlgorithmVersion: attempt.AlgorithmVersion, StartedAt: attempt.StartedAt,
|
||||
ExpiresAt: attempt.ExpiresAt, FinishedAt: attempt.FinishedAt,
|
||||
MaxItems: attempt.MaxItems, AnsweredItems: attempt.AnsweredItems,
|
||||
SessionsUsed: attempt.SessionsUsed, MaxSessions: attempt.MaxSessions,
|
||||
IdleTimeout: attempt.IdleTimeout, CurrentItem: attempt.CurrentItem, Practices: attempt.Practices,
|
||||
}
|
||||
if attempt.RootAttemptID != nil {
|
||||
rootID := attempt.RootAttemptID.UUID()
|
||||
documentAttempt.RootAttemptID = &rootID
|
||||
}
|
||||
pins := result.Pins
|
||||
gradingPolicyVersionID := optionalAssessmentPolicyVersionUUID(pins.GradingPolicyVersionID)
|
||||
openingID := optionalAssessmentUUID(pins.OpeningID)
|
||||
openingManifestHash := optionalAssessmentDigest(pins.OpeningManifestHash)
|
||||
trainingBindingID := optionalAssessmentUUID(pins.TrainingBindingID)
|
||||
trainingManifestHash := optionalAssessmentDigest(pins.TrainingManifestHash)
|
||||
return assessmentAttemptResultDocument{
|
||||
SchemaVersion: result.SchemaVersion, Attempt: documentAttempt,
|
||||
Pins: assessmentAttemptResultPinsDocument{
|
||||
ProductPolicyVersionID: uuid.UUID(pins.ProductPolicyVersionID), ProductPolicyVersion: pins.ProductPolicyVersion,
|
||||
GradingPolicyVersionID: gradingPolicyVersionID, OpeningID: openingID,
|
||||
OpeningManifestHash: openingManifestHash, TrainingBindingID: trainingBindingID,
|
||||
TrainingManifestHash: trainingManifestHash, BankVersion: pins.BankVersion,
|
||||
AlgorithmVersion: pins.AlgorithmVersion,
|
||||
},
|
||||
Outcome: result.Outcome, NotDeterminedReason: result.NotDeterminedReason,
|
||||
BasicScore: result.BasicScore, Rationale: result.Rationale,
|
||||
Limitations: result.Limitations, Summary: result.Summary, DecidedAt: result.DecidedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func assessmentAttemptResultSnapshotFromDocument(
|
||||
document assessmentAttemptResultDocument,
|
||||
) (domain.AssessmentAttemptResultSnapshot, error) {
|
||||
attempt := document.Attempt
|
||||
snapshotAttempt := domain.AssessmentAttemptPublicSnapshot{
|
||||
ID: domain.AssessmentAttemptID(attempt.ID), Version: attempt.Version, Kind: attempt.Kind,
|
||||
Mode: attempt.Mode, State: attempt.State, Specialization: attempt.Specialization,
|
||||
TargetGrade: attempt.TargetGrade, TaskLanguage: attempt.TaskLanguage,
|
||||
ChainDeadline: attempt.ChainDeadline, PolicyVersion: attempt.PolicyVersion,
|
||||
BankVersion: attempt.BankVersion, AlgorithmVersion: attempt.AlgorithmVersion,
|
||||
StartedAt: attempt.StartedAt, ExpiresAt: attempt.ExpiresAt, FinishedAt: attempt.FinishedAt,
|
||||
MaxItems: attempt.MaxItems, AnsweredItems: attempt.AnsweredItems,
|
||||
SessionsUsed: attempt.SessionsUsed, MaxSessions: attempt.MaxSessions,
|
||||
IdleTimeout: attempt.IdleTimeout, CurrentItem: attempt.CurrentItem, Practices: attempt.Practices,
|
||||
}
|
||||
if attempt.RootAttemptID != nil {
|
||||
rootID := domain.AssessmentAttemptID(*attempt.RootAttemptID)
|
||||
snapshotAttempt.RootAttemptID = &rootID
|
||||
}
|
||||
pins := document.Pins
|
||||
openingManifestHash, err := restoreOptionalAssessmentDigest(pins.OpeningManifestHash)
|
||||
if err != nil {
|
||||
return domain.AssessmentAttemptResultSnapshot{}, err
|
||||
}
|
||||
trainingManifestHash, err := restoreOptionalAssessmentDigest(pins.TrainingManifestHash)
|
||||
if err != nil {
|
||||
return domain.AssessmentAttemptResultSnapshot{}, err
|
||||
}
|
||||
return domain.AssessmentAttemptResultSnapshot{
|
||||
SchemaVersion: document.SchemaVersion, Attempt: snapshotAttempt,
|
||||
Pins: domain.AssessmentAttemptResultPins{
|
||||
ProductPolicyVersionID: domain.PolicyVersionID(pins.ProductPolicyVersionID),
|
||||
ProductPolicyVersion: pins.ProductPolicyVersion,
|
||||
GradingPolicyVersionID: assessmentPolicyVersionIDFromOptionalUUID(pins.GradingPolicyVersionID),
|
||||
OpeningID: assessmentUUIDFromOptional(pins.OpeningID), OpeningManifestHash: openingManifestHash,
|
||||
TrainingBindingID: assessmentUUIDFromOptional(pins.TrainingBindingID), TrainingManifestHash: trainingManifestHash,
|
||||
BankVersion: pins.BankVersion, AlgorithmVersion: pins.AlgorithmVersion,
|
||||
},
|
||||
Outcome: document.Outcome, NotDeterminedReason: document.NotDeterminedReason,
|
||||
BasicScore: document.BasicScore, Rationale: document.Rationale,
|
||||
Limitations: document.Limitations, Summary: document.Summary, DecidedAt: document.DecidedAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func optionalAssessmentPolicyVersionUUID(value domain.PolicyVersionID) *uuid.UUID {
|
||||
if value == domain.PolicyVersionID(uuid.Nil) {
|
||||
return nil
|
||||
}
|
||||
id := uuid.UUID(value)
|
||||
return &id
|
||||
}
|
||||
|
||||
func optionalAssessmentUUID(value uuid.UUID) *uuid.UUID {
|
||||
if value == uuid.Nil {
|
||||
return nil
|
||||
}
|
||||
return &value
|
||||
}
|
||||
|
||||
func optionalAssessmentDigest(value [sha256.Size]byte) *string {
|
||||
if value == [sha256.Size]byte{} {
|
||||
return nil
|
||||
}
|
||||
digest := hex.EncodeToString(value[:])
|
||||
return &digest
|
||||
}
|
||||
|
||||
func assessmentPolicyVersionIDFromOptionalUUID(value *uuid.UUID) domain.PolicyVersionID {
|
||||
if value == nil {
|
||||
return domain.PolicyVersionID(uuid.Nil)
|
||||
}
|
||||
return domain.PolicyVersionID(*value)
|
||||
}
|
||||
|
||||
func assessmentUUIDFromOptional(value *uuid.UUID) uuid.UUID {
|
||||
if value == nil {
|
||||
return uuid.Nil
|
||||
}
|
||||
return *value
|
||||
}
|
||||
|
||||
func restoreOptionalAssessmentDigest(value *string) ([sha256.Size]byte, error) {
|
||||
if value == nil {
|
||||
return [sha256.Size]byte{}, nil
|
||||
}
|
||||
digest, err := hex.DecodeString(*value)
|
||||
if err != nil || len(digest) != sha256.Size || hex.EncodeToString(digest) != *value {
|
||||
return [sha256.Size]byte{}, domain.ErrInvalidAssessmentAttempt
|
||||
}
|
||||
var restored [sha256.Size]byte
|
||||
copy(restored[:], digest)
|
||||
return restored, nil
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
)
|
||||
|
||||
func TestAssessmentAttemptResultDocumentUsesNullableUUIDPins(t *testing.T) {
|
||||
attemptID := uuid.New()
|
||||
productPolicyID := uuid.New()
|
||||
gradingPolicyID := uuid.New()
|
||||
openingID := uuid.New()
|
||||
trainingBindingID := uuid.New()
|
||||
openingHash := [32]byte{1, 2, 3}
|
||||
trainingHash := [32]byte{4, 5, 6}
|
||||
tests := []struct {
|
||||
name string
|
||||
pins domain.AssessmentAttemptResultPins
|
||||
presentPinFields []string
|
||||
absentPinFields []string
|
||||
}{
|
||||
{
|
||||
name: "real assessment",
|
||||
pins: domain.AssessmentAttemptResultPins{
|
||||
ProductPolicyVersionID: domain.PolicyVersionID(productPolicyID), ProductPolicyVersion: 2,
|
||||
GradingPolicyVersionID: domain.PolicyVersionID(gradingPolicyID), OpeningID: openingID,
|
||||
OpeningManifestHash: openingHash, BankVersion: "bank.v1", AlgorithmVersion: "demo_basic.v1",
|
||||
},
|
||||
presentPinFields: []string{productPolicyID.String(), gradingPolicyID.String(), openingID.String(), hex.EncodeToString(openingHash[:])},
|
||||
absentPinFields: []string{trainingBindingID.String(), "00000000-0000-0000-0000-000000000000"},
|
||||
},
|
||||
{
|
||||
name: "express training",
|
||||
pins: domain.AssessmentAttemptResultPins{
|
||||
ProductPolicyVersionID: domain.PolicyVersionID(productPolicyID), ProductPolicyVersion: 2,
|
||||
TrainingBindingID: trainingBindingID, TrainingManifestHash: trainingHash,
|
||||
BankVersion: "bank.v1", AlgorithmVersion: "demo_express.v1",
|
||||
},
|
||||
presentPinFields: []string{productPolicyID.String(), trainingBindingID.String(), hex.EncodeToString(trainingHash[:])},
|
||||
absentPinFields: []string{gradingPolicyID.String(), openingID.String(), "00000000-0000-0000-0000-000000000000"},
|
||||
},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
document := assessmentAttemptResultDocumentFromSnapshot(domain.AssessmentAttemptResultSnapshot{
|
||||
Attempt: domain.AssessmentAttemptPublicSnapshot{ID: domain.AssessmentAttemptID(attemptID)},
|
||||
Pins: test.pins,
|
||||
})
|
||||
encoded, err := json.Marshal(document)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal result document: %v", err)
|
||||
}
|
||||
var decoded map[string]any
|
||||
if err := json.Unmarshal(encoded, &decoded); err != nil {
|
||||
t.Fatalf("decode result document: %v", err)
|
||||
}
|
||||
pins, ok := decoded["pins"].(map[string]any)
|
||||
if !ok || pins["product_policy_version_id"] != productPolicyID.String() {
|
||||
t.Fatalf("result pins = %#v, want UUID string for product policy", decoded["pins"])
|
||||
}
|
||||
for _, value := range test.presentPinFields {
|
||||
if !strings.Contains(string(encoded), `"`+value+`"`) {
|
||||
t.Errorf("encoded result does not contain string pin %q: %s", value, encoded)
|
||||
}
|
||||
}
|
||||
for _, value := range test.absentPinFields {
|
||||
if strings.Contains(string(encoded), value) {
|
||||
t.Errorf("encoded result contains unrelated or zero pin %q: %s", value, encoded)
|
||||
}
|
||||
}
|
||||
restored, err := assessmentAttemptResultSnapshotFromDocument(document)
|
||||
if err != nil || restored.Pins != test.pins {
|
||||
t.Fatalf("restore result pins = %+v, error %v, want %+v", restored.Pins, err, test.pins)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRestoreAssessmentAttemptResultDocumentRejectsNoncanonicalPinHash(t *testing.T) {
|
||||
productPolicyID := uuid.New()
|
||||
openingID := uuid.New()
|
||||
wrongHash := "01"
|
||||
document := assessmentAttemptResultDocument{
|
||||
Pins: assessmentAttemptResultPinsDocument{
|
||||
ProductPolicyVersionID: productPolicyID,
|
||||
OpeningID: &openingID,
|
||||
OpeningManifestHash: &wrongHash,
|
||||
},
|
||||
}
|
||||
if _, err := assessmentAttemptResultSnapshotFromDocument(document); err == nil {
|
||||
t.Fatal("assessmentAttemptResultSnapshotFromDocument() accepted an invalid pin hash")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
func (repository assessmentBankRepository) ListCurrentAssessmentAvailabilitySelections(
|
||||
ctx context.Context,
|
||||
asOf time.Time,
|
||||
) ([]outbound.AssessmentAvailabilitySelection, error) {
|
||||
const location = "assessmentBankRepository.ListCurrentAssessmentAvailabilitySelections"
|
||||
if asOf.IsZero() {
|
||||
return nil, fmt.Errorf("%s - database time is required: %w", location, domain.ErrInvalidAssessmentFamily)
|
||||
}
|
||||
rows, err := repository.queries.ListCurrentAssessmentAvailabilitySelections(ctx, pgTime(asOf))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - select current bindings: %w", location, mapAssessmentError(err))
|
||||
}
|
||||
selections := make([]outbound.AssessmentAvailabilitySelection, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
metadataRow := sqlc.ListCurrentSpecializationAvailabilityRow{
|
||||
OpeningID: row.OpeningID, Category: row.Category, PolicyVersionID: row.PolicyVersionID,
|
||||
RequiredFamilies: row.RequiredFamilies, PublishedCount: row.PublishedCount,
|
||||
EffectivePolicyID: row.EffectivePolicyID, Specialization: row.Specialization,
|
||||
Grade: row.Grade, TaskLanguages: row.TaskLanguages,
|
||||
PublishedManifestSha256: row.PublishedManifestSha256, PublishedManifest: row.PublishedManifest,
|
||||
}
|
||||
metadata, current, err := currentAssessmentCatalogMetadata(metadataRow)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - validate reviewed binding: %w", location, err)
|
||||
}
|
||||
if !current {
|
||||
continue
|
||||
}
|
||||
if !row.OpeningID.Valid || row.OpeningID.Bytes == [16]byte{} ||
|
||||
!row.EffectivePolicyVersion.Valid || row.EffectivePolicyVersion.Int32 < 1 {
|
||||
return nil, fmt.Errorf("%s - current binding identity is invalid: %w", location, domain.ErrInvalidAssessmentFamily)
|
||||
}
|
||||
manifest, err := decodeAssessmentCategoryManifest(row.PublishedManifest)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - decode verified family manifest: %w", location, err)
|
||||
}
|
||||
familyKeys := make([]domain.AssessmentFamilyKey, 0, len(manifest))
|
||||
for _, entry := range manifest {
|
||||
familyKeys = append(familyKeys, entry.FamilyKey)
|
||||
}
|
||||
selections = append(selections, outbound.AssessmentAvailabilitySelection{
|
||||
OpeningID: row.OpeningID.Bytes, Category: domain.AssessmentCategory(row.Category),
|
||||
ProductPolicyVersionID: domain.PolicyVersionID(row.EffectivePolicyID.Bytes),
|
||||
ProductPolicyVersion: row.EffectivePolicyVersion.Int32,
|
||||
Specialization: metadata.Specialization(), Grade: metadata.Grade(),
|
||||
TaskLanguages: metadata.TaskLanguages(), FamilyKeys: familyKeys,
|
||||
})
|
||||
}
|
||||
return selections, nil
|
||||
}
|
||||
@@ -43,6 +43,19 @@ func TestMapAssessmentErrorRecognizesBankConstraints(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestPinnedFamilyLookupMapsOnlyMissingFamiliesToUnavailable(t *testing.T) {
|
||||
missing := mapPinnedFamilyLookupError(errors.Join(errors.New("select pinned family"), outbound.ErrAssessmentFamilyNotFound))
|
||||
if !errors.Is(missing, outbound.ErrAssessmentSelectionUnavailable) {
|
||||
t.Fatalf("map missing pinned family error = %v, want ErrAssessmentSelectionUnavailable", missing)
|
||||
}
|
||||
|
||||
transient := errors.New("database connection reset")
|
||||
got := mapPinnedFamilyLookupError(transient)
|
||||
if !errors.Is(got, transient) || errors.Is(got, outbound.ErrAssessmentSelectionUnavailable) {
|
||||
t.Fatalf("map transient pinned family error = %v, want original infrastructure error", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLockCategoryWorksOnlyInsideATransaction(t *testing.T) {
|
||||
// A repository without queries proves that no statement runs.
|
||||
standalone := assessmentBankRepository{transactional: false}
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/domain"
|
||||
@@ -94,6 +95,419 @@ func (repository assessmentBankRepository) ListCurrentSpecializationAvailability
|
||||
return buildAssessmentCatalogAvailability(aggregates), nil
|
||||
}
|
||||
|
||||
func (repository assessmentBankRepository) ResolveCurrentSelection(
|
||||
ctx context.Context,
|
||||
specialization domain.SpecializationCode,
|
||||
grade domain.GradeCode,
|
||||
language *domain.TaskLanguageCode,
|
||||
) (outbound.AssessmentBankSelection, error) {
|
||||
const location = "assessmentBankRepository.ResolveCurrentSelection"
|
||||
if !repository.transactional {
|
||||
return outbound.AssessmentBankSelection{}, fmt.Errorf("%s - current selection needs a transaction: %w", location, outbound.ErrAssessmentLockOutsideTransaction)
|
||||
}
|
||||
initial, err := repository.currentSelectionRows(ctx, specialization, grade, language)
|
||||
if err != nil {
|
||||
return outbound.AssessmentBankSelection{}, fmt.Errorf("%s - read candidate selection: %w", location, err)
|
||||
}
|
||||
if len(initial) == 0 {
|
||||
return outbound.AssessmentBankSelection{}, fmt.Errorf("%s - no current reviewed selection: %w", location, outbound.ErrAssessmentSelectionUnavailable)
|
||||
}
|
||||
if len(initial) > 1 {
|
||||
return outbound.AssessmentBankSelection{}, fmt.Errorf("%s - multiple current reviewed selections: %w", location, outbound.ErrAssessmentSelectionAmbiguous)
|
||||
}
|
||||
category := domain.AssessmentCategory(initial[0].Category)
|
||||
if err := repository.LockCategory(ctx, category); err != nil {
|
||||
return outbound.AssessmentBankSelection{}, fmt.Errorf("%s - lock selected category: %w", location, err)
|
||||
}
|
||||
current, err := repository.currentSelectionRows(ctx, specialization, grade, language)
|
||||
if err != nil {
|
||||
return outbound.AssessmentBankSelection{}, fmt.Errorf("%s - recheck candidate selection: %w", location, err)
|
||||
}
|
||||
if len(current) == 0 || len(current) > 1 || current[0].Category != string(category) ||
|
||||
current[0].OpeningID.Bytes != initial[0].OpeningID.Bytes {
|
||||
return outbound.AssessmentBankSelection{}, fmt.Errorf("%s - selection changed while locking: %w", location, outbound.ErrAssessmentSelectionUnavailable)
|
||||
}
|
||||
return repository.currentSelectionFromRow(ctx, current[0])
|
||||
}
|
||||
|
||||
func (repository assessmentBankRepository) currentSelectionRows(
|
||||
ctx context.Context,
|
||||
specialization domain.SpecializationCode,
|
||||
grade domain.GradeCode,
|
||||
language *domain.TaskLanguageCode,
|
||||
) ([]sqlc.ResolveCurrentAssessmentSelectionRow, error) {
|
||||
var selectedLanguage pgtype.Text
|
||||
if language != nil {
|
||||
selectedLanguage = pgText(string(*language))
|
||||
}
|
||||
rows, err := repository.queries.ResolveCurrentAssessmentSelection(ctx, sqlc.ResolveCurrentAssessmentSelectionParams{
|
||||
Specialization: string(specialization), Grade: string(grade), TaskLanguage: selectedLanguage,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, mapAssessmentError(err)
|
||||
}
|
||||
current := make([]sqlc.ResolveCurrentAssessmentSelectionRow, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
metadata, available, err := currentAssessmentSelectionMetadata(row)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("validate current catalog binding: %w", err)
|
||||
}
|
||||
if !available || metadata.Specialization() != specialization || metadata.Grade() != grade ||
|
||||
!assessmentCatalogLanguageMatches(metadata.TaskLanguages(), language) {
|
||||
continue
|
||||
}
|
||||
current = append(current, row)
|
||||
}
|
||||
return current, nil
|
||||
}
|
||||
|
||||
func currentAssessmentSelectionMetadata(
|
||||
row sqlc.ResolveCurrentAssessmentSelectionRow,
|
||||
) (domain.AssessmentCategoryCatalogMetadata, bool, error) {
|
||||
return currentAssessmentCatalogMetadata(sqlc.ListCurrentSpecializationAvailabilityRow{
|
||||
OpeningID: row.OpeningID, Category: row.Category, PolicyVersionID: row.PolicyVersionID,
|
||||
RequiredFamilies: row.RequiredFamilies, PublishedCount: row.PublishedCount,
|
||||
EffectivePolicyID: row.EffectivePolicyID, Specialization: row.Specialization,
|
||||
Grade: row.Grade, TaskLanguages: row.TaskLanguages,
|
||||
PublishedManifestSha256: row.PublishedManifestSha256, PublishedManifest: row.PublishedManifest,
|
||||
})
|
||||
}
|
||||
|
||||
func assessmentCatalogLanguageMatches(
|
||||
available []domain.TaskLanguageCode,
|
||||
requested *domain.TaskLanguageCode,
|
||||
) bool {
|
||||
if requested == nil {
|
||||
return len(available) == 0
|
||||
}
|
||||
return slices.Contains(available, *requested)
|
||||
}
|
||||
|
||||
func (repository assessmentBankRepository) currentSelectionFromRow(
|
||||
ctx context.Context,
|
||||
row sqlc.ResolveCurrentAssessmentSelectionRow,
|
||||
) (outbound.AssessmentBankSelection, error) {
|
||||
const location = "assessmentBankRepository.currentSelectionFromRow"
|
||||
if !row.EffectivePolicyID.Valid || !row.EffectivePolicyVersion.Valid || row.EffectivePolicyVersion.Int32 < 1 {
|
||||
return outbound.AssessmentBankSelection{}, outbound.ErrAssessmentSelectionUnavailable
|
||||
}
|
||||
opening, err := repository.selectionOpening(ctx, row)
|
||||
if err != nil {
|
||||
return outbound.AssessmentBankSelection{}, fmt.Errorf("%s - validate current opening: %w", location, err)
|
||||
}
|
||||
entries, manifestSHA, err := currentSelectionManifest(row)
|
||||
if err != nil {
|
||||
return outbound.AssessmentBankSelection{}, fmt.Errorf("%s - validate current manifest: %w", location, err)
|
||||
}
|
||||
families, err := repository.resolveCurrentSelectionFamilies(ctx, opening.Category, entries)
|
||||
if err != nil {
|
||||
return outbound.AssessmentBankSelection{}, fmt.Errorf("%s - resolve pinned families: %w", location, err)
|
||||
}
|
||||
return outbound.AssessmentBankSelection{
|
||||
Opening: opening, ProductPolicyVersionID: domain.PolicyVersionID(row.EffectivePolicyID.Bytes),
|
||||
ProductPolicyVersion: row.EffectivePolicyVersion.Int32, ManifestSHA: manifestSHA, Families: families,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (repository assessmentBankRepository) selectionOpening(
|
||||
ctx context.Context,
|
||||
row sqlc.ResolveCurrentAssessmentSelectionRow,
|
||||
) (domain.AssessmentCategoryOpening, error) {
|
||||
opening, err := repository.GetCurrentCategoryOpening(ctx, domain.AssessmentCategory(row.Category))
|
||||
if err != nil {
|
||||
return domain.AssessmentCategoryOpening{}, err
|
||||
}
|
||||
if opening.ID != row.OpeningID.Bytes || opening.PolicyVersionID != domain.PolicyVersionID(row.PolicyVersionID.Bytes) ||
|
||||
opening.RequiredFamilies != row.RequiredFamilies || row.PublishedCount < row.RequiredFamilies {
|
||||
return domain.AssessmentCategoryOpening{}, outbound.ErrAssessmentSelectionUnavailable
|
||||
}
|
||||
return opening, nil
|
||||
}
|
||||
|
||||
func currentSelectionManifest(
|
||||
row sqlc.ResolveCurrentAssessmentSelectionRow,
|
||||
) ([]domain.AssessmentCategoryManifestEntry, [sha256.Size]byte, error) {
|
||||
entries, err := decodeAssessmentCategoryManifest(row.PublishedManifest)
|
||||
if err != nil {
|
||||
return nil, [sha256.Size]byte{}, outbound.ErrAssessmentSelectionUnavailable
|
||||
}
|
||||
fingerprint, err := assessmentCategoryManifestFingerprint(entries)
|
||||
if err != nil || len(entries) != int(row.PublishedCount) || !slices.Equal(fingerprint[:], row.PublishedManifestSha256) {
|
||||
return nil, [sha256.Size]byte{}, outbound.ErrAssessmentSelectionUnavailable
|
||||
}
|
||||
return entries, fingerprint, nil
|
||||
}
|
||||
|
||||
func (repository assessmentBankRepository) resolveCurrentSelectionFamilies(
|
||||
ctx context.Context,
|
||||
category domain.AssessmentCategory,
|
||||
entries []domain.AssessmentCategoryManifestEntry,
|
||||
) ([]domain.AssessmentFamily, error) {
|
||||
families := make([]domain.AssessmentFamily, 0, len(entries))
|
||||
for _, entry := range entries {
|
||||
family, err := repository.GetFamilyVersion(ctx, entry.FamilyKey, entry.Version)
|
||||
if err != nil {
|
||||
return nil, mapPinnedFamilyLookupError(err)
|
||||
}
|
||||
hash := family.ContentHash()
|
||||
if family.Category() != category || family.Lifecycle() != domain.AssessmentLifecyclePublished ||
|
||||
family.ReviewStatus() != domain.AssessmentReviewApproved || !slices.Equal(hash[:], entry.ContentSHA256) {
|
||||
return nil, outbound.ErrAssessmentSelectionUnavailable
|
||||
}
|
||||
families = append(families, family)
|
||||
}
|
||||
return families, nil
|
||||
}
|
||||
|
||||
func mapPinnedFamilyLookupError(err error) error {
|
||||
if errors.Is(err, outbound.ErrAssessmentFamilyNotFound) {
|
||||
return outbound.ErrAssessmentSelectionUnavailable
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (repository assessmentBankRepository) ResolveCurrentTrainingSelection(
|
||||
ctx context.Context,
|
||||
productPolicyID domain.PolicyVersionID,
|
||||
productPolicyVersion int32,
|
||||
) (outbound.AssessmentTrainingBankSelection, error) {
|
||||
const location = "assessmentBankRepository.ResolveCurrentTrainingSelection"
|
||||
if !repository.transactional {
|
||||
return outbound.AssessmentTrainingBankSelection{}, fmt.Errorf("%s - training selection needs a transaction: %w", location, outbound.ErrAssessmentLockOutsideTransaction)
|
||||
}
|
||||
initial, err := repository.queries.ListCurrentAssessmentTrainingBindings(ctx)
|
||||
if err != nil {
|
||||
return outbound.AssessmentTrainingBankSelection{}, fmt.Errorf("%s - read current bindings: %w", location, mapAssessmentError(err))
|
||||
}
|
||||
locked, err := repository.lockCurrentTrainingCategories(ctx, initial, productPolicyID, productPolicyVersion)
|
||||
if err != nil {
|
||||
return outbound.AssessmentTrainingBankSelection{}, fmt.Errorf("%s - lock training categories: %w", location, err)
|
||||
}
|
||||
current, err := repository.queries.ListCurrentAssessmentTrainingBindings(ctx)
|
||||
if err != nil {
|
||||
return outbound.AssessmentTrainingBankSelection{}, fmt.Errorf("%s - recheck current bindings: %w", location, mapAssessmentError(err))
|
||||
}
|
||||
selections, err := repository.currentTrainingSelections(ctx, current, locked, productPolicyID, productPolicyVersion)
|
||||
if err != nil {
|
||||
return outbound.AssessmentTrainingBankSelection{}, fmt.Errorf("%s - validate current bindings: %w", location, err)
|
||||
}
|
||||
if len(selections) == 0 {
|
||||
return outbound.AssessmentTrainingBankSelection{}, fmt.Errorf("%s - no current reviewed training binding: %w", location, outbound.ErrAssessmentSelectionUnavailable)
|
||||
}
|
||||
if len(selections) > 1 {
|
||||
return outbound.AssessmentTrainingBankSelection{}, fmt.Errorf("%s - multiple current reviewed training bindings: %w", location, outbound.ErrAssessmentSelectionAmbiguous)
|
||||
}
|
||||
return selections[0], nil
|
||||
}
|
||||
|
||||
func (repository assessmentBankRepository) lockCurrentTrainingCategories(
|
||||
ctx context.Context,
|
||||
rows []sqlc.ListCurrentAssessmentTrainingBindingsRow,
|
||||
productPolicyID domain.PolicyVersionID,
|
||||
productPolicyVersion int32,
|
||||
) (map[domain.AssessmentCategory]struct{}, error) {
|
||||
locked := make(map[domain.AssessmentCategory]struct{})
|
||||
for _, row := range rows {
|
||||
if !matchesProductPolicy(row.ProductPolicyVersionID, row.ProductPolicyVersion, productPolicyID, productPolicyVersion) {
|
||||
continue
|
||||
}
|
||||
category := domain.AssessmentCategory(row.Category)
|
||||
if _, exists := locked[category]; exists {
|
||||
continue
|
||||
}
|
||||
if err := repository.LockCategory(ctx, category); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
locked[category] = struct{}{}
|
||||
}
|
||||
return locked, nil
|
||||
}
|
||||
|
||||
func (repository assessmentBankRepository) currentTrainingSelections(
|
||||
ctx context.Context,
|
||||
rows []sqlc.ListCurrentAssessmentTrainingBindingsRow,
|
||||
locked map[domain.AssessmentCategory]struct{},
|
||||
productPolicyID domain.PolicyVersionID,
|
||||
productPolicyVersion int32,
|
||||
) ([]outbound.AssessmentTrainingBankSelection, error) {
|
||||
selections := make([]outbound.AssessmentTrainingBankSelection, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
if !matchesProductPolicy(row.ProductPolicyVersionID, row.ProductPolicyVersion, productPolicyID, productPolicyVersion) {
|
||||
continue
|
||||
}
|
||||
category := domain.AssessmentCategory(row.Category)
|
||||
if _, ok := locked[category]; !ok {
|
||||
return nil, outbound.ErrAssessmentSelectionUnavailable
|
||||
}
|
||||
selection, err := repository.currentTrainingSelectionFromRow(ctx, row)
|
||||
if errors.Is(err, outbound.ErrAssessmentSelectionUnavailable) {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
selections = append(selections, selection)
|
||||
}
|
||||
return selections, nil
|
||||
}
|
||||
|
||||
func matchesProductPolicy(
|
||||
rowID pgtype.UUID,
|
||||
rowVersion int32,
|
||||
policyID domain.PolicyVersionID,
|
||||
policyVersion int32,
|
||||
) bool {
|
||||
return rowID.Bytes == uuid.UUID(policyID) && rowVersion == policyVersion
|
||||
}
|
||||
|
||||
func (repository assessmentBankRepository) currentTrainingSelectionFromRow(
|
||||
ctx context.Context,
|
||||
row sqlc.ListCurrentAssessmentTrainingBindingsRow,
|
||||
) (outbound.AssessmentTrainingBankSelection, error) {
|
||||
const location = "assessmentBankRepository.currentTrainingSelectionFromRow"
|
||||
category := domain.AssessmentCategory(row.Category)
|
||||
entries, manifestSHA, err := repository.validateCurrentTrainingManifest(ctx, category, row)
|
||||
if err != nil {
|
||||
return outbound.AssessmentTrainingBankSelection{}, fmt.Errorf("%s - validate current manifest: %w", location, err)
|
||||
}
|
||||
members, err := repository.queries.ListAssessmentTrainingBindingFamilies(ctx, pgUUID(row.ID.Bytes))
|
||||
if err != nil {
|
||||
return outbound.AssessmentTrainingBankSelection{}, fmt.Errorf("%s - read pinned training families: %w", location, mapAssessmentError(err))
|
||||
}
|
||||
families, err := repository.resolveCurrentTrainingFamilies(ctx, category, entries, members)
|
||||
if err != nil {
|
||||
return outbound.AssessmentTrainingBankSelection{}, fmt.Errorf("%s - resolve pinned families: %w", location, err)
|
||||
}
|
||||
return outbound.AssessmentTrainingBankSelection{
|
||||
BindingID: row.ID.Bytes, Category: category,
|
||||
ProductPolicyVersionID: domain.PolicyVersionID(row.ProductPolicyVersionID.Bytes),
|
||||
ProductPolicyVersion: row.ProductPolicyVersion, ManifestSHA: manifestSHA, Families: families,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (repository assessmentBankRepository) validateCurrentTrainingManifest(
|
||||
ctx context.Context,
|
||||
category domain.AssessmentCategory,
|
||||
row sqlc.ListCurrentAssessmentTrainingBindingsRow,
|
||||
) ([]domain.AssessmentCategoryManifestEntry, [sha256.Size]byte, error) {
|
||||
entries, err := decodeAssessmentCategoryManifest(string(row.FamilyManifest))
|
||||
if err != nil || len(entries) != int(row.ItemCount) {
|
||||
return nil, [sha256.Size]byte{}, outbound.ErrAssessmentSelectionUnavailable
|
||||
}
|
||||
manifestSHA, err := assessmentCategoryManifestFingerprint(entries)
|
||||
if err != nil || !slices.Equal(manifestSHA[:], row.ManifestSha256) {
|
||||
return nil, [sha256.Size]byte{}, outbound.ErrAssessmentSelectionUnavailable
|
||||
}
|
||||
liveEntries, err := repository.currentPublishedManifestEntries(ctx, category)
|
||||
if err != nil {
|
||||
return nil, [sha256.Size]byte{}, err
|
||||
}
|
||||
liveHash, err := assessmentCategoryManifestFingerprint(liveEntries)
|
||||
if err != nil || !assessmentManifestEntriesEqual(entries, liveEntries) || !slices.Equal(liveHash[:], row.ManifestSha256) {
|
||||
return nil, [sha256.Size]byte{}, outbound.ErrAssessmentSelectionUnavailable
|
||||
}
|
||||
return entries, manifestSHA, nil
|
||||
}
|
||||
|
||||
func (repository assessmentBankRepository) currentPublishedManifestEntries(
|
||||
ctx context.Context,
|
||||
category domain.AssessmentCategory,
|
||||
) ([]domain.AssessmentCategoryManifestEntry, error) {
|
||||
rows, err := repository.queries.ReadPublishedAssessmentCategoryManifest(ctx, string(category))
|
||||
if err != nil {
|
||||
return nil, mapAssessmentError(err)
|
||||
}
|
||||
entries := make([]domain.AssessmentCategoryManifestEntry, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
key, parseErr := domain.ParseAssessmentFamilyKey(row.FamilyKey)
|
||||
if parseErr != nil || row.Version < 1 || len(row.ContentSha256) != sha256.Size {
|
||||
return nil, domain.ErrInvalidAssessmentFamily
|
||||
}
|
||||
entries = append(entries, domain.AssessmentCategoryManifestEntry{
|
||||
FamilyKey: key, Version: row.Version, ContentSHA256: slices.Clone(row.ContentSha256),
|
||||
})
|
||||
}
|
||||
return entries, nil
|
||||
}
|
||||
|
||||
func (repository assessmentBankRepository) resolveCurrentTrainingFamilies(
|
||||
ctx context.Context,
|
||||
category domain.AssessmentCategory,
|
||||
entries []domain.AssessmentCategoryManifestEntry,
|
||||
members []sqlc.ListAssessmentTrainingBindingFamiliesRow,
|
||||
) ([]domain.AssessmentFamily, error) {
|
||||
if len(members) != len(entries) {
|
||||
return nil, outbound.ErrAssessmentSelectionUnavailable
|
||||
}
|
||||
sort.Slice(entries, func(i, j int) bool {
|
||||
if entries[i].FamilyKey == entries[j].FamilyKey {
|
||||
return entries[i].Version < entries[j].Version
|
||||
}
|
||||
return entries[i].FamilyKey < entries[j].FamilyKey
|
||||
})
|
||||
families := make([]domain.AssessmentFamily, 0, len(entries))
|
||||
for index, entry := range entries {
|
||||
family, err := repository.resolveTrainingFamily(ctx, category, entry, members[index], index)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
families = append(families, family)
|
||||
}
|
||||
return families, nil
|
||||
}
|
||||
|
||||
func (repository assessmentBankRepository) resolveTrainingFamily(
|
||||
ctx context.Context,
|
||||
category domain.AssessmentCategory,
|
||||
entry domain.AssessmentCategoryManifestEntry,
|
||||
member sqlc.ListAssessmentTrainingBindingFamiliesRow,
|
||||
index int,
|
||||
) (domain.AssessmentFamily, error) {
|
||||
if member.Ordinal < 1 || int64(member.Ordinal) != int64(index)+1 || member.FamilyKey != string(entry.FamilyKey) ||
|
||||
member.FamilyVersion != entry.Version || !slices.Equal(member.ContentSha256, entry.ContentSHA256) {
|
||||
return domain.AssessmentFamily{}, outbound.ErrAssessmentSelectionUnavailable
|
||||
}
|
||||
family, err := repository.GetFamilyVersion(ctx, entry.FamilyKey, entry.Version)
|
||||
if err != nil {
|
||||
return domain.AssessmentFamily{}, mapPinnedFamilyLookupError(err)
|
||||
}
|
||||
hash := family.ContentHash()
|
||||
if family.ID().UUID() != member.FamilyID.Bytes || family.Category() != category ||
|
||||
family.Lifecycle() != domain.AssessmentLifecyclePublished || family.ReviewStatus() != domain.AssessmentReviewApproved ||
|
||||
!slices.Equal(hash[:], entry.ContentSHA256) {
|
||||
return domain.AssessmentFamily{}, outbound.ErrAssessmentSelectionUnavailable
|
||||
}
|
||||
return family, nil
|
||||
}
|
||||
|
||||
func assessmentManifestEntriesEqual(
|
||||
left []domain.AssessmentCategoryManifestEntry,
|
||||
right []domain.AssessmentCategoryManifestEntry,
|
||||
) bool {
|
||||
if len(left) != len(right) {
|
||||
return false
|
||||
}
|
||||
canonical := func(entries []domain.AssessmentCategoryManifestEntry) []domain.AssessmentCategoryManifestEntry {
|
||||
result := slices.Clone(entries)
|
||||
sort.Slice(result, func(i, j int) bool {
|
||||
if result[i].FamilyKey == result[j].FamilyKey {
|
||||
return result[i].Version < result[j].Version
|
||||
}
|
||||
return result[i].FamilyKey < result[j].FamilyKey
|
||||
})
|
||||
return result
|
||||
}
|
||||
orderedLeft, orderedRight := canonical(left), canonical(right)
|
||||
for index := range orderedLeft {
|
||||
if orderedLeft[index].FamilyKey != orderedRight[index].FamilyKey ||
|
||||
orderedLeft[index].Version != orderedRight[index].Version ||
|
||||
!slices.Equal(orderedLeft[index].ContentSHA256, orderedRight[index].ContentSHA256) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func currentAssessmentCatalogMetadata(
|
||||
row sqlc.ListCurrentSpecializationAvailabilityRow,
|
||||
) (domain.AssessmentCategoryCatalogMetadata, bool, error) {
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const assessmentSignalBatchEventLimit = 50
|
||||
|
||||
var (
|
||||
_ outbound.AssessmentSignalRepositories = (*UnitOfWork)(nil)
|
||||
_ outbound.AssessmentSignalRepository = assessmentSignalRepository{}
|
||||
)
|
||||
|
||||
func (unit *UnitOfWork) AssessmentSignals() outbound.AssessmentSignalRepository {
|
||||
return assessmentSignalRepository{queries: unit.queries}
|
||||
}
|
||||
|
||||
type assessmentSignalRepository struct {
|
||||
queries *sqlc.Queries
|
||||
}
|
||||
|
||||
func (repository assessmentSignalRepository) CountRecentOutcomes(
|
||||
ctx context.Context,
|
||||
attemptID domain.AssessmentAttemptID,
|
||||
since time.Time,
|
||||
) (int64, time.Time, error) {
|
||||
const location = "assessmentSignalRepository.CountRecentOutcomes"
|
||||
if attemptID.IsZero() || since.IsZero() {
|
||||
return 0, time.Time{}, fmt.Errorf("%s - attempt and window start are required: %w", location, domain.ErrInvalidAssessmentSignal)
|
||||
}
|
||||
row, err := repository.queries.CountRecentAssessmentSignalOutcomes(ctx, sqlc.CountRecentAssessmentSignalOutcomesParams{
|
||||
AttemptID: pgUUID(attemptID.UUID()), Since: pgTime(since),
|
||||
})
|
||||
if err != nil {
|
||||
return 0, time.Time{}, fmt.Errorf("%s - count recent receipts: %w", location, mapAssessmentError(err))
|
||||
}
|
||||
if row.OutcomeCount < 0 {
|
||||
return 0, time.Time{}, fmt.Errorf("%s - stored receipt count is negative", location)
|
||||
}
|
||||
oldest, err := quotaWindowEarliest(row.OldestAt)
|
||||
if err != nil {
|
||||
return 0, time.Time{}, fmt.Errorf("%s - read oldest receipt: %w", location, err)
|
||||
}
|
||||
return row.OutcomeCount, oldest, nil
|
||||
}
|
||||
|
||||
func (repository assessmentSignalRepository) CountAttemptEvents(
|
||||
ctx context.Context,
|
||||
attemptID domain.AssessmentAttemptID,
|
||||
) (int64, error) {
|
||||
const location = "assessmentSignalRepository.CountAttemptEvents"
|
||||
if attemptID.IsZero() {
|
||||
return 0, fmt.Errorf("%s - attempt ID is required: %w", location, domain.ErrInvalidAssessmentSignal)
|
||||
}
|
||||
count, err := repository.queries.CountAssessmentSignalEvents(ctx, pgUUID(attemptID.UUID()))
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("%s - count stored events: %w", location, mapAssessmentError(err))
|
||||
}
|
||||
if count < 0 {
|
||||
return 0, fmt.Errorf("%s - stored event count is negative", location)
|
||||
}
|
||||
return count, nil
|
||||
}
|
||||
|
||||
func (repository assessmentSignalRepository) SaveBatch(ctx context.Context, batch domain.AssessmentSignalBatch) error {
|
||||
const location = "assessmentSignalRepository.SaveBatch"
|
||||
if _, err := domain.NewAssessmentSignalBatch(batch.ID(), batch.AttemptID(), batch.ReceivedAt(), batch.Events()); err != nil {
|
||||
return fmt.Errorf("%s - batch is invalid: %w", location, err)
|
||||
}
|
||||
events := batch.Events()
|
||||
eventCount, err := assessmentSignalBatchEventCount(events)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - event count is outside the database bound: %w", location, err)
|
||||
}
|
||||
if err := repository.queries.InsertAssessmentSignalBatch(ctx, sqlc.InsertAssessmentSignalBatchParams{
|
||||
ID: pgUUID(batch.ID()), AttemptID: pgUUID(batch.AttemptID().UUID()), ReceivedAt: pgTime(batch.ReceivedAt()),
|
||||
EventCount: eventCount,
|
||||
}); err != nil {
|
||||
return fmt.Errorf("%s - insert batch receipt: %w", location, mapAssessmentError(err))
|
||||
}
|
||||
for index, event := range events {
|
||||
duration, hasDuration := event.DurationMS()
|
||||
size, hasSize := event.SizeBytes()
|
||||
if err := repository.queries.InsertAssessmentSignalEvent(ctx, sqlc.InsertAssessmentSignalEventParams{
|
||||
BatchID: pgUUID(batch.ID()), AttemptID: pgUUID(batch.AttemptID().UUID()), Ordinal: int32(index + 1),
|
||||
ItemInstanceID: pgUUID(event.ItemInstanceID()), Kind: string(event.Kind()), OccurredAt: pgTime(event.OccurredAt()),
|
||||
DurationMs: nullableSignalMeasurement(duration, hasDuration), SizeBytes: nullableSignalMeasurement(size, hasSize),
|
||||
}); err != nil {
|
||||
return fmt.Errorf("%s - insert event metadata: %w", location, mapAssessmentError(err))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func assessmentSignalBatchEventCount(events []domain.AssessmentSignalEvent) (int32, error) {
|
||||
if len(events) < 1 || len(events) > assessmentSignalBatchEventLimit {
|
||||
return 0, domain.ErrInvalidAssessmentSignal
|
||||
}
|
||||
var count int32
|
||||
for range events {
|
||||
count++
|
||||
}
|
||||
return count, nil
|
||||
}
|
||||
|
||||
func (repository assessmentSignalRepository) SaveOutcome(
|
||||
ctx context.Context,
|
||||
scope outbound.AssessmentAttemptIdempotencyScope,
|
||||
attemptID domain.AssessmentAttemptID,
|
||||
receipt domain.AssessmentSignalReceipt,
|
||||
) error {
|
||||
const location = "assessmentSignalRepository.SaveOutcome"
|
||||
if scope == (outbound.AssessmentAttemptIdempotencyScope{}) || attemptID.IsZero() {
|
||||
return fmt.Errorf("%s - scope and attempt ID are required: %w", location, domain.ErrInvalidAssessmentSignal)
|
||||
}
|
||||
if _, err := domain.NewAssessmentSignalReceipt(receipt.Status(), receipt.AcceptedEvents(), receipt.ReceivedAt()); err != nil {
|
||||
return fmt.Errorf("%s - receipt is invalid: %w", location, err)
|
||||
}
|
||||
if err := repository.queries.InsertAssessmentSignalOutcome(ctx, sqlc.InsertAssessmentSignalOutcomeParams{
|
||||
ScopeHash: scope[:], AttemptID: pgUUID(attemptID.UUID()), Status: string(receipt.Status()),
|
||||
AcceptedEvents: receipt.AcceptedEvents(), ReceivedAt: pgTime(receipt.ReceivedAt()),
|
||||
}); err != nil {
|
||||
return fmt.Errorf("%s - insert immutable receipt: %w", location, mapAssessmentError(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository assessmentSignalRepository) DeleteExpiredOutcome(
|
||||
ctx context.Context,
|
||||
scope outbound.AssessmentAttemptIdempotencyScope,
|
||||
) error {
|
||||
const location = "assessmentSignalRepository.DeleteExpiredOutcome"
|
||||
if scope == (outbound.AssessmentAttemptIdempotencyScope{}) {
|
||||
return fmt.Errorf("%s - scope is required: %w", location, domain.ErrInvalidAssessmentSignal)
|
||||
}
|
||||
if err := repository.queries.DeleteExpiredAssessmentSignalOutcome(ctx, scope[:]); err != nil {
|
||||
return fmt.Errorf("%s - remove expired receipt: %w", location, mapAssessmentError(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository assessmentSignalRepository) GetOutcome(
|
||||
ctx context.Context,
|
||||
scope outbound.AssessmentAttemptIdempotencyScope,
|
||||
) (domain.AssessmentSignalReceipt, error) {
|
||||
const location = "assessmentSignalRepository.GetOutcome"
|
||||
if scope == (outbound.AssessmentAttemptIdempotencyScope{}) {
|
||||
return domain.AssessmentSignalReceipt{}, fmt.Errorf("%s - scope is required: %w", location, domain.ErrInvalidAssessmentSignal)
|
||||
}
|
||||
row, err := repository.queries.GetAssessmentSignalOutcome(ctx, scope[:])
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.AssessmentSignalReceipt{}, fmt.Errorf("%s - receipt does not exist: %w", location, outbound.ErrAssessmentSignalOutcomeNotFound)
|
||||
}
|
||||
if err != nil {
|
||||
return domain.AssessmentSignalReceipt{}, fmt.Errorf("%s - read immutable receipt: %w", location, mapAssessmentError(err))
|
||||
}
|
||||
receivedAt, err := requiredSignalReceiptTime(row.ReceivedAt)
|
||||
if err != nil {
|
||||
return domain.AssessmentSignalReceipt{}, fmt.Errorf("%s - restore receipt time: %w", location, err)
|
||||
}
|
||||
receipt, err := domain.NewAssessmentSignalReceipt(domain.AssessmentSignalReceiptStatus(row.Status), row.AcceptedEvents, receivedAt)
|
||||
if err != nil {
|
||||
return domain.AssessmentSignalReceipt{}, fmt.Errorf("%s - restore receipt: %w", location, err)
|
||||
}
|
||||
return receipt, nil
|
||||
}
|
||||
|
||||
func nullableSignalMeasurement(value int32, valid bool) pgtype.Int4 {
|
||||
if !valid {
|
||||
return pgtype.Int4{}
|
||||
}
|
||||
return pgtype.Int4{Int32: value, Valid: true}
|
||||
}
|
||||
|
||||
func requiredSignalReceiptTime(value pgtype.Timestamptz) (time.Time, error) {
|
||||
if !value.Valid || value.Time.IsZero() {
|
||||
return time.Time{}, domain.ErrInvalidAssessmentSignal
|
||||
}
|
||||
return value.Time.UTC(), nil
|
||||
}
|
||||
@@ -256,6 +256,22 @@ func (ledger consentLedger) Current(ctx context.Context, subjectID uuid.UUID, pu
|
||||
return consentRecordFromRow(consentRecordRow(row))
|
||||
}
|
||||
|
||||
func (ledger consentLedger) LockCurrentForUse(
|
||||
ctx context.Context,
|
||||
subjectID uuid.UUID,
|
||||
purpose domain.ConsentPurpose,
|
||||
) (domain.ConsentRecord, error) {
|
||||
const location = "consentLedger.LockCurrentForUse"
|
||||
if subjectID == uuid.Nil || purpose != domain.ConsentPurposeAutoCategorization {
|
||||
return domain.ConsentRecord{}, fmt.Errorf("%s - only a valid subject and C3 can authorize automated use: %w", location, domain.ErrInvalidConsent)
|
||||
}
|
||||
row, err := ledger.queries.LockCurrentConsentForUse(ctx, pgUUID(subjectID))
|
||||
if err != nil {
|
||||
return domain.ConsentRecord{}, fmt.Errorf("%s - lock current C3 record: %w", location, mapConsentNoRows(err, outbound.ErrConsentNotFound))
|
||||
}
|
||||
return consentRecordFromRow(consentRecordRow(row))
|
||||
}
|
||||
|
||||
func (ledger consentLedger) LockRegistration(
|
||||
ctx context.Context,
|
||||
subjectID uuid.UUID,
|
||||
|
||||
@@ -18,12 +18,24 @@ import (
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
var _ outbound.NeedRepository = needRepository{}
|
||||
var (
|
||||
_ outbound.NeedRepository = needRepository{}
|
||||
_ outbound.NeedListRepository = needRepository{}
|
||||
_ outbound.NeedCreationResultRepository = needRepository{}
|
||||
)
|
||||
|
||||
func (unit *UnitOfWork) Needs() outbound.NeedRepository {
|
||||
return needRepository{queries: unit.queries}
|
||||
}
|
||||
|
||||
func (unit *UnitOfWork) NeedLists() outbound.NeedListRepository {
|
||||
return needRepository{queries: unit.queries}
|
||||
}
|
||||
|
||||
func (unit *UnitOfWork) NeedCreationResults() outbound.NeedCreationResultRepository {
|
||||
return needRepository{queries: unit.queries}
|
||||
}
|
||||
|
||||
type needRepository struct {
|
||||
queries *sqlc.Queries
|
||||
}
|
||||
@@ -99,6 +111,129 @@ func (repository needRepository) GetVersion(
|
||||
return restoreNeedSnapshot(location, encoded, organizationID, needID, version, 0, nil, nil)
|
||||
}
|
||||
|
||||
func (repository needRepository) List(ctx context.Context, query outbound.NeedListQuery) (outbound.NeedPage, error) {
|
||||
const location = "needRepository.List"
|
||||
if query.OrganizationID == uuid.Nil {
|
||||
return outbound.NeedPage{}, fmt.Errorf("%s - organization ID must be set: %w", location, domain.ErrInvalidNeed)
|
||||
}
|
||||
if query.Limit < 1 || query.Limit > outbound.MaxNeedPageSize {
|
||||
return outbound.NeedPage{}, fmt.Errorf("%s - limit must be 1 to %d: %w", location, outbound.MaxNeedPageSize, domain.ErrInvalidNeed)
|
||||
}
|
||||
params := sqlc.ListOrganizationNeedsParams{
|
||||
OrganizationID: pgUUID(query.OrganizationID),
|
||||
RowLimit: query.Limit + 1,
|
||||
}
|
||||
if query.After != nil {
|
||||
if err := validateNeedListPosition(location, *query.After); err != nil {
|
||||
return outbound.NeedPage{}, err
|
||||
}
|
||||
params.AfterCreatedAt = pgTime(query.After.CreatedAt)
|
||||
params.AfterNeedID = pgUUID(query.After.NeedID)
|
||||
}
|
||||
rows, err := repository.queries.ListOrganizationNeeds(ctx, params)
|
||||
if err != nil {
|
||||
return outbound.NeedPage{}, fmt.Errorf("%s - select current needs: %w", location, mapNeedError(err))
|
||||
}
|
||||
page := outbound.NeedPage{HasMore: len(rows) > int(query.Limit)}
|
||||
if page.HasMore {
|
||||
rows = rows[:query.Limit]
|
||||
}
|
||||
page.Items = make([]domain.Need, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
if !row.OrganizationID.Valid || !row.NeedID.Valid || !row.CreatedAt.Valid || !row.UpdatedAt.Valid || uuid.UUID(row.OrganizationID.Bytes) != query.OrganizationID {
|
||||
return outbound.NeedPage{}, fmt.Errorf("%s - current need row has invalid scope or metadata", location)
|
||||
}
|
||||
need, err := restoreNeedSnapshot(
|
||||
location, row.Snapshot, query.OrganizationID, uuid.UUID(row.NeedID.Bytes),
|
||||
row.CurrentVersion, row.RequirementsVersion, &row.CreatedAt.Time, &row.UpdatedAt.Time,
|
||||
)
|
||||
if err != nil {
|
||||
return outbound.NeedPage{}, err
|
||||
}
|
||||
page.Items = append(page.Items, need)
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func validateNeedListPosition(location string, position outbound.NeedListPosition) error {
|
||||
createdAt := position.CreatedAt
|
||||
if position.NeedID == uuid.Nil || createdAt.IsZero() || createdAt.Year() < 1 || createdAt.Year() > 9999 ||
|
||||
createdAt.Unix() < 0 || createdAt.Nanosecond()%int(time.Microsecond) != 0 {
|
||||
return fmt.Errorf("%s - pagination position is outside the stored need timestamp range: %w", location, domain.ErrInvalidNeed)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository needRepository) SaveCreationResult(
|
||||
ctx context.Context,
|
||||
scope [outbound.IdempotencyDigestSize]byte,
|
||||
snapshot domain.NeedResponseSnapshot,
|
||||
) error {
|
||||
const location = "needRepository.SaveCreationResult"
|
||||
if scope == ([outbound.IdempotencyDigestSize]byte{}) {
|
||||
return fmt.Errorf("%s - idempotency scope must be set: %w", location, domain.ErrInvalidNeed)
|
||||
}
|
||||
_, encoded, err := encodeNeedCreationResult(snapshot)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - validate and encode response snapshot: %w", location, err)
|
||||
}
|
||||
if err := repository.queries.SaveOrganizationNeedCreationResult(ctx, sqlc.SaveOrganizationNeedCreationResultParams{
|
||||
ScopeHash: scope[:], Snapshot: encoded,
|
||||
}); err != nil {
|
||||
return fmt.Errorf("%s - store response snapshot: %w", location, mapNeedError(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository needRepository) GetCreationResult(
|
||||
ctx context.Context,
|
||||
scope [outbound.IdempotencyDigestSize]byte,
|
||||
) (domain.NeedResponseSnapshot, error) {
|
||||
const location = "needRepository.GetCreationResult"
|
||||
if scope == ([outbound.IdempotencyDigestSize]byte{}) {
|
||||
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - idempotency scope must be set: %w", location, domain.ErrInvalidNeed)
|
||||
}
|
||||
encoded, err := repository.queries.GetOrganizationNeedCreationResult(ctx, scope[:])
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.NeedResponseSnapshot{}, outbound.ErrNeedCreationResultNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - read response snapshot: %w", location, mapNeedError(err))
|
||||
}
|
||||
if len(encoded) > domain.MaxNeedCreationResultStorageBytes {
|
||||
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - stored response snapshot exceeds its bound", location)
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewBufferString(encoded))
|
||||
decoder.DisallowUnknownFields()
|
||||
var snapshot domain.NeedResponseSnapshot
|
||||
if err := decoder.Decode(&snapshot); err != nil {
|
||||
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - stored response snapshot is invalid", location)
|
||||
}
|
||||
if err := decoder.Decode(new(any)); !errors.Is(err, io.EOF) {
|
||||
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - stored response snapshot has trailing data", location)
|
||||
}
|
||||
validated, _, err := encodeNeedCreationResult(snapshot)
|
||||
if err != nil {
|
||||
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - restore response snapshot: %w", location, err)
|
||||
}
|
||||
return validated, nil
|
||||
}
|
||||
|
||||
func encodeNeedCreationResult(snapshot domain.NeedResponseSnapshot) (domain.NeedResponseSnapshot, []byte, error) {
|
||||
validated, err := domain.RestoreNeedResponseSnapshot(snapshot)
|
||||
if err != nil {
|
||||
return domain.NeedResponseSnapshot{}, nil, err
|
||||
}
|
||||
encoded, err := json.Marshal(validated)
|
||||
if err != nil {
|
||||
return domain.NeedResponseSnapshot{}, nil, fmt.Errorf("encode need response snapshot: %w", err)
|
||||
}
|
||||
if len(encoded) > domain.MaxNeedCreationResultBytes {
|
||||
return domain.NeedResponseSnapshot{}, nil, fmt.Errorf("need response snapshot exceeds its storage bound: %w", domain.ErrInvalidNeed)
|
||||
}
|
||||
return validated, encoded, nil
|
||||
}
|
||||
|
||||
func (repository needRepository) Save(
|
||||
ctx context.Context,
|
||||
organizationID, needID uuid.UUID,
|
||||
@@ -216,7 +351,7 @@ func restoreNeedSnapshot(
|
||||
version, requirementsVersion int64,
|
||||
createdAt, updatedAt *time.Time,
|
||||
) (domain.Need, error) {
|
||||
if len(encoded) > domain.MaxNeedSnapshotBytes {
|
||||
if len(encoded) > domain.MaxNeedSnapshotStorageBytes {
|
||||
return domain.Need{}, fmt.Errorf("%s - stored snapshot exceeds its bound", location)
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewBufferString(encoded))
|
||||
@@ -269,6 +404,9 @@ func mapNeedError(err error) error {
|
||||
if pgError.Code == foreignKeyViolationCode && pgError.ConstraintName == "organization_needs_organization_fkey" {
|
||||
return fmt.Errorf("postgres.mapNeedError - organization no longer exists: %w", outbound.ErrOrganizationNotFound)
|
||||
}
|
||||
if pgError.Code == foreignKeyViolationCode && pgError.ConstraintName == "organization_need_creation_results_idempotency_fkey" {
|
||||
return fmt.Errorf("postgres.mapNeedError - idempotency record no longer exists: %w", outbound.ErrIdempotencyRecordNotFound)
|
||||
}
|
||||
if pgError.Code == uniqueViolationCode && pgError.ConstraintName == "organization_needs_pkey" {
|
||||
return fmt.Errorf("postgres.mapNeedError - need ID already exists: %w", outbound.ErrNeedAlreadyExists)
|
||||
}
|
||||
|
||||
@@ -316,6 +316,33 @@ func (repository organizationRepository) GetForMember(
|
||||
return organization, membership, nil
|
||||
}
|
||||
|
||||
func (repository organizationRepository) LockActiveMembership(
|
||||
ctx context.Context,
|
||||
organizationID, userID uuid.UUID,
|
||||
) (domain.Membership, error) {
|
||||
const location = "organizationRepository.LockActiveMembership"
|
||||
row, err := repository.queries.LockActiveMembership(ctx, sqlc.LockActiveMembershipParams{
|
||||
OrganizationID: pgUUID(organizationID),
|
||||
UserID: pgUUID(userID),
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Membership{}, fmt.Errorf("%s - lock active membership: %w", location, mapOrganizationNoRows(err, outbound.ErrOrganizationNotFound))
|
||||
}
|
||||
membership, err := domain.RestoreMembership(domain.StoredMembership{
|
||||
ID: optionalUUID(row.MembershipID),
|
||||
OrganizationID: optionalUUID(row.OrganizationID),
|
||||
UserID: optionalUUID(row.UserID),
|
||||
Role: row.Role,
|
||||
State: row.State,
|
||||
CreatedAt: row.CreatedAt.Time,
|
||||
UpdatedAt: row.UpdatedAt.Time,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Membership{}, fmt.Errorf("%s - restore membership: %w", location, err)
|
||||
}
|
||||
return membership, nil
|
||||
}
|
||||
|
||||
// representativeJSON is one element of the representatives column that
|
||||
// GetOrganizationForMember aggregates in the same statement as the
|
||||
// organization, so the profile and the list come from one snapshot.
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
var _ outbound.PrivacyCohortRepository = privacyCohortRepository{}
|
||||
|
||||
// PrivacyCohortStore reads the current visible candidate cohort outside a
|
||||
// transaction. The single query provides one consistent publication and
|
||||
// hidden-organization snapshot.
|
||||
type PrivacyCohortStore struct {
|
||||
queries *sqlc.Queries
|
||||
}
|
||||
|
||||
func NewPrivacyCohortStore(pool *pgxpool.Pool) *PrivacyCohortStore {
|
||||
return &PrivacyCohortStore{queries: sqlc.New(standaloneDB{pool: pool})}
|
||||
}
|
||||
|
||||
func (unit *UnitOfWork) PrivacyCohort() outbound.PrivacyCohortRepository {
|
||||
return privacyCohortRepository{queries: unit.queries}
|
||||
}
|
||||
|
||||
func (unit *UnitOfWork) PrivacyView() outbound.PrivacyViewRepository {
|
||||
return privacyCohortRepository{queries: unit.queries}
|
||||
}
|
||||
|
||||
func (store *PrivacyCohortStore) ListVisibleCandidateViewSources(
|
||||
ctx context.Context,
|
||||
organizationID uuid.UUID,
|
||||
) ([]domain.CandidateViewSource, error) {
|
||||
return (privacyCohortRepository{queries: store.queries}).ListVisibleCandidateViewSources(ctx, organizationID)
|
||||
}
|
||||
|
||||
type privacyCohortRepository struct {
|
||||
queries *sqlc.Queries
|
||||
}
|
||||
|
||||
type privacyCohortCandidate struct {
|
||||
id uuid.UUID
|
||||
fields domain.CardFieldSet
|
||||
claims []domain.StoredProfileClaim
|
||||
acknowledgements []domain.ProfileParallelPeriodAcknowledgement
|
||||
workFormats []domain.QuestionnaireWorkFormat
|
||||
}
|
||||
|
||||
func (repository privacyCohortRepository) ListVisibleCandidateViewSources(
|
||||
ctx context.Context,
|
||||
organizationID uuid.UUID,
|
||||
) ([]domain.CandidateViewSource, error) {
|
||||
const location = "privacyCohortRepository.ListVisibleCandidateViewSources"
|
||||
if organizationID == uuid.Nil {
|
||||
return nil, fmt.Errorf("%s - organization ID must be set: %w", location, domain.ErrInvalidCandidateViewSource)
|
||||
}
|
||||
rows, err := repository.queries.ListVisibleCandidateViewSources(ctx, pgUUID(organizationID))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - select visible sources: %w", location, markTransactionConflict(sanitizeConnectError(err)))
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return []domain.CandidateViewSource{}, nil
|
||||
}
|
||||
result := make([]domain.CandidateViewSource, 0, len(rows))
|
||||
current := privacyCohortCandidate{}
|
||||
for _, row := range rows {
|
||||
candidateID, err := privacyCohortUUID(row.UserID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - source identity is invalid: %w", location, domain.ErrInvalidCandidateViewSource)
|
||||
}
|
||||
if current.id != uuid.Nil && current.id != candidateID {
|
||||
source, err := buildPrivacyCohortSource(current)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - restore candidate source: %w", location, err)
|
||||
}
|
||||
result = append(result, source)
|
||||
current = privacyCohortCandidate{}
|
||||
}
|
||||
if current.id == uuid.Nil {
|
||||
current, err = newPrivacyCohortCandidate(candidateID, row.Fields, row.WorkFormats, row.ParallelPeriodAcknowledgements)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - restore candidate source: %w", location, err)
|
||||
}
|
||||
}
|
||||
if row.Kind.Valid {
|
||||
claim, err := privacyCohortStoredClaim(row)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - restore candidate claims: %w", location, err)
|
||||
}
|
||||
current.claims = append(current.claims, claim)
|
||||
}
|
||||
}
|
||||
source, err := buildPrivacyCohortSource(current)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - restore candidate source: %w", location, err)
|
||||
}
|
||||
result = append(result, source)
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func newPrivacyCohortCandidate(
|
||||
candidateID uuid.UUID,
|
||||
fieldCodes []string,
|
||||
workFormatCodes []string,
|
||||
acknowledgementsValue any,
|
||||
) (privacyCohortCandidate, error) {
|
||||
fields := make([]domain.CardField, 0, len(fieldCodes))
|
||||
for _, code := range fieldCodes {
|
||||
fields = append(fields, domain.CardField(code))
|
||||
}
|
||||
fieldSet, err := domain.NewCardFieldSet(fields)
|
||||
if err != nil {
|
||||
return privacyCohortCandidate{}, fmt.Errorf("invalid publication fields: %w", domain.ErrInvalidCandidateViewSource)
|
||||
}
|
||||
workFormats := make([]domain.QuestionnaireWorkFormat, 0, len(workFormatCodes))
|
||||
for _, code := range workFormatCodes {
|
||||
workFormats = append(workFormats, domain.QuestionnaireWorkFormat(code))
|
||||
}
|
||||
acknowledgementsJSON, err := privacyCohortEncodedJSONBytes(acknowledgementsValue)
|
||||
if err != nil {
|
||||
return privacyCohortCandidate{}, fmt.Errorf("invalid overlap acknowledgements: %w", domain.ErrInvalidCandidateProfile)
|
||||
}
|
||||
var acknowledgements []domain.ProfileParallelPeriodAcknowledgement
|
||||
if err := json.Unmarshal(acknowledgementsJSON, &acknowledgements); err != nil {
|
||||
return privacyCohortCandidate{}, fmt.Errorf("invalid overlap acknowledgements: %w", domain.ErrInvalidCandidateProfile)
|
||||
}
|
||||
return privacyCohortCandidate{
|
||||
id: candidateID, fields: fieldSet, workFormats: workFormats,
|
||||
acknowledgements: acknowledgements,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func privacyCohortStoredClaim(row sqlc.ListVisibleCandidateViewSourcesRow) (domain.StoredProfileClaim, error) {
|
||||
value, err := privacyCohortJSONBytes(row.SafeValue)
|
||||
if err != nil {
|
||||
return domain.StoredProfileClaim{}, fmt.Errorf("safe JSON type %T is invalid: %w", row.SafeValue, domain.ErrInvalidCandidateProfile)
|
||||
}
|
||||
if !row.Ordinal.Valid || !row.Status.Valid || !row.Origin.Valid || !row.TrustLevel.Valid {
|
||||
return domain.StoredProfileClaim{}, fmt.Errorf("claim metadata is incomplete: %w", domain.ErrInvalidCandidateProfile)
|
||||
}
|
||||
confirmedAt := time.Time{}
|
||||
if row.ConfirmedAt.Valid {
|
||||
confirmedAt = row.ConfirmedAt.Time.UTC()
|
||||
}
|
||||
return domain.StoredProfileClaim{
|
||||
Kind: row.Kind.String, Ordinal: int(row.Ordinal.Int16), Value: value,
|
||||
Status: row.Status.String, Origin: row.Origin.String, TrustLevel: int(row.TrustLevel.Int16),
|
||||
ExtractionVersion: row.ExtractionVersion.String, ConfirmedAt: confirmedAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func buildPrivacyCohortSource(candidate privacyCohortCandidate) (domain.CandidateViewSource, error) {
|
||||
content, err := domain.RestoreCandidateProfileContentWithParallelPeriods(candidate.claims, candidate.acknowledgements)
|
||||
if err != nil {
|
||||
return domain.CandidateViewSource{}, fmt.Errorf("validate safe profile claims: %w", domain.ErrInvalidCandidateViewSource)
|
||||
}
|
||||
return domain.NewCandidateViewSource(
|
||||
candidate.id, candidate.fields, domain.CandidateViewProfileFromContent(content), nil,
|
||||
candidate.workFormats, nil,
|
||||
)
|
||||
}
|
||||
|
||||
func privacyCohortJSONBytes(value any) ([]byte, error) {
|
||||
switch typed := value.(type) {
|
||||
case []byte:
|
||||
return slices.Clone(typed), nil
|
||||
case json.RawMessage:
|
||||
return slices.Clone(typed), nil
|
||||
default:
|
||||
encoded, err := json.Marshal(typed)
|
||||
if err != nil {
|
||||
return nil, errors.New("JSON projection has an unexpected type")
|
||||
}
|
||||
return encoded, nil
|
||||
}
|
||||
}
|
||||
|
||||
func privacyCohortEncodedJSONBytes(value any) ([]byte, error) {
|
||||
switch typed := value.(type) {
|
||||
case string:
|
||||
return []byte(typed), nil
|
||||
case []byte:
|
||||
return slices.Clone(typed), nil
|
||||
case json.RawMessage:
|
||||
return slices.Clone(typed), nil
|
||||
default:
|
||||
return nil, errors.New("encoded JSON projection has an unexpected type")
|
||||
}
|
||||
}
|
||||
|
||||
func privacyCohortUUID(value pgtype.UUID) (uuid.UUID, error) {
|
||||
if !value.Valid || value.Bytes == uuid.Nil {
|
||||
return uuid.Nil, domain.ErrInvalidCandidateViewSource
|
||||
}
|
||||
return uuid.UUID(value.Bytes), nil
|
||||
}
|
||||
@@ -0,0 +1,441 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
var _ outbound.PrivacySettingsRepository = privacySettingsRepository{}
|
||||
|
||||
var privacySettingsConstraintErrors = map[constraintViolation]error{
|
||||
{foreignKeyViolationCode, "candidate_publications_consent_fkey"}: outbound.ErrConsentNotFound,
|
||||
{foreignKeyViolationCode, "candidate_hidden_organizations_user_id_fkey"}: outbound.ErrUserNotFound,
|
||||
{foreignKeyViolationCode, "candidate_hidden_organizations_organization_id_fkey"}: outbound.ErrCandidatePrivacyOrganizationNotVisible,
|
||||
{foreignKeyViolationCode, "candidate_privacy_events_user_id_fkey"}: outbound.ErrUserNotFound,
|
||||
{foreignKeyViolationCode, "candidate_privacy_events_consent_fkey"}: outbound.ErrConsentNotFound,
|
||||
{foreignKeyViolationCode, "candidate_privacy_events_organization_id_fkey"}: outbound.ErrCandidatePrivacyOrganizationNotVisible,
|
||||
{checkViolationCode, "candidate_hidden_organizations_limit"}: outbound.ErrCandidateHiddenOrganizationLimit,
|
||||
}
|
||||
|
||||
func (unit *UnitOfWork) PrivacySettings() outbound.PrivacySettingsRepository {
|
||||
return privacySettingsRepository{queries: unit.queries}
|
||||
}
|
||||
|
||||
type privacySettingsRepository struct {
|
||||
queries *sqlc.Queries
|
||||
}
|
||||
|
||||
func (repository privacySettingsRepository) ReadSettings(ctx context.Context, userID uuid.UUID) (outbound.CandidatePrivacySettings, error) {
|
||||
const location = "privacySettingsRepository.ReadSettings"
|
||||
if userID == uuid.Nil {
|
||||
return outbound.CandidatePrivacySettings{}, fmt.Errorf("%s - user ID is empty: %w", location, domain.ErrInvalidVisibility)
|
||||
}
|
||||
row, err := repository.queries.ReadCandidatePrivacySettings(ctx, pgUUID(userID))
|
||||
if err != nil {
|
||||
return outbound.CandidatePrivacySettings{}, fmt.Errorf("%s - select settings: %w", location, mapPrivacySettingsNoRows(err, outbound.ErrUserNotFound))
|
||||
}
|
||||
if got, err := privacySettingsUUID(row.UserID); err != nil || got != userID {
|
||||
return outbound.CandidatePrivacySettings{}, fmt.Errorf("%s - result identity is invalid: %w", location, domain.ErrInvalidVisibility)
|
||||
}
|
||||
publication, err := publicationFromSettingsRow(userID, row)
|
||||
if err != nil {
|
||||
return outbound.CandidatePrivacySettings{}, fmt.Errorf("%s - restore publication: %w", location, err)
|
||||
}
|
||||
searchStatus, err := searchStatusFromSettingsRow(userID, row)
|
||||
if err != nil {
|
||||
return outbound.CandidatePrivacySettings{}, fmt.Errorf("%s - restore search status: %w", location, err)
|
||||
}
|
||||
return outbound.CandidatePrivacySettings{
|
||||
Publication: publication, SearchStatus: searchStatus, HiddenCount: row.HiddenCount,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func publicationFromSettingsRow(userID uuid.UUID, row sqlc.ReadCandidatePrivacySettingsRow) (domain.Publication, error) {
|
||||
if !row.PublicationState.Valid {
|
||||
return domain.NewPublication(userID)
|
||||
}
|
||||
consentID, err := privacySettingsUUID(row.PublicationConsentRecordID)
|
||||
if err != nil {
|
||||
return domain.Publication{}, fmt.Errorf("publication consent ID is invalid: %w", domain.ErrInvalidVisibility)
|
||||
}
|
||||
if !row.PublicationVersion.Valid || !row.PublicationPublishedAt.Valid {
|
||||
return domain.Publication{}, fmt.Errorf("publication snapshot is incomplete: %w", domain.ErrInvalidVisibility)
|
||||
}
|
||||
stored := domain.StoredPublication{
|
||||
UserID: userID, State: row.PublicationState.String, Fields: row.PublicationFields,
|
||||
ConsentRecordID: consentID, PublishedAt: row.PublicationPublishedAt.Time.UTC(),
|
||||
ClosedAt: privacySettingsTime(row.PublicationClosedAt), Version: row.PublicationVersion.Int64,
|
||||
ConsentRevoked: row.PublicationConsentRevokedAt.Valid,
|
||||
}
|
||||
return domain.RestorePublication(stored)
|
||||
}
|
||||
|
||||
func searchStatusFromSettingsRow(userID uuid.UUID, row sqlc.ReadCandidatePrivacySettingsRow) (domain.SearchStatus, error) {
|
||||
if !row.SearchStatus.Valid {
|
||||
return domain.NewSearchStatus(userID)
|
||||
}
|
||||
if !row.SearchVersion.Valid {
|
||||
return domain.SearchStatus{}, fmt.Errorf("search status snapshot is incomplete: %w", domain.ErrInvalidVisibility)
|
||||
}
|
||||
var policyVersionID domain.PolicyVersionID
|
||||
if row.SearchPolicyVersionID.Valid {
|
||||
policyVersionID = domain.PolicyVersionID(row.SearchPolicyVersionID.Bytes)
|
||||
}
|
||||
return domain.RestoreSearchStatus(domain.StoredSearchStatus{
|
||||
UserID: userID, Status: row.SearchStatus.String,
|
||||
ConfirmedAt: privacySettingsTime(row.SearchConfirmedAt), LapsesAt: privacySettingsTime(row.SearchLapsesAt),
|
||||
PolicyVersionID: policyVersionID, Version: row.SearchVersion.Int64,
|
||||
})
|
||||
}
|
||||
|
||||
func (repository privacySettingsRepository) LockCurrentC2ForPublication(ctx context.Context, userID uuid.UUID) (uuid.UUID, error) {
|
||||
const location = "privacySettingsRepository.LockCurrentC2ForPublication"
|
||||
if userID == uuid.Nil {
|
||||
return uuid.Nil, fmt.Errorf("%s - user ID is empty: %w", location, domain.ErrInvalidVisibility)
|
||||
}
|
||||
id, err := repository.queries.LockCurrentC2Record(ctx, pgUUID(userID))
|
||||
if err != nil {
|
||||
return uuid.Nil, fmt.Errorf("%s - lock current C2: %w", location, mapPrivacySettingsNoRows(err, outbound.ErrConsentNotFound))
|
||||
}
|
||||
return privacySettingsUUID(id)
|
||||
}
|
||||
|
||||
func (repository privacySettingsRepository) SavePublication(ctx context.Context, publication domain.Publication, expectedVersion int64) error {
|
||||
const location = "privacySettingsRepository.SavePublication"
|
||||
if publication.UserID() == uuid.Nil || publication.Version() != expectedVersion+1 || expectedVersion < 0 {
|
||||
return fmt.Errorf("%s - publication version is invalid: %w", location, domain.ErrInvalidVisibility)
|
||||
}
|
||||
params := sqlc.InsertCandidatePublicationParams{
|
||||
UserID: pgUUID(publication.UserID()), State: string(publication.StoredState()), Fields: publication.StoredFields(),
|
||||
ConsentRecordID: privacySettingsOptionalUUID(publication.ConsentRecordID()),
|
||||
PublishedAt: pgTime(publication.PublishedAt()), ClosedAt: privacySettingsOptionalTime(publication.ClosedAt()),
|
||||
At: pgTime(privacySettingsPublicationUpdatedAt(publication)),
|
||||
}
|
||||
var err error
|
||||
if expectedVersion == 0 {
|
||||
_, err = repository.queries.InsertCandidatePublication(ctx, params)
|
||||
} else {
|
||||
_, err = repository.queries.UpdateCandidatePublication(ctx, sqlc.UpdateCandidatePublicationParams{
|
||||
State: params.State, Fields: params.Fields, ConsentRecordID: params.ConsentRecordID,
|
||||
PublishedAt: params.PublishedAt, ClosedAt: params.ClosedAt, At: params.At,
|
||||
UserID: params.UserID, ExpectedVersion: expectedVersion,
|
||||
})
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - persist publication: %w", location, mapPrivacySettingsWriteError(err, domain.ErrVisibilityVersionConflict))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func privacySettingsPublicationUpdatedAt(publication domain.Publication) time.Time {
|
||||
if publication.StoredState() == domain.PublicationClosed {
|
||||
return publication.ClosedAt()
|
||||
}
|
||||
return publication.PublishedAt()
|
||||
}
|
||||
|
||||
func (repository privacySettingsRepository) SaveSearchStatus(ctx context.Context, status domain.SearchStatus, expectedVersion int64, at time.Time) error {
|
||||
const location = "privacySettingsRepository.SaveSearchStatus"
|
||||
if status.UserID() == uuid.Nil || status.Version() != expectedVersion+1 || expectedVersion < 0 {
|
||||
return fmt.Errorf("%s - status version is invalid: %w", location, domain.ErrInvalidVisibility)
|
||||
}
|
||||
policyID := status.PolicyVersionID().UUID()
|
||||
params := sqlc.InsertCandidateSearchStatusParams{
|
||||
UserID: pgUUID(status.UserID()), Status: string(status.StoredValue()),
|
||||
ConfirmedAt: privacySettingsOptionalTime(status.ConfirmedAt()),
|
||||
LapsesAt: privacySettingsOptionalTime(status.LapsesAt()), PolicyVersionID: privacySettingsOptionalUUID(policyID),
|
||||
At: pgTime(at.UTC().Truncate(time.Microsecond)),
|
||||
}
|
||||
var err error
|
||||
if expectedVersion == 0 {
|
||||
_, err = repository.queries.InsertCandidateSearchStatus(ctx, params)
|
||||
} else {
|
||||
_, err = repository.queries.UpdateCandidateSearchStatus(ctx, sqlc.UpdateCandidateSearchStatusParams{
|
||||
UserID: params.UserID, Status: params.Status, ConfirmedAt: params.ConfirmedAt, LapsesAt: params.LapsesAt,
|
||||
PolicyVersionID: params.PolicyVersionID, At: params.At, ExpectedVersion: expectedVersion,
|
||||
})
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - persist status: %w", location, mapPrivacySettingsWriteError(err, domain.ErrVisibilityVersionConflict))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository privacySettingsRepository) CountHiddenOrganizations(ctx context.Context, userID uuid.UUID) (int64, error) {
|
||||
if userID == uuid.Nil {
|
||||
return 0, domain.ErrInvalidVisibility
|
||||
}
|
||||
count, err := repository.queries.CountCandidateHiddenOrganizations(ctx, pgUUID(userID))
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("privacySettingsRepository.CountHiddenOrganizations - count records: %w", mapPrivacySettingsError(err))
|
||||
}
|
||||
return count, nil
|
||||
}
|
||||
|
||||
func (repository privacySettingsRepository) GetHiddenOrganization(ctx context.Context, userID, organizationID uuid.UUID) (outbound.HiddenOrganizationRecord, error) {
|
||||
const location = "privacySettingsRepository.GetHiddenOrganization"
|
||||
if userID == uuid.Nil || organizationID == uuid.Nil {
|
||||
return outbound.HiddenOrganizationRecord{}, fmt.Errorf("%s - IDs are empty: %w", location, domain.ErrInvalidVisibility)
|
||||
}
|
||||
row, err := repository.queries.GetCandidateHiddenOrganization(ctx, sqlc.GetCandidateHiddenOrganizationParams{
|
||||
UserID: pgUUID(userID), OrganizationID: pgUUID(organizationID),
|
||||
})
|
||||
if err != nil {
|
||||
return outbound.HiddenOrganizationRecord{}, fmt.Errorf("%s - select record: %w", location, mapPrivacySettingsNoRows(err, outbound.ErrCandidatePrivacySettingsNotFound))
|
||||
}
|
||||
return hiddenOrganizationFromRow(row.OrganizationID, row.OrganizationName, row.HiddenAt)
|
||||
}
|
||||
|
||||
func (repository privacySettingsRepository) CandidateCanSeeOrganization(ctx context.Context, userID, organizationID uuid.UUID) (outbound.CandidateVisibleOrganization, error) {
|
||||
const location = "privacySettingsRepository.CandidateCanSeeOrganization"
|
||||
if userID == uuid.Nil || organizationID == uuid.Nil {
|
||||
return outbound.CandidateVisibleOrganization{}, fmt.Errorf("%s - IDs are empty: %w", location, domain.ErrInvalidVisibility)
|
||||
}
|
||||
row, err := repository.queries.CandidateCanSeeOrganization(ctx, sqlc.CandidateCanSeeOrganizationParams{
|
||||
OrganizationID: pgUUID(organizationID), UserID: pgUUID(userID),
|
||||
})
|
||||
if err != nil {
|
||||
return outbound.CandidateVisibleOrganization{}, fmt.Errorf("%s - select visible organization: %w", location, mapPrivacySettingsNoRows(err, outbound.ErrCandidatePrivacyOrganizationNotVisible))
|
||||
}
|
||||
id, err := privacySettingsUUID(row.ID)
|
||||
if err != nil || id != organizationID || row.Name == "" {
|
||||
return outbound.CandidateVisibleOrganization{}, fmt.Errorf("%s - organization snapshot is invalid: %w", location, domain.ErrInvalidVisibility)
|
||||
}
|
||||
return outbound.CandidateVisibleOrganization{ID: id, Name: row.Name}, nil
|
||||
}
|
||||
|
||||
func (repository privacySettingsRepository) HideOrganization(ctx context.Context, hidden domain.HiddenOrganization) (bool, error) {
|
||||
const location = "privacySettingsRepository.HideOrganization"
|
||||
if hidden.UserID() == uuid.Nil || hidden.OrganizationID() == uuid.Nil || hidden.HiddenAt().IsZero() {
|
||||
return false, fmt.Errorf("%s - hiding is invalid: %w", location, domain.ErrInvalidVisibility)
|
||||
}
|
||||
_, err := repository.queries.InsertCandidateHiddenOrganization(ctx, sqlc.InsertCandidateHiddenOrganizationParams{
|
||||
UserID: pgUUID(hidden.UserID()), OrganizationID: pgUUID(hidden.OrganizationID()), At: pgTime(hidden.HiddenAt()),
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("%s - insert record: %w", location, mapPrivacySettingsError(err))
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (repository privacySettingsRepository) UnhideOrganization(ctx context.Context, userID, organizationID uuid.UUID) (bool, error) {
|
||||
const location = "privacySettingsRepository.UnhideOrganization"
|
||||
if userID == uuid.Nil || organizationID == uuid.Nil {
|
||||
return false, fmt.Errorf("%s - IDs are empty: %w", location, domain.ErrInvalidVisibility)
|
||||
}
|
||||
_, err := repository.queries.DeleteCandidateHiddenOrganization(ctx, sqlc.DeleteCandidateHiddenOrganizationParams{
|
||||
UserID: pgUUID(userID), OrganizationID: pgUUID(organizationID),
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("%s - delete record: %w", location, mapPrivacySettingsError(err))
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (repository privacySettingsRepository) ListHiddenOrganizations(ctx context.Context, query outbound.HiddenOrganizationListQuery) (outbound.HiddenOrganizationPage, error) {
|
||||
const location = "privacySettingsRepository.ListHiddenOrganizations"
|
||||
if query.UserID == uuid.Nil || query.Limit < 1 || query.Limit > outbound.MaxPrivacyPageSize {
|
||||
return outbound.HiddenOrganizationPage{}, fmt.Errorf("%s - query is invalid: %w", location, domain.ErrInvalidVisibility)
|
||||
}
|
||||
params := sqlc.ListCandidateHiddenOrganizationsParams{UserID: pgUUID(query.UserID), RowLimit: query.Limit + 1}
|
||||
if query.After != nil {
|
||||
if query.After.HiddenAt.IsZero() || query.After.OrganizationID == uuid.Nil {
|
||||
return outbound.HiddenOrganizationPage{}, fmt.Errorf("%s - cursor is invalid: %w", location, domain.ErrInvalidVisibility)
|
||||
}
|
||||
params.AfterHiddenAt = pgTime(query.After.HiddenAt)
|
||||
params.AfterOrganizationID = pgUUID(query.After.OrganizationID)
|
||||
}
|
||||
rows, err := repository.queries.ListCandidateHiddenOrganizations(ctx, params)
|
||||
if err != nil {
|
||||
return outbound.HiddenOrganizationPage{}, fmt.Errorf("%s - select records: %w", location, mapPrivacySettingsError(err))
|
||||
}
|
||||
page := outbound.HiddenOrganizationPage{Items: make([]outbound.HiddenOrganizationRecord, 0, min(len(rows), int(query.Limit)))}
|
||||
for index, row := range rows {
|
||||
if index == int(query.Limit) {
|
||||
page.HasMore = true
|
||||
break
|
||||
}
|
||||
record, err := hiddenOrganizationFromRow(row.OrganizationID, row.OrganizationName, row.HiddenAt)
|
||||
if err != nil {
|
||||
return outbound.HiddenOrganizationPage{}, fmt.Errorf("%s - restore record: %w", location, err)
|
||||
}
|
||||
page.Items = append(page.Items, record)
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func (repository privacySettingsRepository) RecordPrivacyEvent(ctx context.Context, event domain.PrivacyEvent) error {
|
||||
const location = "privacySettingsRepository.RecordPrivacyEvent"
|
||||
if event.ID() == uuid.Nil || event.UserID() == uuid.Nil || !event.Kind().Valid() || event.OccurredAt().IsZero() {
|
||||
return fmt.Errorf("%s - event is invalid: %w", location, domain.ErrInvalidVisibility)
|
||||
}
|
||||
params := sqlc.InsertCandidatePrivacyEventParams{
|
||||
ID: pgUUID(event.ID()), UserID: pgUUID(event.UserID()), Kind: string(event.Kind()), OccurredAt: pgTime(event.OccurredAt()),
|
||||
}
|
||||
if event.HasFieldSet() {
|
||||
params.Fields = event.Fields().Codes()
|
||||
}
|
||||
if event.ConsentRecordID() != uuid.Nil {
|
||||
params.ConsentRecordID = pgUUID(event.ConsentRecordID())
|
||||
}
|
||||
if event.OrganizationID() != uuid.Nil {
|
||||
params.OrganizationID = pgUUID(event.OrganizationID())
|
||||
}
|
||||
if err := repository.queries.InsertCandidatePrivacyEvent(ctx, params); err != nil {
|
||||
return fmt.Errorf("%s - insert event: %w", location, mapPrivacySettingsError(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository privacySettingsRepository) ListPrivacyEvents(ctx context.Context, query outbound.CandidatePrivacyEventListQuery) (outbound.CandidatePrivacyEventPage, error) {
|
||||
const location = "privacySettingsRepository.ListPrivacyEvents"
|
||||
if query.UserID == uuid.Nil || query.Limit < 1 || query.Limit > outbound.MaxPrivacyPageSize {
|
||||
return outbound.CandidatePrivacyEventPage{}, fmt.Errorf("%s - query is invalid: %w", location, domain.ErrInvalidVisibility)
|
||||
}
|
||||
params := sqlc.ListCandidatePrivacyEventsParams{UserID: pgUUID(query.UserID), RowLimit: query.Limit + 1}
|
||||
if query.After != nil {
|
||||
if query.After.OccurredAt.IsZero() || query.After.ID == uuid.Nil {
|
||||
return outbound.CandidatePrivacyEventPage{}, fmt.Errorf("%s - cursor is invalid: %w", location, domain.ErrInvalidVisibility)
|
||||
}
|
||||
params.AfterOccurredAt = pgTime(query.After.OccurredAt)
|
||||
params.AfterID = pgUUID(query.After.ID)
|
||||
}
|
||||
rows, err := repository.queries.ListCandidatePrivacyEvents(ctx, params)
|
||||
if err != nil {
|
||||
return outbound.CandidatePrivacyEventPage{}, fmt.Errorf("%s - select events: %w", location, mapPrivacySettingsError(err))
|
||||
}
|
||||
page := outbound.CandidatePrivacyEventPage{Items: make([]outbound.CandidatePrivacyEventRecord, 0, min(len(rows), int(query.Limit)))}
|
||||
for index, row := range rows {
|
||||
if index == int(query.Limit) {
|
||||
page.HasMore = true
|
||||
break
|
||||
}
|
||||
record, err := privacyEventFromRow(row)
|
||||
if err != nil {
|
||||
return outbound.CandidatePrivacyEventPage{}, fmt.Errorf("%s - restore event: %w", location, err)
|
||||
}
|
||||
page.Items = append(page.Items, record)
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func privacyEventFromRow(row sqlc.ListCandidatePrivacyEventsRow) (outbound.CandidatePrivacyEventRecord, error) {
|
||||
id, err := privacySettingsUUID(row.ID)
|
||||
if err != nil || !row.OccurredAt.Valid {
|
||||
return outbound.CandidatePrivacyEventRecord{}, domain.ErrInvalidVisibility
|
||||
}
|
||||
record := outbound.CandidatePrivacyEventRecord{ID: id, Kind: domain.PrivacyEventKind(row.Kind), OccurredAt: row.OccurredAt.Time.UTC()}
|
||||
if !record.Kind.Valid() {
|
||||
return outbound.CandidatePrivacyEventRecord{}, domain.ErrInvalidVisibility
|
||||
}
|
||||
if row.Fields != nil {
|
||||
fields, err := domain.NewCardFieldSet(stringsToCardFields(row.Fields))
|
||||
if err != nil {
|
||||
return outbound.CandidatePrivacyEventRecord{}, domain.ErrInvalidVisibility
|
||||
}
|
||||
record.Fields = &fields
|
||||
}
|
||||
if row.ConsentRecordID.Valid {
|
||||
record.ConsentRecordID, err = privacySettingsUUID(row.ConsentRecordID)
|
||||
if err != nil {
|
||||
return outbound.CandidatePrivacyEventRecord{}, err
|
||||
}
|
||||
}
|
||||
if row.OrganizationID.Valid {
|
||||
record.OrganizationID, err = privacySettingsUUID(row.OrganizationID)
|
||||
if err != nil {
|
||||
return outbound.CandidatePrivacyEventRecord{}, err
|
||||
}
|
||||
}
|
||||
if row.OrganizationName.Valid {
|
||||
record.OrganizationName = row.OrganizationName.String
|
||||
}
|
||||
return record, nil
|
||||
}
|
||||
|
||||
func hiddenOrganizationFromRow(id pgtype.UUID, name string, hiddenAt pgtype.Timestamptz) (outbound.HiddenOrganizationRecord, error) {
|
||||
organizationID, err := privacySettingsUUID(id)
|
||||
if err != nil || name == "" || !hiddenAt.Valid {
|
||||
return outbound.HiddenOrganizationRecord{}, domain.ErrInvalidVisibility
|
||||
}
|
||||
return outbound.HiddenOrganizationRecord{OrganizationID: organizationID, OrganizationName: name, HiddenAt: hiddenAt.Time.UTC()}, nil
|
||||
}
|
||||
|
||||
func privacySettingsOptionalTime(value time.Time) pgtype.Timestamptz {
|
||||
if value.IsZero() {
|
||||
return pgtype.Timestamptz{}
|
||||
}
|
||||
return pgTime(value)
|
||||
}
|
||||
|
||||
func privacySettingsOptionalUUID(value uuid.UUID) pgtype.UUID {
|
||||
if value == uuid.Nil {
|
||||
return pgtype.UUID{}
|
||||
}
|
||||
return pgUUID(value)
|
||||
}
|
||||
|
||||
func privacySettingsTime(value pgtype.Timestamptz) time.Time {
|
||||
if !value.Valid {
|
||||
return time.Time{}
|
||||
}
|
||||
return value.Time.UTC()
|
||||
}
|
||||
|
||||
func privacySettingsUUID(value pgtype.UUID) (uuid.UUID, error) {
|
||||
if !value.Valid || uuid.UUID(value.Bytes) == uuid.Nil {
|
||||
return uuid.Nil, domain.ErrInvalidVisibility
|
||||
}
|
||||
return uuid.UUID(value.Bytes), nil
|
||||
}
|
||||
|
||||
func stringsToCardFields(codes []string) []domain.CardField {
|
||||
fields := make([]domain.CardField, 0, len(codes))
|
||||
for _, code := range codes {
|
||||
fields = append(fields, domain.CardField(code))
|
||||
}
|
||||
return fields
|
||||
}
|
||||
|
||||
func mapPrivacySettingsNoRows(err, sentinel error) error {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return sentinel
|
||||
}
|
||||
return mapPrivacySettingsError(err)
|
||||
}
|
||||
|
||||
func mapPrivacySettingsWriteError(err, noRows error) error {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return noRows
|
||||
}
|
||||
return mapPrivacySettingsError(err)
|
||||
}
|
||||
|
||||
func mapPrivacySettingsError(err error) error {
|
||||
var pgError *pgconn.PgError
|
||||
if !errors.As(err, &pgError) {
|
||||
return sanitizeConnectError(err)
|
||||
}
|
||||
violation := constraintViolation{code: pgError.Code, constraint: pgError.ConstraintName}
|
||||
if sentinel, ok := privacySettingsConstraintErrors[violation]; ok {
|
||||
return fmt.Errorf("postgres.mapPrivacySettingsError - constraint %s: %w", pgError.ConstraintName, sentinel)
|
||||
}
|
||||
return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName})
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
var _ outbound.PrivacyViewRepository = privacyCohortRepository{}
|
||||
|
||||
// CurrentFields stays closed until invitation grants have transaction-bound
|
||||
// persistence. The C4 ledger alone does not identify a live invitation grant.
|
||||
func (privacyCohortRepository) CurrentFields(context.Context, uuid.UUID, uuid.UUID) (domain.ContactFieldSet, error) {
|
||||
return domain.ContactFieldSet{}, outbound.ErrContactAccessClosed
|
||||
}
|
||||
|
||||
func (privacyCohortRepository) CloseForVisibility(context.Context, uuid.UUID, uuid.UUID, time.Time) error {
|
||||
// No C4 contact-grant persistence exists in this release. Contact reads are
|
||||
// closed by default, so there is no persisted grant to reactivate later.
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository privacyCohortRepository) LockCandidateAccountForView(ctx context.Context, candidateID uuid.UUID) error {
|
||||
const location = "privacyCohortRepository.LockCandidateAccountForView"
|
||||
if candidateID == uuid.Nil {
|
||||
return fmt.Errorf("%s - candidate ID must be set: %w", location, domain.ErrInvalidCandidateViewSource)
|
||||
}
|
||||
_, err := repository.queries.LockCandidateAccountForView(ctx, pgUUID(candidateID))
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - lock candidate account: %w", location,
|
||||
mapNoRows(sanitizeConnectError(err), outbound.ErrUserNotFound))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository privacyCohortRepository) LockCurrentC2ForView(ctx context.Context, candidateID uuid.UUID) (uuid.UUID, error) {
|
||||
const location = "privacyCohortRepository.LockCurrentC2ForView"
|
||||
if candidateID == uuid.Nil {
|
||||
return uuid.Nil, fmt.Errorf("%s - candidate ID must be set: %w", location, domain.ErrInvalidCandidateViewSource)
|
||||
}
|
||||
consentID, err := repository.queries.LockCurrentC2ForView(ctx, pgUUID(candidateID))
|
||||
if err != nil {
|
||||
return uuid.Nil, fmt.Errorf("%s - lock current C2: %w", location,
|
||||
mapNoRows(sanitizeConnectError(err), outbound.ErrCandidateC2Unavailable))
|
||||
}
|
||||
return privacyCohortUUID(consentID)
|
||||
}
|
||||
|
||||
func (repository privacyCohortRepository) LockVisiblePublicationForView(
|
||||
ctx context.Context,
|
||||
organizationID, candidateID, consentRecordID uuid.UUID,
|
||||
) (bool, error) {
|
||||
const location = "privacyCohortRepository.LockVisiblePublicationForView"
|
||||
if organizationID == uuid.Nil || candidateID == uuid.Nil || consentRecordID == uuid.Nil {
|
||||
return false, fmt.Errorf("%s - identifiers must be set: %w", location, domain.ErrInvalidCandidateViewSource)
|
||||
}
|
||||
_, err := repository.queries.LockVisiblePublicationForView(ctx, sqlc.LockVisiblePublicationForViewParams{
|
||||
OrganizationID: pgUUID(organizationID), CandidateID: pgUUID(candidateID), ConsentRecordID: pgUUID(consentRecordID),
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("%s - lock visible publication: %w", location, markTransactionConflict(sanitizeConnectError(err)))
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (repository privacyCohortRepository) LockPublicationForPreview(ctx context.Context, candidateID uuid.UUID) (bool, error) {
|
||||
const location = "privacyCohortRepository.LockPublicationForPreview"
|
||||
if candidateID == uuid.Nil {
|
||||
return false, fmt.Errorf("%s - candidate ID must be set: %w", location, domain.ErrInvalidCandidateViewSource)
|
||||
}
|
||||
_, err := repository.queries.LockPublicationForCandidatePreview(ctx, pgUUID(candidateID))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("%s - lock current publication: %w", location, markTransactionConflict(sanitizeConnectError(err)))
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (repository privacyCohortRepository) ReadCandidateViewSourceForPreview(
|
||||
ctx context.Context,
|
||||
candidateID uuid.UUID,
|
||||
) (domain.CandidateViewSource, error) {
|
||||
const location = "privacyCohortRepository.ReadCandidateViewSourceForPreview"
|
||||
if candidateID == uuid.Nil {
|
||||
return domain.CandidateViewSource{}, fmt.Errorf("%s - candidate ID must be set: %w", location, domain.ErrInvalidCandidateViewSource)
|
||||
}
|
||||
rows, err := repository.queries.ReadCandidateViewSourceForPreview(ctx, pgUUID(candidateID))
|
||||
if err != nil {
|
||||
return domain.CandidateViewSource{}, fmt.Errorf("%s - read candidate projection: %w", location, markTransactionConflict(sanitizeConnectError(err)))
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return domain.CandidateViewSource{}, fmt.Errorf("%s - current publication has no projection row: %w", location, outbound.ErrPrivacyCohortUnavailable)
|
||||
}
|
||||
return buildPreviewCandidateViewSource(candidateID, rows)
|
||||
}
|
||||
|
||||
func buildPreviewCandidateViewSource(
|
||||
candidateID uuid.UUID,
|
||||
rows []sqlc.ReadCandidateViewSourceForPreviewRow,
|
||||
) (domain.CandidateViewSource, error) {
|
||||
const location = "buildPreviewCandidateViewSource"
|
||||
first := rows[0]
|
||||
if got, err := privacyCohortUUID(first.UserID); err != nil || got != candidateID {
|
||||
return domain.CandidateViewSource{}, fmt.Errorf("%s - projection identity is invalid: %w", location, domain.ErrInvalidCandidateViewSource)
|
||||
}
|
||||
candidate, err := newPrivacyCohortCandidate(candidateID, first.Fields, first.WorkFormats, first.ParallelPeriodAcknowledgements)
|
||||
if err != nil {
|
||||
return domain.CandidateViewSource{}, fmt.Errorf("%s - restore candidate input: %w", location, err)
|
||||
}
|
||||
for _, row := range rows {
|
||||
if row.Kind.Valid {
|
||||
claim, err := previewStoredClaim(row)
|
||||
if err != nil {
|
||||
return domain.CandidateViewSource{}, fmt.Errorf("%s - restore candidate claim: %w", location, err)
|
||||
}
|
||||
candidate.claims = append(candidate.claims, claim)
|
||||
}
|
||||
}
|
||||
return buildPrivacyCohortSource(candidate)
|
||||
}
|
||||
|
||||
func previewStoredClaim(row sqlc.ReadCandidateViewSourceForPreviewRow) (domain.StoredProfileClaim, error) {
|
||||
value, err := privacyCohortJSONBytes(row.SafeValue)
|
||||
if err != nil {
|
||||
return domain.StoredProfileClaim{}, fmt.Errorf("safe JSON type %T is invalid: %w", row.SafeValue, domain.ErrInvalidCandidateProfile)
|
||||
}
|
||||
if !row.Ordinal.Valid || !row.Status.Valid || !row.Origin.Valid || !row.TrustLevel.Valid {
|
||||
return domain.StoredProfileClaim{}, fmt.Errorf("claim metadata is incomplete: %w", domain.ErrInvalidCandidateProfile)
|
||||
}
|
||||
confirmedAt := timeValueOrZero(row.ConfirmedAt)
|
||||
return domain.StoredProfileClaim{
|
||||
Kind: row.Kind.String, Ordinal: int(row.Ordinal.Int16), Value: value,
|
||||
Status: row.Status.String, Origin: row.Origin.String, TrustLevel: int(row.TrustLevel.Int16),
|
||||
ExtractionVersion: row.ExtractionVersion.String, ConfirmedAt: confirmedAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func timeValueOrZero(value pgtype.Timestamptz) time.Time {
|
||||
if !value.Valid {
|
||||
return time.Time{}
|
||||
}
|
||||
return value.Time.UTC()
|
||||
}
|
||||
|
||||
func (repository privacyCohortRepository) RecordCandidateCardAccess(ctx context.Context, access domain.CandidateCardAccess) error {
|
||||
const location = "privacyCohortRepository.RecordCandidateCardAccess"
|
||||
if access.IsZero() || access.ActorID() == uuid.Nil {
|
||||
return fmt.Errorf("%s - access event is invalid: %w", location, domain.ErrInvalidCandidateCardAccess)
|
||||
}
|
||||
err := repository.queries.InsertCandidateCardAccessEvent(ctx, sqlc.InsertCandidateCardAccessEventParams{
|
||||
ID: pgUUID(access.ID()), CandidateID: pgUUID(access.CandidateID()),
|
||||
OrganizationID: pgUUID(access.OrganizationID()), ActorID: pgUUID(access.ActorID()),
|
||||
Kind: string(access.Kind()), FieldCodes: access.FieldCodes(), OccurredAt: pgTime(access.OccurredAt()),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - insert access audit: %w", location, markTransactionConflict(sanitizeConnectError(err)))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository privacyCohortRepository) ListCandidateCardAccess(
|
||||
ctx context.Context,
|
||||
query outbound.CandidateCardAccessListQuery,
|
||||
) (outbound.CandidateCardAccessListPage, error) {
|
||||
const location = "privacyCohortRepository.ListCandidateCardAccess"
|
||||
if query.CandidateID == uuid.Nil || query.Limit < 1 || query.Limit > outbound.MaxCandidateCardAccessPageSize {
|
||||
return outbound.CandidateCardAccessListPage{}, fmt.Errorf("%s - query is invalid: %w", location, domain.ErrInvalidCandidateCardAccess)
|
||||
}
|
||||
params := sqlc.ListCandidateCardAccessEventsParams{CandidateID: pgUUID(query.CandidateID), RowLimit: query.Limit + 1}
|
||||
if query.After != nil {
|
||||
if query.After.ID == uuid.Nil || query.After.OccurredAt.IsZero() {
|
||||
return outbound.CandidateCardAccessListPage{}, fmt.Errorf("%s - continuation position is invalid: %w", location, domain.ErrInvalidCandidateCardAccess)
|
||||
}
|
||||
params.AfterOccurredAt = pgTime(query.After.OccurredAt)
|
||||
params.AfterID = pgUUID(query.After.ID)
|
||||
}
|
||||
rows, err := repository.queries.ListCandidateCardAccessEvents(ctx, params)
|
||||
if err != nil {
|
||||
return outbound.CandidateCardAccessListPage{}, fmt.Errorf("%s - list access audit: %w", location, markTransactionConflict(sanitizeConnectError(err)))
|
||||
}
|
||||
return buildCandidateCardAccessPage(query.CandidateID, query.Limit, rows)
|
||||
}
|
||||
|
||||
func buildCandidateCardAccessPage(
|
||||
candidateID uuid.UUID,
|
||||
limit int32,
|
||||
rows []sqlc.ListCandidateCardAccessEventsRow,
|
||||
) (outbound.CandidateCardAccessListPage, error) {
|
||||
const location = "buildCandidateCardAccessPage"
|
||||
page := outbound.CandidateCardAccessListPage{
|
||||
Items: make([]domain.CandidateCardAccess, 0, min(len(rows), int(limit))),
|
||||
OrganizationNames: make(map[uuid.UUID]string),
|
||||
}
|
||||
if len(rows) > int(limit) {
|
||||
page.HasMore = true
|
||||
rows = rows[:limit]
|
||||
}
|
||||
for _, row := range rows {
|
||||
access, organizationID, err := restoreCandidateCardAccessEvent(row, candidateID)
|
||||
if err != nil {
|
||||
return outbound.CandidateCardAccessListPage{}, fmt.Errorf("%s - restore access event: %w", location, err)
|
||||
}
|
||||
page.Items = append(page.Items, access)
|
||||
page.OrganizationNames[organizationID] = row.OrganizationName
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func restoreCandidateCardAccessEvent(
|
||||
row sqlc.ListCandidateCardAccessEventsRow,
|
||||
expectedCandidateID uuid.UUID,
|
||||
) (domain.CandidateCardAccess, uuid.UUID, error) {
|
||||
const location = "restoreCandidateCardAccessEvent"
|
||||
id, err := privacyCohortUUID(row.ID)
|
||||
if err != nil {
|
||||
return domain.CandidateCardAccess{}, uuid.Nil, fmt.Errorf("%s - access identifier is invalid: %w", location, domain.ErrInvalidCandidateCardAccess)
|
||||
}
|
||||
candidateID, err := privacyCohortUUID(row.CandidateID)
|
||||
if err != nil || candidateID != expectedCandidateID {
|
||||
return domain.CandidateCardAccess{}, uuid.Nil, fmt.Errorf("%s - access candidate is invalid: %w", location, domain.ErrInvalidCandidateCardAccess)
|
||||
}
|
||||
organizationID, err := privacyCohortUUID(row.OrganizationID)
|
||||
if err != nil {
|
||||
return domain.CandidateCardAccess{}, uuid.Nil, fmt.Errorf("%s - access organization is invalid: %w", location, domain.ErrInvalidCandidateCardAccess)
|
||||
}
|
||||
access, err := domain.RestoreCandidateCardAccess(id, restoreCandidateCardAccessInput(row, candidateID, organizationID))
|
||||
if err != nil {
|
||||
return domain.CandidateCardAccess{}, uuid.Nil, fmt.Errorf("%s - access event values are invalid: %w", location, err)
|
||||
}
|
||||
return access, organizationID, nil
|
||||
}
|
||||
|
||||
func restoreCandidateCardAccessInput(
|
||||
row sqlc.ListCandidateCardAccessEventsRow,
|
||||
candidateID, organizationID uuid.UUID,
|
||||
) domain.CandidateCardAccessInput {
|
||||
var projectionFields []domain.CardField
|
||||
var contactFields []domain.ContactField
|
||||
for _, code := range row.FieldCodes {
|
||||
if field := domain.CardField(code); field.Valid() {
|
||||
projectionFields = append(projectionFields, field)
|
||||
continue
|
||||
}
|
||||
contactFields = append(contactFields, domain.ContactField(code))
|
||||
}
|
||||
input := domain.CandidateCardAccessInput{
|
||||
CandidateID: candidateID, OrganizationID: organizationID,
|
||||
ActorID: optionalUUID(row.ActorID), Kind: domain.CandidateCardAccessKind(row.Kind),
|
||||
ProjectionFields: projectionFields, ContactFields: contactFields,
|
||||
OccurredAt: timeValueOrZero(row.OccurredAt),
|
||||
}
|
||||
return input
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,365 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: assessment_availability.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const getAssessmentAvailabilityActiveAttempt = `-- name: GetAssessmentAvailabilityActiveAttempt :one
|
||||
SELECT id, expires_at
|
||||
FROM assessment_attempts
|
||||
WHERE user_id = $1
|
||||
AND specialization = $2
|
||||
AND kind IN ('root', 'corrective')
|
||||
AND state IN ('in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize')
|
||||
ORDER BY created_at DESC, id DESC
|
||||
LIMIT 1
|
||||
`
|
||||
|
||||
type GetAssessmentAvailabilityActiveAttemptParams struct {
|
||||
UserID pgtype.UUID
|
||||
Specialization pgtype.Text
|
||||
}
|
||||
|
||||
type GetAssessmentAvailabilityActiveAttemptRow struct {
|
||||
ID pgtype.UUID
|
||||
ExpiresAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Reads an active real attempt without taking the write lock used by create.
|
||||
// The availability GET never expires or otherwise mutates this row.
|
||||
func (q *Queries) GetAssessmentAvailabilityActiveAttempt(ctx context.Context, arg GetAssessmentAvailabilityActiveAttemptParams) (GetAssessmentAvailabilityActiveAttemptRow, error) {
|
||||
row := q.db.QueryRow(ctx, getAssessmentAvailabilityActiveAttempt, arg.UserID, arg.Specialization)
|
||||
var i GetAssessmentAvailabilityActiveAttemptRow
|
||||
err := row.Scan(&i.ID, &i.ExpiresAt)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getAssessmentRootQuotaAvailability = `-- name: GetAssessmentRootQuotaAvailability :one
|
||||
WITH eligible AS (
|
||||
SELECT attempt.id, attempt.created_at
|
||||
FROM assessment_attempts AS attempt
|
||||
LEFT JOIN assessment_attempt_results AS result
|
||||
ON result.attempt_id = attempt.id AND result.user_id = attempt.user_id
|
||||
WHERE attempt.user_id = $3
|
||||
AND attempt.kind = 'root'
|
||||
AND attempt.state <> 'insufficient_bank'
|
||||
AND attempt.created_at >= $4::timestamptz
|
||||
AND attempt.created_at <= $5::timestamptz
|
||||
AND COALESCE(result.result_snapshot->>'not_determined_reason', '')
|
||||
NOT IN ('insufficient_bank', 'sandbox_unavailable')
|
||||
), total AS (
|
||||
SELECT count(*)::bigint AS attempt_count FROM eligible
|
||||
)
|
||||
SELECT
|
||||
total.attempt_count,
|
||||
CASE WHEN total.attempt_count >= $1::bigint THEN (
|
||||
SELECT eligible.created_at
|
||||
+ make_interval(secs => $2::double precision)
|
||||
+ interval '1 microsecond'
|
||||
FROM eligible
|
||||
ORDER BY eligible.created_at, eligible.id
|
||||
LIMIT 1
|
||||
OFFSET (total.attempt_count - $1::bigint)
|
||||
) ELSE NULL::timestamptz END AS available_at
|
||||
FROM total
|
||||
`
|
||||
|
||||
type GetAssessmentRootQuotaAvailabilityParams struct {
|
||||
MaxAttempts int64
|
||||
WindowSeconds float64
|
||||
UserID pgtype.UUID
|
||||
Since pgtype.Timestamptz
|
||||
AsOf pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type GetAssessmentRootQuotaAvailabilityRow struct {
|
||||
AttemptCount int64
|
||||
AvailableAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Counts eligible root attempts in a policy window and computes the instant
|
||||
// at which one additional root slot opens. The microsecond adjustment matches
|
||||
// the creation predicate created_at >= since at PostgreSQL timestamp precision.
|
||||
func (q *Queries) GetAssessmentRootQuotaAvailability(ctx context.Context, arg GetAssessmentRootQuotaAvailabilityParams) (GetAssessmentRootQuotaAvailabilityRow, error) {
|
||||
row := q.db.QueryRow(ctx, getAssessmentRootQuotaAvailability,
|
||||
arg.MaxAttempts,
|
||||
arg.WindowSeconds,
|
||||
arg.UserID,
|
||||
arg.Since,
|
||||
arg.AsOf,
|
||||
)
|
||||
var i GetAssessmentRootQuotaAvailabilityRow
|
||||
err := row.Scan(&i.AttemptCount, &i.AvailableAt)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const listAssessmentAvailabilityRootSummaries = `-- name: ListAssessmentAvailabilityRootSummaries :many
|
||||
SELECT
|
||||
root.target_grade AS root_target_grade,
|
||||
root.created_at AS root_created_at,
|
||||
root.updated_at AS root_updated_at,
|
||||
root.expires_at AS root_expires_at,
|
||||
root.state AS root_state,
|
||||
root.outcome AS root_outcome,
|
||||
root.chain_deadline AS root_chain_deadline,
|
||||
latest.target_grade AS latest_target_grade,
|
||||
latest.updated_at AS latest_updated_at,
|
||||
latest.expires_at AS latest_expires_at,
|
||||
latest.state AS latest_state,
|
||||
latest.outcome AS latest_outcome,
|
||||
latest.chain_deadline AS latest_chain_deadline,
|
||||
COALESCE(latest_result.result_snapshot->>'not_determined_reason', '')::text AS latest_platform_error
|
||||
FROM assessment_attempts AS root
|
||||
JOIN LATERAL (
|
||||
SELECT attempt.id, attempt.user_id, attempt.kind, attempt.mode, attempt.state, attempt.outcome, attempt.bank_category, attempt.specialization, attempt.target_grade, attempt.task_language, attempt.root_attempt_id, attempt.product_policy_version_id, attempt.product_policy_version, attempt.grading_policy_version_id, attempt.opening_id, attempt.opening_manifest_sha256, attempt.training_binding_id, attempt.training_manifest_sha256, attempt.bank_version, attempt.algorithm_version, attempt.created_at, attempt.updated_at, attempt.expires_at, attempt.chain_deadline, attempt.idle_timeout_seconds, attempt.max_sessions, attempt.sessions_used, attempt.session_started_at, attempt.last_activity_at, attempt.version, attempt.ended_at
|
||||
FROM assessment_attempts AS attempt
|
||||
WHERE attempt.user_id = root.user_id
|
||||
AND attempt.root_attempt_id = root.id
|
||||
AND attempt.kind IN ('root', 'corrective')
|
||||
ORDER BY attempt.created_at DESC, attempt.id DESC
|
||||
LIMIT 1
|
||||
) AS latest ON true
|
||||
LEFT JOIN assessment_attempt_results AS root_result
|
||||
ON root_result.attempt_id = root.id AND root_result.user_id = root.user_id
|
||||
LEFT JOIN assessment_attempt_results AS latest_result
|
||||
ON latest_result.attempt_id = latest.id AND latest_result.user_id = latest.user_id
|
||||
WHERE root.user_id = $1
|
||||
AND root.specialization = $2
|
||||
AND root.kind = 'root'
|
||||
AND root.created_at >= $3::timestamptz
|
||||
AND root.state <> 'insufficient_bank'
|
||||
AND COALESCE(root_result.result_snapshot->>'not_determined_reason', '')
|
||||
NOT IN ('insufficient_bank', 'sandbox_unavailable')
|
||||
ORDER BY root.created_at DESC, root.id DESC
|
||||
`
|
||||
|
||||
type ListAssessmentAvailabilityRootSummariesParams struct {
|
||||
UserID pgtype.UUID
|
||||
Specialization pgtype.Text
|
||||
Since pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type ListAssessmentAvailabilityRootSummariesRow struct {
|
||||
RootTargetGrade pgtype.Text
|
||||
RootCreatedAt pgtype.Timestamptz
|
||||
RootUpdatedAt pgtype.Timestamptz
|
||||
RootExpiresAt pgtype.Timestamptz
|
||||
RootState string
|
||||
RootOutcome pgtype.Text
|
||||
RootChainDeadline pgtype.Timestamptz
|
||||
LatestTargetGrade pgtype.Text
|
||||
LatestUpdatedAt pgtype.Timestamptz
|
||||
LatestExpiresAt pgtype.Timestamptz
|
||||
LatestState string
|
||||
LatestOutcome pgtype.Text
|
||||
LatestChainDeadline pgtype.Timestamptz
|
||||
LatestPlatformError string
|
||||
}
|
||||
|
||||
// Reads roots within the policy horizon and the last header in each correction
|
||||
// chain. It deliberately omits frozen items, answers, and row locks.
|
||||
func (q *Queries) ListAssessmentAvailabilityRootSummaries(ctx context.Context, arg ListAssessmentAvailabilityRootSummariesParams) ([]ListAssessmentAvailabilityRootSummariesRow, error) {
|
||||
rows, err := q.db.Query(ctx, listAssessmentAvailabilityRootSummaries, arg.UserID, arg.Specialization, arg.Since)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ListAssessmentAvailabilityRootSummariesRow
|
||||
for rows.Next() {
|
||||
var i ListAssessmentAvailabilityRootSummariesRow
|
||||
if err := rows.Scan(
|
||||
&i.RootTargetGrade,
|
||||
&i.RootCreatedAt,
|
||||
&i.RootUpdatedAt,
|
||||
&i.RootExpiresAt,
|
||||
&i.RootState,
|
||||
&i.RootOutcome,
|
||||
&i.RootChainDeadline,
|
||||
&i.LatestTargetGrade,
|
||||
&i.LatestUpdatedAt,
|
||||
&i.LatestExpiresAt,
|
||||
&i.LatestState,
|
||||
&i.LatestOutcome,
|
||||
&i.LatestChainDeadline,
|
||||
&i.LatestPlatformError,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listAssessmentDisclosedFamilyKeys = `-- name: ListAssessmentDisclosedFamilyKeys :many
|
||||
WITH progress AS (
|
||||
SELECT
|
||||
attempt.id AS attempt_id,
|
||||
attempt.created_at,
|
||||
COALESCE(max(item.ordinal) FILTER (WHERE item.answered_at IS NOT NULL), 0) + 1 AS last_disclosed_ordinal
|
||||
FROM assessment_attempts AS attempt
|
||||
JOIN assessment_attempt_items AS item ON item.attempt_id = attempt.id
|
||||
WHERE attempt.user_id = $2
|
||||
AND attempt.kind IN ('root', 'corrective')
|
||||
AND attempt.expires_at > $1::timestamptz
|
||||
GROUP BY attempt.id
|
||||
), disclosed AS (
|
||||
SELECT
|
||||
item.family_key,
|
||||
CASE
|
||||
WHEN item.ordinal = 1 THEN progress.created_at
|
||||
ELSE previous.answered_at
|
||||
END AS disclosed_at
|
||||
FROM progress
|
||||
JOIN assessment_attempt_items AS item ON item.attempt_id = progress.attempt_id
|
||||
LEFT JOIN assessment_attempt_items AS previous
|
||||
ON previous.attempt_id = item.attempt_id AND previous.ordinal = item.ordinal - 1
|
||||
WHERE item.ordinal <= progress.last_disclosed_ordinal
|
||||
)
|
||||
SELECT DISTINCT disclosed.family_key
|
||||
FROM disclosed
|
||||
WHERE disclosed.disclosed_at > $1::timestamptz
|
||||
ORDER BY disclosed.family_key
|
||||
`
|
||||
|
||||
type ListAssessmentDisclosedFamilyKeysParams struct {
|
||||
Since pgtype.Timestamptz
|
||||
UserID pgtype.UUID
|
||||
}
|
||||
|
||||
// Counts family instances disclosed after the non-repeat boundary. The first
|
||||
// item is disclosed when the attempt is created; each later item is disclosed
|
||||
// when the preceding answer is accepted. This per-item timestamp prevents a
|
||||
// long-running attempt from making later items appear older than they are.
|
||||
// Counting the first unanswered item after expiry is conservative when the
|
||||
// final response was lost, while frozen future items remain excluded.
|
||||
func (q *Queries) ListAssessmentDisclosedFamilyKeys(ctx context.Context, arg ListAssessmentDisclosedFamilyKeysParams) ([]string, error) {
|
||||
rows, err := q.db.Query(ctx, listAssessmentDisclosedFamilyKeys, arg.Since, arg.UserID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []string
|
||||
for rows.Next() {
|
||||
var family_key string
|
||||
if err := rows.Scan(&family_key); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, family_key)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listCurrentAssessmentAvailabilitySelections = `-- name: ListCurrentAssessmentAvailabilitySelections :many
|
||||
WITH current_policy AS (
|
||||
SELECT id, version
|
||||
FROM policy_versions
|
||||
WHERE policy_key = 'product' AND effective_at <= $1::timestamptz
|
||||
ORDER BY version DESC
|
||||
LIMIT 1
|
||||
), current_openings AS (
|
||||
SELECT DISTINCT ON (category)
|
||||
id,
|
||||
category,
|
||||
policy_version_id,
|
||||
required_families,
|
||||
opened_at
|
||||
FROM assessment_category_openings
|
||||
ORDER BY category, opened_at DESC, id DESC
|
||||
)
|
||||
SELECT
|
||||
opening.id AS opening_id,
|
||||
opening.category,
|
||||
opening.policy_version_id,
|
||||
opening.required_families,
|
||||
COALESCE((
|
||||
SELECT count(DISTINCT family.family_key)::integer
|
||||
FROM assessment_families AS family
|
||||
WHERE family.category = opening.category AND family.lifecycle = 'published'
|
||||
), 0)::integer AS published_count,
|
||||
policy.id AS effective_policy_id,
|
||||
policy.version AS effective_policy_version,
|
||||
binding.specialization,
|
||||
binding.grade,
|
||||
binding.task_languages,
|
||||
binding.published_manifest_sha256,
|
||||
COALESCE((
|
||||
SELECT jsonb_agg(
|
||||
jsonb_build_object(
|
||||
'family_key', family.family_key,
|
||||
'version', family.version,
|
||||
'content_sha256', encode(family.content_sha256, 'hex')
|
||||
) ORDER BY family.family_key, family.version
|
||||
)
|
||||
FROM assessment_families AS family
|
||||
WHERE family.category = opening.category AND family.lifecycle = 'published'
|
||||
), '[]'::jsonb)::text AS published_manifest
|
||||
FROM current_openings AS opening
|
||||
JOIN assessment_category_catalog_bindings AS binding
|
||||
ON binding.opening_id = opening.id
|
||||
LEFT JOIN current_policy AS policy ON true
|
||||
ORDER BY binding.specialization, binding.grade, binding.task_languages, opening.category
|
||||
`
|
||||
|
||||
type ListCurrentAssessmentAvailabilitySelectionsRow struct {
|
||||
OpeningID pgtype.UUID
|
||||
Category string
|
||||
PolicyVersionID pgtype.UUID
|
||||
RequiredFamilies int32
|
||||
PublishedCount int32
|
||||
EffectivePolicyID pgtype.UUID
|
||||
EffectivePolicyVersion pgtype.Int4
|
||||
Specialization string
|
||||
Grade string
|
||||
TaskLanguages []string
|
||||
PublishedManifestSha256 []byte
|
||||
PublishedManifest string
|
||||
}
|
||||
|
||||
// Returns current reviewed grade/language bindings and the live published
|
||||
// family manifest at one caller-supplied database time. The adapter verifies
|
||||
// the pinned manifest hash before exposing only family keys.
|
||||
func (q *Queries) ListCurrentAssessmentAvailabilitySelections(ctx context.Context, asOf pgtype.Timestamptz) ([]ListCurrentAssessmentAvailabilitySelectionsRow, error) {
|
||||
rows, err := q.db.Query(ctx, listCurrentAssessmentAvailabilitySelections, asOf)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ListCurrentAssessmentAvailabilitySelectionsRow
|
||||
for rows.Next() {
|
||||
var i ListCurrentAssessmentAvailabilitySelectionsRow
|
||||
if err := rows.Scan(
|
||||
&i.OpeningID,
|
||||
&i.Category,
|
||||
&i.PolicyVersionID,
|
||||
&i.RequiredFamilies,
|
||||
&i.PublishedCount,
|
||||
&i.EffectivePolicyID,
|
||||
&i.EffectivePolicyVersion,
|
||||
&i.Specialization,
|
||||
&i.Grade,
|
||||
&i.TaskLanguages,
|
||||
&i.PublishedManifestSha256,
|
||||
&i.PublishedManifest,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: assessment_signals.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const countAssessmentSignalEvents = `-- name: CountAssessmentSignalEvents :one
|
||||
SELECT count(*)::bigint AS event_count
|
||||
FROM assessment_signal_events
|
||||
WHERE attempt_id = $1
|
||||
`
|
||||
|
||||
// Count events only for the already owner-locked attempt.
|
||||
func (q *Queries) CountAssessmentSignalEvents(ctx context.Context, attemptID pgtype.UUID) (int64, error) {
|
||||
row := q.db.QueryRow(ctx, countAssessmentSignalEvents, attemptID)
|
||||
var event_count int64
|
||||
err := row.Scan(&event_count)
|
||||
return event_count, err
|
||||
}
|
||||
|
||||
const countRecentAssessmentSignalOutcomes = `-- name: CountRecentAssessmentSignalOutcomes :one
|
||||
SELECT
|
||||
count(*)::bigint AS outcome_count,
|
||||
COALESCE(min(received_at), $1::timestamptz) AS oldest_at
|
||||
FROM assessment_signal_idempotency_outcomes
|
||||
WHERE
|
||||
attempt_id = $2
|
||||
AND received_at > $1
|
||||
`
|
||||
|
||||
type CountRecentAssessmentSignalOutcomesParams struct {
|
||||
Since pgtype.Timestamptz
|
||||
AttemptID pgtype.UUID
|
||||
}
|
||||
|
||||
type CountRecentAssessmentSignalOutcomesRow struct {
|
||||
OutcomeCount int64
|
||||
OldestAt interface{}
|
||||
}
|
||||
|
||||
// New outcomes share the generic idempotency row and are counted for the
|
||||
// attempt's rolling receipt window. Replays bypass this query in the usecase.
|
||||
func (q *Queries) CountRecentAssessmentSignalOutcomes(ctx context.Context, arg CountRecentAssessmentSignalOutcomesParams) (CountRecentAssessmentSignalOutcomesRow, error) {
|
||||
row := q.db.QueryRow(ctx, countRecentAssessmentSignalOutcomes, arg.Since, arg.AttemptID)
|
||||
var i CountRecentAssessmentSignalOutcomesRow
|
||||
err := row.Scan(&i.OutcomeCount, &i.OldestAt)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const deleteExpiredAssessmentSignalOutcome = `-- name: DeleteExpiredAssessmentSignalOutcome :exec
|
||||
DELETE FROM assessment_signal_idempotency_outcomes
|
||||
WHERE scope_hash = $1
|
||||
`
|
||||
|
||||
// The generic reservation has already established that a previous outcome is
|
||||
// expired before this child is removed and replaced in the same transaction.
|
||||
func (q *Queries) DeleteExpiredAssessmentSignalOutcome(ctx context.Context, scopeHash []byte) error {
|
||||
_, err := q.db.Exec(ctx, deleteExpiredAssessmentSignalOutcome, scopeHash)
|
||||
return err
|
||||
}
|
||||
|
||||
const getAssessmentSignalOutcome = `-- name: GetAssessmentSignalOutcome :one
|
||||
SELECT status, accepted_events, received_at
|
||||
FROM assessment_signal_idempotency_outcomes
|
||||
WHERE scope_hash = $1
|
||||
`
|
||||
|
||||
type GetAssessmentSignalOutcomeRow struct {
|
||||
Status string
|
||||
AcceptedEvents int32
|
||||
ReceivedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Read only the receipt associated with the reserved idempotency scope.
|
||||
func (q *Queries) GetAssessmentSignalOutcome(ctx context.Context, scopeHash []byte) (GetAssessmentSignalOutcomeRow, error) {
|
||||
row := q.db.QueryRow(ctx, getAssessmentSignalOutcome, scopeHash)
|
||||
var i GetAssessmentSignalOutcomeRow
|
||||
err := row.Scan(&i.Status, &i.AcceptedEvents, &i.ReceivedAt)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const insertAssessmentSignalBatch = `-- name: InsertAssessmentSignalBatch :exec
|
||||
INSERT INTO assessment_signal_batches (id, attempt_id, received_at, event_count)
|
||||
VALUES (
|
||||
$1,
|
||||
$2,
|
||||
$3,
|
||||
$4
|
||||
)
|
||||
`
|
||||
|
||||
type InsertAssessmentSignalBatchParams struct {
|
||||
ID pgtype.UUID
|
||||
AttemptID pgtype.UUID
|
||||
ReceivedAt pgtype.Timestamptz
|
||||
EventCount int32
|
||||
}
|
||||
|
||||
// The attempt row is already locked by the caller. Store a parent before its
|
||||
// bounded child events, in the same transaction as the immutable receipt.
|
||||
func (q *Queries) InsertAssessmentSignalBatch(ctx context.Context, arg InsertAssessmentSignalBatchParams) error {
|
||||
_, err := q.db.Exec(ctx, insertAssessmentSignalBatch,
|
||||
arg.ID,
|
||||
arg.AttemptID,
|
||||
arg.ReceivedAt,
|
||||
arg.EventCount,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const insertAssessmentSignalEvent = `-- name: InsertAssessmentSignalEvent :exec
|
||||
INSERT INTO assessment_signal_events (
|
||||
batch_id,
|
||||
attempt_id,
|
||||
ordinal,
|
||||
item_instance_id,
|
||||
kind,
|
||||
occurred_at,
|
||||
duration_ms,
|
||||
size_bytes
|
||||
) VALUES (
|
||||
$1,
|
||||
$2,
|
||||
$3,
|
||||
$4,
|
||||
$5,
|
||||
$6,
|
||||
$7::integer,
|
||||
$8::integer
|
||||
)
|
||||
`
|
||||
|
||||
type InsertAssessmentSignalEventParams struct {
|
||||
BatchID pgtype.UUID
|
||||
AttemptID pgtype.UUID
|
||||
Ordinal int32
|
||||
ItemInstanceID pgtype.UUID
|
||||
Kind string
|
||||
OccurredAt pgtype.Timestamptz
|
||||
DurationMs pgtype.Int4
|
||||
SizeBytes pgtype.Int4
|
||||
}
|
||||
|
||||
// Each inserted event is checked by the database guard against attempt state
|
||||
// and the aggregate capacity as a second line of defense.
|
||||
func (q *Queries) InsertAssessmentSignalEvent(ctx context.Context, arg InsertAssessmentSignalEventParams) error {
|
||||
_, err := q.db.Exec(ctx, insertAssessmentSignalEvent,
|
||||
arg.BatchID,
|
||||
arg.AttemptID,
|
||||
arg.Ordinal,
|
||||
arg.ItemInstanceID,
|
||||
arg.Kind,
|
||||
arg.OccurredAt,
|
||||
arg.DurationMs,
|
||||
arg.SizeBytes,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const insertAssessmentSignalOutcome = `-- name: InsertAssessmentSignalOutcome :exec
|
||||
INSERT INTO assessment_signal_idempotency_outcomes (
|
||||
scope_hash,
|
||||
attempt_id,
|
||||
status,
|
||||
accepted_events,
|
||||
received_at
|
||||
) VALUES (
|
||||
$1,
|
||||
$2,
|
||||
$3,
|
||||
$4,
|
||||
$5
|
||||
)
|
||||
`
|
||||
|
||||
type InsertAssessmentSignalOutcomeParams struct {
|
||||
ScopeHash []byte
|
||||
AttemptID pgtype.UUID
|
||||
Status string
|
||||
AcceptedEvents int32
|
||||
ReceivedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Save exactly one immutable response receipt for each live idempotency scope.
|
||||
func (q *Queries) InsertAssessmentSignalOutcome(ctx context.Context, arg InsertAssessmentSignalOutcomeParams) error {
|
||||
_, err := q.db.Exec(ctx, insertAssessmentSignalOutcome,
|
||||
arg.ScopeHash,
|
||||
arg.AttemptID,
|
||||
arg.Status,
|
||||
arg.AcceptedEvents,
|
||||
arg.ReceivedAt,
|
||||
)
|
||||
return err
|
||||
}
|
||||
@@ -871,6 +871,79 @@ func (q *Queries) ListCurrentContactConsentRecords(ctx context.Context, arg List
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const lockCurrentConsentForUse = `-- name: LockCurrentConsentForUse :one
|
||||
SELECT
|
||||
id,
|
||||
subject_id,
|
||||
purpose,
|
||||
text_version,
|
||||
text_hash,
|
||||
source,
|
||||
registration_version,
|
||||
organization_id,
|
||||
organization_name,
|
||||
field_set,
|
||||
invitation_id,
|
||||
invitation_terms_version,
|
||||
granted_at,
|
||||
revoked_at,
|
||||
revocation_source,
|
||||
'active'::text AS state
|
||||
FROM consent_records
|
||||
WHERE
|
||||
subject_id = $1
|
||||
AND purpose = 'c3'
|
||||
AND revoked_at IS NULL
|
||||
ORDER BY granted_at DESC, id DESC
|
||||
LIMIT 1
|
||||
FOR SHARE
|
||||
`
|
||||
|
||||
type LockCurrentConsentForUseRow struct {
|
||||
ID pgtype.UUID
|
||||
SubjectID pgtype.UUID
|
||||
Purpose string
|
||||
TextVersion string
|
||||
TextHash []byte
|
||||
Source string
|
||||
RegistrationVersion pgtype.Int8
|
||||
OrganizationID pgtype.UUID
|
||||
OrganizationName pgtype.Text
|
||||
FieldSet []string
|
||||
InvitationID pgtype.UUID
|
||||
InvitationTermsVersion pgtype.Int8
|
||||
GrantedAt pgtype.Timestamptz
|
||||
RevokedAt pgtype.Timestamptz
|
||||
RevocationSource pgtype.Text
|
||||
State string
|
||||
}
|
||||
|
||||
// Keeps the current C3 grant stable through a real assessment transaction.
|
||||
// Revocation updates this row and therefore waits until the caller commits.
|
||||
func (q *Queries) LockCurrentConsentForUse(ctx context.Context, subjectID pgtype.UUID) (LockCurrentConsentForUseRow, error) {
|
||||
row := q.db.QueryRow(ctx, lockCurrentConsentForUse, subjectID)
|
||||
var i LockCurrentConsentForUseRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.SubjectID,
|
||||
&i.Purpose,
|
||||
&i.TextVersion,
|
||||
&i.TextHash,
|
||||
&i.Source,
|
||||
&i.RegistrationVersion,
|
||||
&i.OrganizationID,
|
||||
&i.OrganizationName,
|
||||
&i.FieldSet,
|
||||
&i.InvitationID,
|
||||
&i.InvitationTermsVersion,
|
||||
&i.GrantedAt,
|
||||
&i.RevokedAt,
|
||||
&i.RevocationSource,
|
||||
&i.State,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const lockRegistrationConsentRecord = `-- name: LockRegistrationConsentRecord :one
|
||||
SELECT
|
||||
id,
|
||||
|
||||
@@ -16,6 +16,89 @@ type AccountDeletionRequest struct {
|
||||
CompletedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type AssessmentAttempt struct {
|
||||
ID pgtype.UUID
|
||||
UserID pgtype.UUID
|
||||
Kind string
|
||||
Mode string
|
||||
State string
|
||||
Outcome pgtype.Text
|
||||
BankCategory string
|
||||
Specialization pgtype.Text
|
||||
TargetGrade pgtype.Text
|
||||
TaskLanguage pgtype.Text
|
||||
RootAttemptID pgtype.UUID
|
||||
ProductPolicyVersionID pgtype.UUID
|
||||
ProductPolicyVersion int32
|
||||
GradingPolicyVersionID pgtype.UUID
|
||||
OpeningID pgtype.UUID
|
||||
OpeningManifestSha256 []byte
|
||||
TrainingBindingID pgtype.UUID
|
||||
TrainingManifestSha256 []byte
|
||||
BankVersion string
|
||||
AlgorithmVersion string
|
||||
CreatedAt pgtype.Timestamptz
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
ExpiresAt pgtype.Timestamptz
|
||||
ChainDeadline pgtype.Timestamptz
|
||||
IdleTimeoutSeconds int32
|
||||
MaxSessions int32
|
||||
SessionsUsed int32
|
||||
SessionStartedAt pgtype.Timestamptz
|
||||
LastActivityAt pgtype.Timestamptz
|
||||
Version int64
|
||||
EndedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type AssessmentAttemptIdempotencyOutcome struct {
|
||||
ScopeHash []byte
|
||||
Operation string
|
||||
StatusCode int16
|
||||
ProblemCode pgtype.Text
|
||||
ResponseSnapshot []byte
|
||||
ResponseSchemaVersion int16
|
||||
CreatedAt pgtype.Timestamptz
|
||||
PendingItemIds []pgtype.UUID
|
||||
}
|
||||
|
||||
type AssessmentAttemptItem struct {
|
||||
ID pgtype.UUID
|
||||
AttemptID pgtype.UUID
|
||||
Ordinal int32
|
||||
FamilyID pgtype.UUID
|
||||
FamilyKey string
|
||||
FamilyVersion int32
|
||||
FamilyContentSha256 []byte
|
||||
Variant []byte
|
||||
Answer []byte
|
||||
AnsweredAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type AssessmentAttemptResult struct {
|
||||
AttemptID pgtype.UUID
|
||||
UserID pgtype.UUID
|
||||
ResultSnapshot []byte
|
||||
SchemaVersion int16
|
||||
Kind string
|
||||
Mode string
|
||||
Outcome string
|
||||
ProductPolicyVersionID pgtype.UUID
|
||||
ProductPolicyVersion int32
|
||||
GradingPolicyVersionID pgtype.UUID
|
||||
OpeningID pgtype.UUID
|
||||
OpeningManifestSha256 []byte
|
||||
TrainingBindingID pgtype.UUID
|
||||
TrainingManifestSha256 []byte
|
||||
BankVersion string
|
||||
AlgorithmVersion string
|
||||
RationaleRule string
|
||||
PassMarkBasisPoints pgtype.Int4
|
||||
ScoredItems pgtype.Int2
|
||||
RawScore pgtype.Int2
|
||||
PassPoints pgtype.Int2
|
||||
DecidedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type AssessmentCategoryCatalogBinding struct {
|
||||
OpeningID pgtype.UUID
|
||||
Specialization string
|
||||
@@ -60,6 +143,62 @@ type AssessmentFamily struct {
|
||||
RetiredBy pgtype.Text
|
||||
}
|
||||
|
||||
type AssessmentSignalBatch struct {
|
||||
ID pgtype.UUID
|
||||
AttemptID pgtype.UUID
|
||||
ReceivedAt pgtype.Timestamptz
|
||||
EventCount int32
|
||||
}
|
||||
|
||||
type AssessmentSignalEvent struct {
|
||||
BatchID pgtype.UUID
|
||||
AttemptID pgtype.UUID
|
||||
Ordinal int32
|
||||
ItemInstanceID pgtype.UUID
|
||||
Kind string
|
||||
OccurredAt pgtype.Timestamptz
|
||||
DurationMs pgtype.Int4
|
||||
SizeBytes pgtype.Int4
|
||||
}
|
||||
|
||||
type AssessmentSignalIdempotencyOutcome struct {
|
||||
ScopeHash []byte
|
||||
AttemptID pgtype.UUID
|
||||
Status string
|
||||
AcceptedEvents int32
|
||||
ReceivedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type AssessmentTrainingBankBinding struct {
|
||||
ID pgtype.UUID
|
||||
Category string
|
||||
ProductPolicyVersionID pgtype.UUID
|
||||
ItemCount int32
|
||||
ManifestSha256 []byte
|
||||
FamilyManifest []byte
|
||||
ReviewedBy string
|
||||
CreatedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type AssessmentTrainingBankBindingFamily struct {
|
||||
BindingID pgtype.UUID
|
||||
Ordinal int32
|
||||
FamilyID pgtype.UUID
|
||||
FamilyKey string
|
||||
FamilyVersion int32
|
||||
ContentSha256 []byte
|
||||
}
|
||||
|
||||
type CandidateCardAccessEvent struct {
|
||||
ID pgtype.UUID
|
||||
CandidateID pgtype.UUID
|
||||
OrganizationID pgtype.UUID
|
||||
ActorID pgtype.UUID
|
||||
Kind string
|
||||
FieldCodes []string
|
||||
OccurredAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type CandidateEffectivePublication struct {
|
||||
UserID pgtype.UUID
|
||||
Fields []string
|
||||
@@ -405,6 +544,11 @@ type OrganizationNeed struct {
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type OrganizationNeedCreationResult struct {
|
||||
ScopeHash []byte
|
||||
Snapshot []byte
|
||||
}
|
||||
|
||||
type OrganizationNeedVersion struct {
|
||||
OrganizationID pgtype.UUID
|
||||
NeedID pgtype.UUID
|
||||
@@ -472,6 +616,57 @@ type Session struct {
|
||||
RevokedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type SupportCase struct {
|
||||
ID pgtype.UUID
|
||||
CaseNumber string
|
||||
OwnerID pgtype.UUID
|
||||
CaseType string
|
||||
Status string
|
||||
Description string
|
||||
ObjectType pgtype.Text
|
||||
ObjectID pgtype.UUID
|
||||
AssessmentSpecialization pgtype.Text
|
||||
AssessmentGrade pgtype.Text
|
||||
ComplaintReason pgtype.Text
|
||||
RubricVersion pgtype.Int4
|
||||
RubricOpeningID pgtype.UUID
|
||||
RubricPolicyVersionID pgtype.UUID
|
||||
TargetBusinessDays int32
|
||||
TargetDueAt pgtype.Timestamptz
|
||||
TargetAnsweredAt pgtype.Timestamptz
|
||||
TargetPolicyVersion int32
|
||||
TargetCalendarVersion int32
|
||||
DecisionOutcome pgtype.Text
|
||||
DecisionReason pgtype.Text
|
||||
DecisionAt pgtype.Timestamptz
|
||||
CreatedAt pgtype.Timestamptz
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type SupportCaseCreateOutcome struct {
|
||||
ScopeHash []byte
|
||||
OutcomeKind string
|
||||
CaseSnapshot []byte
|
||||
TargetWasLate pgtype.Bool
|
||||
CreatedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type SupportCaseEvent struct {
|
||||
CaseID pgtype.UUID
|
||||
Sequence int32
|
||||
EventKind string
|
||||
ActorKind string
|
||||
OccurredAt pgtype.Timestamptz
|
||||
Status pgtype.Text
|
||||
Message pgtype.Text
|
||||
}
|
||||
|
||||
type SupportCaseRequestEvent struct {
|
||||
ID int64
|
||||
OwnerID pgtype.UUID
|
||||
RequestedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type User struct {
|
||||
ID pgtype.UUID
|
||||
Email string
|
||||
|
||||
@@ -80,6 +80,21 @@ func (q *Queries) AdvanceOrganizationNeed(ctx context.Context, arg AdvanceOrgani
|
||||
return snapshot, err
|
||||
}
|
||||
|
||||
const getOrganizationNeedCreationResult = `-- name: GetOrganizationNeedCreationResult :one
|
||||
SELECT snapshot::text AS snapshot
|
||||
FROM organization_need_creation_results
|
||||
WHERE scope_hash = $1
|
||||
`
|
||||
|
||||
// Read only the immutable original response. The current need may have moved
|
||||
// to a later version since this result was created.
|
||||
func (q *Queries) GetOrganizationNeedCreationResult(ctx context.Context, scopeHash []byte) (string, error) {
|
||||
row := q.db.QueryRow(ctx, getOrganizationNeedCreationResult, scopeHash)
|
||||
var snapshot string
|
||||
err := row.Scan(&snapshot)
|
||||
return snapshot, err
|
||||
}
|
||||
|
||||
const insertOrganizationNeed = `-- name: InsertOrganizationNeed :exec
|
||||
INSERT INTO organization_needs (
|
||||
id,
|
||||
@@ -152,6 +167,85 @@ func (q *Queries) InsertOrganizationNeedVersion(ctx context.Context, arg InsertO
|
||||
return err
|
||||
}
|
||||
|
||||
const listOrganizationNeeds = `-- name: ListOrganizationNeeds :many
|
||||
SELECT
|
||||
need.organization_id,
|
||||
need.id AS need_id,
|
||||
need.current_version,
|
||||
need.requirements_version,
|
||||
need.created_at,
|
||||
need.updated_at,
|
||||
version.snapshot::text AS snapshot
|
||||
FROM organization_needs AS need
|
||||
INNER JOIN organization_need_versions AS version
|
||||
ON version.organization_id = need.organization_id
|
||||
AND version.need_id = need.id
|
||||
AND version.version = need.current_version
|
||||
WHERE
|
||||
need.organization_id = $1
|
||||
AND (
|
||||
$2::timestamptz IS NULL
|
||||
OR (need.created_at, need.id) < (
|
||||
$2::timestamptz,
|
||||
$3::uuid
|
||||
)
|
||||
)
|
||||
ORDER BY need.created_at DESC, need.id DESC
|
||||
LIMIT $4
|
||||
`
|
||||
|
||||
type ListOrganizationNeedsParams struct {
|
||||
OrganizationID pgtype.UUID
|
||||
AfterCreatedAt pgtype.Timestamptz
|
||||
AfterNeedID pgtype.UUID
|
||||
RowLimit int32
|
||||
}
|
||||
|
||||
type ListOrganizationNeedsRow struct {
|
||||
OrganizationID pgtype.UUID
|
||||
NeedID pgtype.UUID
|
||||
CurrentVersion int64
|
||||
RequirementsVersion int64
|
||||
CreatedAt pgtype.Timestamptz
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
Snapshot string
|
||||
}
|
||||
|
||||
// Read one bounded newest-first page of current needs. Both the organization
|
||||
// scope and the tuple cursor are applied before the limit.
|
||||
func (q *Queries) ListOrganizationNeeds(ctx context.Context, arg ListOrganizationNeedsParams) ([]ListOrganizationNeedsRow, error) {
|
||||
rows, err := q.db.Query(ctx, listOrganizationNeeds,
|
||||
arg.OrganizationID,
|
||||
arg.AfterCreatedAt,
|
||||
arg.AfterNeedID,
|
||||
arg.RowLimit,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ListOrganizationNeedsRow
|
||||
for rows.Next() {
|
||||
var i ListOrganizationNeedsRow
|
||||
if err := rows.Scan(
|
||||
&i.OrganizationID,
|
||||
&i.NeedID,
|
||||
&i.CurrentVersion,
|
||||
&i.RequirementsVersion,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
&i.Snapshot,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const readCurrentOrganizationNeed = `-- name: ReadCurrentOrganizationNeed :one
|
||||
SELECT
|
||||
need.organization_id,
|
||||
@@ -224,3 +318,23 @@ func (q *Queries) ReadOrganizationNeedVersion(ctx context.Context, arg ReadOrgan
|
||||
err := row.Scan(&snapshot)
|
||||
return snapshot, err
|
||||
}
|
||||
|
||||
const saveOrganizationNeedCreationResult = `-- name: SaveOrganizationNeedCreationResult :exec
|
||||
INSERT INTO organization_need_creation_results (scope_hash, snapshot)
|
||||
VALUES ($1, $2::jsonb)
|
||||
ON CONFLICT (scope_hash) DO UPDATE
|
||||
SET snapshot = excluded.snapshot
|
||||
`
|
||||
|
||||
type SaveOrganizationNeedCreationResultParams struct {
|
||||
ScopeHash []byte
|
||||
Snapshot []byte
|
||||
}
|
||||
|
||||
// The generic idempotency scope serializes retries. Replacing the child row
|
||||
// is safe only in the transaction that reserves an expired scope for a new
|
||||
// create; live retries read and return the stored response without writing.
|
||||
func (q *Queries) SaveOrganizationNeedCreationResult(ctx context.Context, arg SaveOrganizationNeedCreationResultParams) error {
|
||||
_, err := q.db.Exec(ctx, saveOrganizationNeedCreationResult, arg.ScopeHash, arg.Snapshot)
|
||||
return err
|
||||
}
|
||||
@@ -405,6 +405,63 @@ func (q *Queries) ListOrganizationsForUser(ctx context.Context, arg ListOrganiza
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const lockActiveMembership = `-- name: LockActiveMembership :one
|
||||
WITH locked_organization AS MATERIALIZED (
|
||||
SELECT organizations.id
|
||||
FROM organizations
|
||||
WHERE organizations.id = $2
|
||||
FOR SHARE
|
||||
)
|
||||
SELECT
|
||||
membership.id AS membership_id,
|
||||
membership.organization_id,
|
||||
membership.user_id,
|
||||
membership.role,
|
||||
membership.state,
|
||||
membership.created_at,
|
||||
membership.updated_at
|
||||
FROM memberships AS membership
|
||||
INNER JOIN locked_organization ON locked_organization.id = membership.organization_id
|
||||
WHERE
|
||||
membership.user_id = $1
|
||||
AND membership.state = 'active'
|
||||
FOR SHARE OF membership
|
||||
`
|
||||
|
||||
type LockActiveMembershipParams struct {
|
||||
UserID pgtype.UUID
|
||||
OrganizationID pgtype.UUID
|
||||
}
|
||||
|
||||
type LockActiveMembershipRow struct {
|
||||
MembershipID pgtype.UUID
|
||||
OrganizationID pgtype.UUID
|
||||
UserID pgtype.UUID
|
||||
Role string
|
||||
State string
|
||||
CreatedAt pgtype.Timestamptz
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Locks the organization first and then the active membership, using the
|
||||
// same order as organization profile writes. A company operation keeps both
|
||||
// share locks until its transaction commits, so a concurrent revocation
|
||||
// cannot authorize a write after it has committed.
|
||||
func (q *Queries) LockActiveMembership(ctx context.Context, arg LockActiveMembershipParams) (LockActiveMembershipRow, error) {
|
||||
row := q.db.QueryRow(ctx, lockActiveMembership, arg.UserID, arg.OrganizationID)
|
||||
var i LockActiveMembershipRow
|
||||
err := row.Scan(
|
||||
&i.MembershipID,
|
||||
&i.OrganizationID,
|
||||
&i.UserID,
|
||||
&i.Role,
|
||||
&i.State,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const saveOrganizationCreationResult = `-- name: SaveOrganizationCreationResult :exec
|
||||
INSERT INTO organization_creation_results (scope_hash, snapshot)
|
||||
VALUES ($1, $2)
|
||||
|
||||
@@ -11,6 +11,44 @@ import (
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const candidateCanSeeOrganization = `-- name: CandidateCanSeeOrganization :one
|
||||
SELECT organizations.id, organizations.name
|
||||
FROM organizations
|
||||
WHERE organizations.id = $1
|
||||
AND (
|
||||
EXISTS (
|
||||
SELECT 1 FROM candidate_card_access_events
|
||||
WHERE candidate_card_access_events.candidate_id = $2
|
||||
AND candidate_card_access_events.organization_id = organizations.id
|
||||
)
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM candidate_hidden_organizations
|
||||
WHERE candidate_hidden_organizations.user_id = $2
|
||||
AND candidate_hidden_organizations.organization_id = organizations.id
|
||||
)
|
||||
)
|
||||
`
|
||||
|
||||
type CandidateCanSeeOrganizationParams struct {
|
||||
OrganizationID pgtype.UUID
|
||||
UserID pgtype.UUID
|
||||
}
|
||||
|
||||
type CandidateCanSeeOrganizationRow struct {
|
||||
ID pgtype.UUID
|
||||
Name string
|
||||
}
|
||||
|
||||
// The candidate may name an organization in privacy settings only if that
|
||||
// organization already appears in their own access history or is already
|
||||
// hidden. Unknown and unseen organizations produce the same no-row result.
|
||||
func (q *Queries) CandidateCanSeeOrganization(ctx context.Context, arg CandidateCanSeeOrganizationParams) (CandidateCanSeeOrganizationRow, error) {
|
||||
row := q.db.QueryRow(ctx, candidateCanSeeOrganization, arg.OrganizationID, arg.UserID)
|
||||
var i CandidateCanSeeOrganizationRow
|
||||
err := row.Scan(&i.ID, &i.Name)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const countCandidateHiddenOrganizations = `-- name: CountCandidateHiddenOrganizations :one
|
||||
SELECT count(*) AS total
|
||||
FROM candidate_hidden_organizations
|
||||
@@ -79,6 +117,52 @@ func (q *Queries) GetCandidateHiddenOrganization(ctx context.Context, arg GetCan
|
||||
return i, err
|
||||
}
|
||||
|
||||
const insertCandidateCardAccessEvent = `-- name: InsertCandidateCardAccessEvent :exec
|
||||
INSERT INTO candidate_card_access_events (
|
||||
id,
|
||||
candidate_id,
|
||||
organization_id,
|
||||
actor_id,
|
||||
kind,
|
||||
field_codes,
|
||||
occurred_at
|
||||
) VALUES (
|
||||
$1,
|
||||
$2,
|
||||
$3,
|
||||
$4,
|
||||
$5,
|
||||
$6,
|
||||
$7
|
||||
)
|
||||
`
|
||||
|
||||
type InsertCandidateCardAccessEventParams struct {
|
||||
ID pgtype.UUID
|
||||
CandidateID pgtype.UUID
|
||||
OrganizationID pgtype.UUID
|
||||
ActorID pgtype.UUID
|
||||
Kind string
|
||||
FieldCodes []string
|
||||
OccurredAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Records a successfully authorized view after visibility and quota checks.
|
||||
// The audit contains only identities, the access kind, published field codes,
|
||||
// and time; it never receives the projection content, ranking, or filters.
|
||||
func (q *Queries) InsertCandidateCardAccessEvent(ctx context.Context, arg InsertCandidateCardAccessEventParams) error {
|
||||
_, err := q.db.Exec(ctx, insertCandidateCardAccessEvent,
|
||||
arg.ID,
|
||||
arg.CandidateID,
|
||||
arg.OrganizationID,
|
||||
arg.ActorID,
|
||||
arg.Kind,
|
||||
arg.FieldCodes,
|
||||
arg.OccurredAt,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const insertCandidateHiddenOrganization = `-- name: InsertCandidateHiddenOrganization :one
|
||||
INSERT INTO candidate_hidden_organizations (
|
||||
user_id,
|
||||
@@ -272,6 +356,88 @@ func (q *Queries) InsertCandidateSearchStatus(ctx context.Context, arg InsertCan
|
||||
return i, err
|
||||
}
|
||||
|
||||
const listCandidateCardAccessEvents = `-- name: ListCandidateCardAccessEvents :many
|
||||
SELECT
|
||||
candidate_card_access_events.id,
|
||||
candidate_card_access_events.candidate_id,
|
||||
candidate_card_access_events.organization_id,
|
||||
candidate_card_access_events.actor_id,
|
||||
candidate_card_access_events.kind,
|
||||
candidate_card_access_events.field_codes,
|
||||
candidate_card_access_events.occurred_at,
|
||||
organizations.name AS organization_name
|
||||
FROM candidate_card_access_events
|
||||
INNER JOIN organizations
|
||||
ON organizations.id = candidate_card_access_events.organization_id
|
||||
WHERE
|
||||
candidate_card_access_events.candidate_id = $1
|
||||
AND (
|
||||
$2::timestamptz IS NULL
|
||||
OR (candidate_card_access_events.occurred_at, candidate_card_access_events.id) < (
|
||||
$2::timestamptz,
|
||||
$3::uuid
|
||||
)
|
||||
)
|
||||
ORDER BY candidate_card_access_events.occurred_at DESC, candidate_card_access_events.id DESC
|
||||
LIMIT $4
|
||||
`
|
||||
|
||||
type ListCandidateCardAccessEventsParams struct {
|
||||
CandidateID pgtype.UUID
|
||||
AfterOccurredAt pgtype.Timestamptz
|
||||
AfterID pgtype.UUID
|
||||
RowLimit int32
|
||||
}
|
||||
|
||||
type ListCandidateCardAccessEventsRow struct {
|
||||
ID pgtype.UUID
|
||||
CandidateID pgtype.UUID
|
||||
OrganizationID pgtype.UUID
|
||||
ActorID pgtype.UUID
|
||||
Kind string
|
||||
FieldCodes []string
|
||||
OccurredAt pgtype.Timestamptz
|
||||
OrganizationName string
|
||||
}
|
||||
|
||||
// Lists only the current candidate's own access history. It deliberately
|
||||
// omits the employee, requested card fields, and search context. The privacy
|
||||
// read adapter resolves an organization name only through this recorded
|
||||
// access relation, which is already visible to the candidate.
|
||||
func (q *Queries) ListCandidateCardAccessEvents(ctx context.Context, arg ListCandidateCardAccessEventsParams) ([]ListCandidateCardAccessEventsRow, error) {
|
||||
rows, err := q.db.Query(ctx, listCandidateCardAccessEvents,
|
||||
arg.CandidateID,
|
||||
arg.AfterOccurredAt,
|
||||
arg.AfterID,
|
||||
arg.RowLimit,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ListCandidateCardAccessEventsRow
|
||||
for rows.Next() {
|
||||
var i ListCandidateCardAccessEventsRow
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.CandidateID,
|
||||
&i.OrganizationID,
|
||||
&i.ActorID,
|
||||
&i.Kind,
|
||||
&i.FieldCodes,
|
||||
&i.OccurredAt,
|
||||
&i.OrganizationName,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listCandidateHiddenOrganizations = `-- name: ListCandidateHiddenOrganizations :many
|
||||
SELECT
|
||||
candidate_hidden_organizations.organization_id,
|
||||
@@ -480,8 +646,88 @@ func (q *Queries) LockCurrentC2Record(ctx context.Context, subjectID pgtype.UUID
|
||||
return id, err
|
||||
}
|
||||
|
||||
const readCandidatePublication = `-- name: ReadCandidatePublication :one
|
||||
const readCandidatePrivacySettings = `-- name: ReadCandidatePrivacySettings :one
|
||||
|
||||
SELECT
|
||||
users.id AS user_id,
|
||||
candidate_publications.state AS publication_state,
|
||||
candidate_publications.fields AS publication_fields,
|
||||
candidate_publications.consent_record_id AS publication_consent_record_id,
|
||||
candidate_publications.published_at AS publication_published_at,
|
||||
candidate_publications.closed_at AS publication_closed_at,
|
||||
candidate_publications.version AS publication_version,
|
||||
consent_records.revoked_at AS publication_consent_revoked_at,
|
||||
candidate_search_statuses.status AS search_status,
|
||||
candidate_search_statuses.confirmed_at AS search_confirmed_at,
|
||||
candidate_search_statuses.lapses_at AS search_lapses_at,
|
||||
candidate_search_statuses.policy_version_id AS search_policy_version_id,
|
||||
candidate_search_statuses.version AS search_version,
|
||||
(
|
||||
SELECT count(*)
|
||||
FROM candidate_hidden_organizations
|
||||
WHERE candidate_hidden_organizations.user_id = users.id
|
||||
) AS hidden_count
|
||||
FROM users
|
||||
LEFT JOIN candidate_publications
|
||||
ON candidate_publications.user_id = users.id
|
||||
LEFT JOIN consent_records
|
||||
ON consent_records.id = candidate_publications.consent_record_id
|
||||
LEFT JOIN candidate_search_statuses
|
||||
ON candidate_search_statuses.user_id = users.id
|
||||
WHERE users.id = $1
|
||||
`
|
||||
|
||||
type ReadCandidatePrivacySettingsRow struct {
|
||||
UserID pgtype.UUID
|
||||
PublicationState pgtype.Text
|
||||
PublicationFields []string
|
||||
PublicationConsentRecordID pgtype.UUID
|
||||
PublicationPublishedAt pgtype.Timestamptz
|
||||
PublicationClosedAt pgtype.Timestamptz
|
||||
PublicationVersion pgtype.Int8
|
||||
PublicationConsentRevokedAt pgtype.Timestamptz
|
||||
SearchStatus pgtype.Text
|
||||
SearchConfirmedAt pgtype.Timestamptz
|
||||
SearchLapsesAt pgtype.Timestamptz
|
||||
SearchPolicyVersionID pgtype.UUID
|
||||
SearchVersion pgtype.Int8
|
||||
HiddenCount int64
|
||||
}
|
||||
|
||||
// Queries of the candidate visibility settings: the publication of
|
||||
// the card, the search status, the hidden organizations, and the history of
|
||||
// these settings. Every statement is scoped by the candidate's user_id, and
|
||||
// no statement selects another account's row. No statement reads or writes a
|
||||
// profile value, a name, or a contact. A candidate with no row is closed, not
|
||||
// looking, and hides nobody; no statement creates a row except an explicit
|
||||
// act of the candidate.
|
||||
// Reads the candidate-owned settings and hidden count from one statement
|
||||
// snapshot. Missing setting rows are restored as the closed/not-looking
|
||||
// defaults in the adapter. The account row scopes the result but does not
|
||||
// expose private profile values.
|
||||
func (q *Queries) ReadCandidatePrivacySettings(ctx context.Context, userID pgtype.UUID) (ReadCandidatePrivacySettingsRow, error) {
|
||||
row := q.db.QueryRow(ctx, readCandidatePrivacySettings, userID)
|
||||
var i ReadCandidatePrivacySettingsRow
|
||||
err := row.Scan(
|
||||
&i.UserID,
|
||||
&i.PublicationState,
|
||||
&i.PublicationFields,
|
||||
&i.PublicationConsentRecordID,
|
||||
&i.PublicationPublishedAt,
|
||||
&i.PublicationClosedAt,
|
||||
&i.PublicationVersion,
|
||||
&i.PublicationConsentRevokedAt,
|
||||
&i.SearchStatus,
|
||||
&i.SearchConfirmedAt,
|
||||
&i.SearchLapsesAt,
|
||||
&i.SearchPolicyVersionID,
|
||||
&i.SearchVersion,
|
||||
&i.HiddenCount,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const readCandidatePublication = `-- name: ReadCandidatePublication :one
|
||||
SELECT
|
||||
candidate_publications.user_id,
|
||||
candidate_publications.state,
|
||||
@@ -512,13 +758,6 @@ type ReadCandidatePublicationRow struct {
|
||||
ConsentRevokedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Queries of the candidate visibility settings: the publication of
|
||||
// the card, the search status, the hidden organizations, and the history of
|
||||
// these settings. Every statement is scoped by the candidate's user_id, and
|
||||
// no statement selects another account's row. No statement reads or writes a
|
||||
// profile value, a name, or a contact. A candidate with no row is closed, not
|
||||
// looking, and hides nobody; no statement creates a row except an explicit
|
||||
// act of the candidate.
|
||||
// Reads the publication with the revocation state of the C2 record behind it
|
||||
// in one statement, so the stored setting and the ledger come from one
|
||||
// snapshot. The effective state is computed from them: published only while
|
||||
|
||||
@@ -0,0 +1,330 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: privacy_cohort.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const listVisibleCandidateViewSources = `-- name: ListVisibleCandidateViewSources :many
|
||||
SELECT
|
||||
effective.user_id,
|
||||
effective.fields,
|
||||
claim.kind,
|
||||
claim.ordinal,
|
||||
CASE
|
||||
WHEN claim.kind = 'experience' THEN jsonb_build_object(
|
||||
'employer_name', NULL::text,
|
||||
'specialization', claim.value ->> 'specialization',
|
||||
'started_on', claim.value ->> 'started_on',
|
||||
'ended_on', claim.value -> 'ended_on',
|
||||
'summary', NULL::text
|
||||
)
|
||||
ELSE claim.value
|
||||
END AS safe_value,
|
||||
claim.status,
|
||||
claim.origin,
|
||||
claim.trust_level,
|
||||
claim.extraction_version,
|
||||
claim.confirmed_at,
|
||||
COALESCE(questionnaire.work_formats, '{}'::text[]) AS work_formats,
|
||||
COALESCE(
|
||||
(
|
||||
SELECT jsonb_agg(
|
||||
jsonb_build_object(
|
||||
'first_index', overlap.first_index,
|
||||
'second_index', overlap.second_index,
|
||||
'first_period', jsonb_build_object(
|
||||
'started_on', overlap.first_started_on,
|
||||
'ended_on', overlap.first_ended_on
|
||||
),
|
||||
'second_period', jsonb_build_object(
|
||||
'started_on', overlap.second_started_on,
|
||||
'ended_on', overlap.second_ended_on
|
||||
)
|
||||
) ORDER BY overlap.first_index, overlap.second_index
|
||||
)::text
|
||||
FROM candidate_profile_overlap_confirmations AS overlap
|
||||
WHERE overlap.user_id = effective.user_id
|
||||
),
|
||||
'[]'::text
|
||||
) AS parallel_period_acknowledgements
|
||||
FROM candidate_effective_publications AS effective
|
||||
LEFT JOIN candidate_profile_claims AS claim
|
||||
ON claim.user_id = effective.user_id
|
||||
AND claim.kind IN ('stack', 'role', 'experience')
|
||||
LEFT JOIN candidate_questionnaires AS questionnaire
|
||||
ON questionnaire.user_id = effective.user_id
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM candidate_hidden_organizations AS hidden
|
||||
WHERE hidden.user_id = effective.user_id
|
||||
AND hidden.organization_id = $1
|
||||
)
|
||||
ORDER BY effective.user_id, claim.kind, claim.ordinal
|
||||
`
|
||||
|
||||
type ListVisibleCandidateViewSourcesRow struct {
|
||||
UserID pgtype.UUID
|
||||
Fields []string
|
||||
Kind pgtype.Text
|
||||
Ordinal pgtype.Int2
|
||||
SafeValue interface{}
|
||||
Status pgtype.Text
|
||||
Origin pgtype.Text
|
||||
TrustLevel pgtype.Int2
|
||||
ExtractionVersion pgtype.Text
|
||||
ConfirmedAt pgtype.Timestamptz
|
||||
WorkFormats []string
|
||||
ParallelPeriodAcknowledgements interface{}
|
||||
}
|
||||
|
||||
// Organization-facing anonymous candidate projection inputs. The calling
|
||||
// usecase has already authorized the active organization membership. This
|
||||
// single statement snapshot filters both revoked/unpublished C2 states and
|
||||
// candidates hidden from this organization before any profile value is read.
|
||||
// The projection reads only stack, declared role, and experience dates. It
|
||||
// deliberately excludes names, contacts, salary, location, soft skills,
|
||||
// employer names, summaries, and imported excerpts.
|
||||
func (q *Queries) ListVisibleCandidateViewSources(ctx context.Context, organizationID pgtype.UUID) ([]ListVisibleCandidateViewSourcesRow, error) {
|
||||
rows, err := q.db.Query(ctx, listVisibleCandidateViewSources, organizationID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ListVisibleCandidateViewSourcesRow
|
||||
for rows.Next() {
|
||||
var i ListVisibleCandidateViewSourcesRow
|
||||
if err := rows.Scan(
|
||||
&i.UserID,
|
||||
&i.Fields,
|
||||
&i.Kind,
|
||||
&i.Ordinal,
|
||||
&i.SafeValue,
|
||||
&i.Status,
|
||||
&i.Origin,
|
||||
&i.TrustLevel,
|
||||
&i.ExtractionVersion,
|
||||
&i.ConfirmedAt,
|
||||
&i.WorkFormats,
|
||||
&i.ParallelPeriodAcknowledgements,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const lockCandidateAccountForView = `-- name: LockCandidateAccountForView :one
|
||||
SELECT users.id
|
||||
FROM users
|
||||
WHERE users.id = $1
|
||||
FOR SHARE
|
||||
`
|
||||
|
||||
// Lock the account before an organization checks candidate visibility. The
|
||||
// hidden-organization insert trigger takes FOR NO KEY UPDATE on this row, so
|
||||
// a hide either commits before the later visibility recheck or waits for the
|
||||
// read transaction to finish.
|
||||
func (q *Queries) LockCandidateAccountForView(ctx context.Context, candidateID pgtype.UUID) (pgtype.UUID, error) {
|
||||
row := q.db.QueryRow(ctx, lockCandidateAccountForView, candidateID)
|
||||
var id pgtype.UUID
|
||||
err := row.Scan(&id)
|
||||
return id, err
|
||||
}
|
||||
|
||||
const lockCurrentC2ForView = `-- name: LockCurrentC2ForView :one
|
||||
SELECT consent_records.id
|
||||
FROM consent_records
|
||||
WHERE
|
||||
consent_records.subject_id = $1
|
||||
AND consent_records.purpose = 'c2'
|
||||
AND consent_records.revoked_at IS NULL
|
||||
ORDER BY consent_records.granted_at DESC, consent_records.id DESC
|
||||
LIMIT 1
|
||||
FOR SHARE
|
||||
`
|
||||
|
||||
// Lock the current C2 before locking the publication. C2 revocation updates
|
||||
// this row before it locks the publication, so preserving this order avoids
|
||||
// a lock inversion and makes the current consent stable through the read.
|
||||
func (q *Queries) LockCurrentC2ForView(ctx context.Context, candidateID pgtype.UUID) (pgtype.UUID, error) {
|
||||
row := q.db.QueryRow(ctx, lockCurrentC2ForView, candidateID)
|
||||
var id pgtype.UUID
|
||||
err := row.Scan(&id)
|
||||
return id, err
|
||||
}
|
||||
|
||||
const lockPublicationForCandidatePreview = `-- name: LockPublicationForCandidatePreview :one
|
||||
SELECT candidate_publications.user_id
|
||||
FROM candidate_publications
|
||||
INNER JOIN consent_records
|
||||
ON consent_records.id = candidate_publications.consent_record_id
|
||||
WHERE
|
||||
candidate_publications.user_id = $1
|
||||
AND candidate_publications.state = 'published'
|
||||
AND consent_records.subject_id = candidate_publications.user_id
|
||||
AND consent_records.purpose = 'c2'
|
||||
AND consent_records.revoked_at IS NULL
|
||||
FOR SHARE OF candidate_publications, consent_records
|
||||
`
|
||||
|
||||
// Lock a candidate's current publication for the private preview. This has
|
||||
// no organization context and never enters the employer read quota or audit.
|
||||
func (q *Queries) LockPublicationForCandidatePreview(ctx context.Context, candidateID pgtype.UUID) (pgtype.UUID, error) {
|
||||
row := q.db.QueryRow(ctx, lockPublicationForCandidatePreview, candidateID)
|
||||
var user_id pgtype.UUID
|
||||
err := row.Scan(&user_id)
|
||||
return user_id, err
|
||||
}
|
||||
|
||||
const lockVisiblePublicationForView = `-- name: LockVisiblePublicationForView :one
|
||||
SELECT candidate_publications.user_id
|
||||
FROM candidate_publications
|
||||
INNER JOIN consent_records
|
||||
ON consent_records.id = candidate_publications.consent_record_id
|
||||
WHERE
|
||||
candidate_publications.user_id = $1
|
||||
AND candidate_publications.state = 'published'
|
||||
AND candidate_publications.consent_record_id = $2
|
||||
AND consent_records.subject_id = candidate_publications.user_id
|
||||
AND consent_records.purpose = 'c2'
|
||||
AND consent_records.revoked_at IS NULL
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM candidate_hidden_organizations AS hidden
|
||||
WHERE
|
||||
hidden.user_id = candidate_publications.user_id
|
||||
AND hidden.organization_id = $3
|
||||
)
|
||||
FOR SHARE OF candidate_publications, consent_records
|
||||
`
|
||||
|
||||
type LockVisiblePublicationForViewParams struct {
|
||||
CandidateID pgtype.UUID
|
||||
ConsentRecordID pgtype.UUID
|
||||
OrganizationID pgtype.UUID
|
||||
}
|
||||
|
||||
// Lock and recheck one candidate's exact current publication only after the
|
||||
// active C2 row is share-locked. No row includes unpublished, revoked, stale
|
||||
// publication, and organization-hidden states.
|
||||
func (q *Queries) LockVisiblePublicationForView(ctx context.Context, arg LockVisiblePublicationForViewParams) (pgtype.UUID, error) {
|
||||
row := q.db.QueryRow(ctx, lockVisiblePublicationForView, arg.CandidateID, arg.ConsentRecordID, arg.OrganizationID)
|
||||
var user_id pgtype.UUID
|
||||
err := row.Scan(&user_id)
|
||||
return user_id, err
|
||||
}
|
||||
|
||||
const readCandidateViewSourceForPreview = `-- name: ReadCandidateViewSourceForPreview :many
|
||||
SELECT
|
||||
effective.user_id,
|
||||
effective.fields,
|
||||
claim.kind,
|
||||
claim.ordinal,
|
||||
CASE
|
||||
WHEN claim.kind = 'experience' THEN jsonb_build_object(
|
||||
'employer_name', NULL::text,
|
||||
'specialization', claim.value ->> 'specialization',
|
||||
'started_on', claim.value ->> 'started_on',
|
||||
'ended_on', claim.value -> 'ended_on',
|
||||
'summary', NULL::text
|
||||
)
|
||||
ELSE claim.value
|
||||
END AS safe_value,
|
||||
claim.status,
|
||||
claim.origin,
|
||||
claim.trust_level,
|
||||
claim.extraction_version,
|
||||
claim.confirmed_at,
|
||||
COALESCE(questionnaire.work_formats, '{}'::text[]) AS work_formats,
|
||||
COALESCE(
|
||||
(
|
||||
SELECT jsonb_agg(
|
||||
jsonb_build_object(
|
||||
'first_index', overlap.first_index,
|
||||
'second_index', overlap.second_index,
|
||||
'first_period', jsonb_build_object(
|
||||
'started_on', overlap.first_started_on,
|
||||
'ended_on', overlap.first_ended_on
|
||||
),
|
||||
'second_period', jsonb_build_object(
|
||||
'started_on', overlap.second_started_on,
|
||||
'ended_on', overlap.second_ended_on
|
||||
)
|
||||
) ORDER BY overlap.first_index, overlap.second_index
|
||||
)::text
|
||||
FROM candidate_profile_overlap_confirmations AS overlap
|
||||
WHERE overlap.user_id = effective.user_id
|
||||
),
|
||||
'[]'::text
|
||||
) AS parallel_period_acknowledgements
|
||||
FROM candidate_effective_publications AS effective
|
||||
LEFT JOIN candidate_profile_claims AS claim
|
||||
ON claim.user_id = effective.user_id
|
||||
AND claim.kind IN ('stack', 'role', 'experience')
|
||||
LEFT JOIN candidate_questionnaires AS questionnaire
|
||||
ON questionnaire.user_id = effective.user_id
|
||||
WHERE effective.user_id = $1
|
||||
ORDER BY effective.user_id, claim.kind, claim.ordinal
|
||||
`
|
||||
|
||||
type ReadCandidateViewSourceForPreviewRow struct {
|
||||
UserID pgtype.UUID
|
||||
Fields []string
|
||||
Kind pgtype.Text
|
||||
Ordinal pgtype.Int2
|
||||
SafeValue interface{}
|
||||
Status pgtype.Text
|
||||
Origin pgtype.Text
|
||||
TrustLevel pgtype.Int2
|
||||
ExtractionVersion pgtype.Text
|
||||
ConfirmedAt pgtype.Timestamptz
|
||||
WorkFormats []string
|
||||
ParallelPeriodAcknowledgements interface{}
|
||||
}
|
||||
|
||||
// Read the candidate's current private projection inputs after the caller
|
||||
// locks its active C2 and publication. It selects only fields allowed in the
|
||||
// anonymous-card projection and is never used for employer visibility.
|
||||
func (q *Queries) ReadCandidateViewSourceForPreview(ctx context.Context, candidateID pgtype.UUID) ([]ReadCandidateViewSourceForPreviewRow, error) {
|
||||
rows, err := q.db.Query(ctx, readCandidateViewSourceForPreview, candidateID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ReadCandidateViewSourceForPreviewRow
|
||||
for rows.Next() {
|
||||
var i ReadCandidateViewSourceForPreviewRow
|
||||
if err := rows.Scan(
|
||||
&i.UserID,
|
||||
&i.Fields,
|
||||
&i.Kind,
|
||||
&i.Ordinal,
|
||||
&i.SafeValue,
|
||||
&i.Status,
|
||||
&i.Origin,
|
||||
&i.TrustLevel,
|
||||
&i.ExtractionVersion,
|
||||
&i.ConfirmedAt,
|
||||
&i.WorkFormats,
|
||||
&i.ParallelPeriodAcknowledgements,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
@@ -60,6 +60,10 @@ type Querier interface {
|
||||
// redacts the bodies of a token mail like any other cancellation. now is the
|
||||
// application clock.
|
||||
CancelUnreadableDelivery(ctx context.Context, arg CancelUnreadableDeliveryParams) (int64, error)
|
||||
// The candidate may name an organization in privacy settings only if that
|
||||
// organization already appears in their own access history or is already
|
||||
// hidden. Unknown and unseen organizations produce the same no-row result.
|
||||
CandidateCanSeeOrganization(ctx context.Context, arg CandidateCanSeeOrganizationParams) (CandidateCanSeeOrganizationRow, error)
|
||||
// Claims the most overdue delivery that the sending worker may send, in one
|
||||
// statement: a pending, waiting_quota, or scheduled unknown delivery of the service mail kinds
|
||||
// (the literals match the predicate of deliveries_due_idx, so an idle poll
|
||||
@@ -118,6 +122,8 @@ type Querier interface {
|
||||
// returned registration version in the same transaction, rolled back when it
|
||||
// matches no row.
|
||||
ConsumeEmailToken(ctx context.Context, arg ConsumeEmailTokenParams) (ConsumeEmailTokenRow, error)
|
||||
// Count events only for the already owner-locked attempt.
|
||||
CountAssessmentSignalEvents(ctx context.Context, attemptID pgtype.UUID) (int64, error)
|
||||
// Counts the hiding records of one candidate for the settings read.
|
||||
CountCandidateHiddenOrganizations(ctx context.Context, userID pgtype.UUID) (int64, error)
|
||||
CountCompanyCardViewQuotaWindow(ctx context.Context, arg CountCompanyCardViewQuotaWindowParams) (CountCompanyCardViewQuotaWindowRow, error)
|
||||
@@ -125,10 +131,22 @@ type Querier interface {
|
||||
// Counts the families of a category that have at least one published
|
||||
// version, however many versions each has.
|
||||
CountPublishedAssessmentFamilies(ctx context.Context, category string) (int32, error)
|
||||
// New outcomes share the generic idempotency row and are counted for the
|
||||
// attempt's rolling receipt window. Replays bypass this query in the usecase.
|
||||
CountRecentAssessmentSignalOutcomes(ctx context.Context, arg CountRecentAssessmentSignalOutcomesParams) (CountRecentAssessmentSignalOutcomesRow, error)
|
||||
// Counts root attempts only; the caller applies the effective policy's
|
||||
// configured window and the product's approved accounting scope.
|
||||
CountRootAssessmentAttemptsSince(ctx context.Context, arg CountRootAssessmentAttemptsSinceParams) (int64, error)
|
||||
// The strict lower boundary means an event exactly one window old no longer
|
||||
// counts. The use case derives Retry-After from first_in_window.
|
||||
CountSupportCaseRequestEvents(ctx context.Context, arg CountSupportCaseRequestEventsParams) (CountSupportCaseRequestEventsRow, error)
|
||||
// Creates one durable deletion request per subject until a worker completes it.
|
||||
// The caller appends the matching outbox intent in the same transaction only
|
||||
// when this insert returns a row.
|
||||
CreateAccountDeletionRequest(ctx context.Context, arg CreateAccountDeletionRequestParams) (CreateAccountDeletionRequestRow, error)
|
||||
// A newly reserved generic idempotency window can replace an expired typed
|
||||
// outcome before the new immutable response is inserted.
|
||||
DeleteAssessmentAttemptIdempotencyOutcome(ctx context.Context, scopeHash []byte) error
|
||||
// Lifts one hiding. No row returns when the organization was not hidden, so
|
||||
// the caller writes the history event only for a real deletion and answers
|
||||
// 204 either way.
|
||||
@@ -142,9 +160,15 @@ type Querier interface {
|
||||
// Replaces all specialization answers after the version row advanced in the
|
||||
// same transaction.
|
||||
DeleteCandidateQuestionnaireSpecializations(ctx context.Context, userID pgtype.UUID) error
|
||||
// The generic reservation has already established that a previous outcome is
|
||||
// expired before this child is removed and replaced in the same transaction.
|
||||
DeleteExpiredAssessmentSignalOutcome(ctx context.Context, scopeHash []byte) error
|
||||
DeleteExpiredCompanyCardViewQuotaUsage(ctx context.Context, arg DeleteExpiredCompanyCardViewQuotaUsageParams) (int64, error)
|
||||
DeleteMailRequest(ctx context.Context, id pgtype.UUID) (int64, error)
|
||||
DeleteOrganizationRepresentatives(ctx context.Context, organizationID pgtype.UUID) error
|
||||
// No raw Idempotency-Key or request body reaches these statements. Failure
|
||||
// responses pass {} as case_snapshot and the CASE stores SQL NULL instead.
|
||||
DeleteSupportCaseCreateOutcome(ctx context.Context, scopeHash []byte) error
|
||||
// Deletes one batch of accounts that stayed unverified since before cutoff,
|
||||
// oldest first, with their tokens, sessions, mail requests, mail deliveries
|
||||
// (and through the deliveries their attempts), and consent records. The
|
||||
@@ -190,9 +214,30 @@ type Querier interface {
|
||||
// Reads the durable active deletion request when an earlier request already
|
||||
// exists. A completed request does not suppress a later explicit request.
|
||||
GetActiveAccountDeletionRequest(ctx context.Context, subjectID pgtype.UUID) (GetActiveAccountDeletionRequestRow, error)
|
||||
// Locks the active real attempt after LockAssessmentAttemptScope.
|
||||
GetActiveAssessmentAttemptForSpecialization(ctx context.Context, arg GetActiveAssessmentAttemptForSpecializationParams) (AssessmentAttempt, error)
|
||||
GetActiveSessionByTokenHash(ctx context.Context, arg GetActiveSessionByTokenHashParams) (Session, error)
|
||||
// Locks the one active express attempt after LockAssessmentAttemptScope.
|
||||
GetActiveTrainingAssessmentAttempt(ctx context.Context, userID pgtype.UUID) (AssessmentAttempt, error)
|
||||
// Returns a full private attempt only to its candidate.
|
||||
GetAssessmentAttemptForCandidate(ctx context.Context, arg GetAssessmentAttemptForCandidateParams) (AssessmentAttempt, error)
|
||||
GetAssessmentAttemptIdempotencyOutcome(ctx context.Context, scopeHash []byte) (GetAssessmentAttemptIdempotencyOutcomeRow, error)
|
||||
// Reads the immutable attempt kind without locking the row. Session commands
|
||||
// use this only to decide whether C3 applies before acquiring the row lock.
|
||||
GetAssessmentAttemptKindForCandidate(ctx context.Context, arg GetAssessmentAttemptKindForCandidateParams) (string, error)
|
||||
// Reads a result only for the owning candidate.
|
||||
GetAssessmentAttemptResult(ctx context.Context, arg GetAssessmentAttemptResultParams) (string, error)
|
||||
// Reads an active real attempt without taking the write lock used by create.
|
||||
// The availability GET never expires or otherwise mutates this row.
|
||||
GetAssessmentAvailabilityActiveAttempt(ctx context.Context, arg GetAssessmentAvailabilityActiveAttemptParams) (GetAssessmentAvailabilityActiveAttemptRow, error)
|
||||
GetAssessmentFamilyByID(ctx context.Context, id pgtype.UUID) (AssessmentFamily, error)
|
||||
GetAssessmentFamilyVersion(ctx context.Context, arg GetAssessmentFamilyVersionParams) (AssessmentFamily, error)
|
||||
// Counts eligible root attempts in a policy window and computes the instant
|
||||
// at which one additional root slot opens. The microsecond adjustment matches
|
||||
// the creation predicate created_at >= since at PostgreSQL timestamp precision.
|
||||
GetAssessmentRootQuotaAvailability(ctx context.Context, arg GetAssessmentRootQuotaAvailabilityParams) (GetAssessmentRootQuotaAvailabilityRow, error)
|
||||
// Read only the receipt associated with the reserved idempotency scope.
|
||||
GetAssessmentSignalOutcome(ctx context.Context, scopeHash []byte) (GetAssessmentSignalOutcomeRow, error)
|
||||
// Reads one hiding of the candidate with the current name of the
|
||||
// organization.
|
||||
GetCandidateHiddenOrganization(ctx context.Context, arg GetCandidateHiddenOrganizationParams) (GetCandidateHiddenOrganizationRow, error)
|
||||
@@ -236,6 +281,8 @@ type Querier interface {
|
||||
// resend, which issues its token with the same credentials.
|
||||
GetLatestPendingRegistration(ctx context.Context, arg GetLatestPendingRegistrationParams) (GetLatestPendingRegistrationRow, error)
|
||||
GetLatestPolicyVersion(ctx context.Context, policyKey string) (PolicyVersion, error)
|
||||
// Reads the latest root in a specialization, optionally restricted to grade.
|
||||
GetLatestRootAssessmentAttempt(ctx context.Context, arg GetLatestRootAssessmentAttemptParams) (AssessmentAttempt, error)
|
||||
GetLiveIdempotencyRecord(ctx context.Context, arg GetLiveIdempotencyRecordParams) (IdempotencyRecord, error)
|
||||
// Reads the usage of the day and the month window without locking.
|
||||
GetMailQuotaUsage(ctx context.Context, arg GetMailQuotaUsageParams) ([]GetMailQuotaUsageRow, error)
|
||||
@@ -250,6 +297,9 @@ type Querier interface {
|
||||
// unknown organization, an account that is no member, and a suspended,
|
||||
// removed, or left member all return no row and cannot be told apart.
|
||||
GetOrganizationForMember(ctx context.Context, arg GetOrganizationForMemberParams) (GetOrganizationForMemberRow, error)
|
||||
// Read only the immutable original response. The current need may have moved
|
||||
// to a later version since this result was created.
|
||||
GetOrganizationNeedCreationResult(ctx context.Context, scopeHash []byte) (string, error)
|
||||
// Reads the relay backlog for metrics without locking. Both subqueries use
|
||||
// the partial index on unpublished positions, so the cost follows the backlog
|
||||
// size, not the table size. The age comes from the database clock, the same
|
||||
@@ -278,6 +328,15 @@ type Querier interface {
|
||||
GetUnrevokedConsentRecordByVersion(ctx context.Context, arg GetUnrevokedConsentRecordByVersionParams) (GetUnrevokedConsentRecordByVersionRow, error)
|
||||
GetUserByEmailNormalized(ctx context.Context, emailNormalized string) (User, error)
|
||||
GetUserByID(ctx context.Context, id pgtype.UUID) (User, error)
|
||||
// Inserts the attempt header. The database guard rechecks the current policy,
|
||||
// opening or disjoint training binding, and immutable pins.
|
||||
InsertAssessmentAttempt(ctx context.Context, arg InsertAssessmentAttemptParams) error
|
||||
InsertAssessmentAttemptIdempotencyOutcome(ctx context.Context, arg InsertAssessmentAttemptIdempotencyOutcomeParams) error
|
||||
// Stores the immutable generated variant and empty answer slot.
|
||||
InsertAssessmentAttemptItem(ctx context.Context, arg InsertAssessmentAttemptItemParams) error
|
||||
// Stores one immutable candidate-visible result with the decision rationale
|
||||
// and source versions used by its finalized attempt.
|
||||
InsertAssessmentAttemptResult(ctx context.Context, arg InsertAssessmentAttemptResultParams) error
|
||||
// Stores an explicit mapping against a newly-created immutable opening. The
|
||||
// insert trigger checks the opening, declared reviewer, current policy, and
|
||||
// live coverage; the adapter supplies the fingerprint of the published set.
|
||||
@@ -292,6 +351,18 @@ type Querier interface {
|
||||
// returns no row instead of an error, so a conflict does not abort the
|
||||
// surrounding transaction.
|
||||
InsertAssessmentFamily(ctx context.Context, arg InsertAssessmentFamilyParams) (AssessmentFamily, error)
|
||||
// The attempt row is already locked by the caller. Store a parent before its
|
||||
// bounded child events, in the same transaction as the immutable receipt.
|
||||
InsertAssessmentSignalBatch(ctx context.Context, arg InsertAssessmentSignalBatchParams) error
|
||||
// Each inserted event is checked by the database guard against attempt state
|
||||
// and the aggregate capacity as a second line of defense.
|
||||
InsertAssessmentSignalEvent(ctx context.Context, arg InsertAssessmentSignalEventParams) error
|
||||
// Save exactly one immutable response receipt for each live idempotency scope.
|
||||
InsertAssessmentSignalOutcome(ctx context.Context, arg InsertAssessmentSignalOutcomeParams) error
|
||||
// Records a successfully authorized view after visibility and quota checks.
|
||||
// The audit contains only identities, the access kind, published field codes,
|
||||
// and time; it never receives the projection content, ranking, or filters.
|
||||
InsertCandidateCardAccessEvent(ctx context.Context, arg InsertCandidateCardAccessEventParams) error
|
||||
// Hides one organization. No row returns when the pair already exists, and
|
||||
// the caller reads the existing record with its original time. The foreign key
|
||||
// refuses an unknown organization (SQLSTATE 23503); the caller answers it
|
||||
@@ -390,12 +461,44 @@ type Querier interface {
|
||||
// transaction and then inserts nothing, or inserts after its rollback.
|
||||
InsertScheduledJob(ctx context.Context, arg InsertScheduledJobParams) (int64, error)
|
||||
InsertSession(ctx context.Context, arg InsertSessionParams) error
|
||||
// The initial public history is inserted in the caller's case transaction.
|
||||
// Any unique business conflict leaves the transaction usable so the caller can
|
||||
// store the immutable 409 outcome under the request's idempotency key.
|
||||
InsertSupportCase(ctx context.Context, arg InsertSupportCaseParams) (int64, error)
|
||||
InsertSupportCaseCreateOutcome(ctx context.Context, arg InsertSupportCaseCreateOutcomeParams) error
|
||||
InsertSupportCaseEvent(ctx context.Context, arg InsertSupportCaseEventParams) error
|
||||
InsertSupportCaseRequestEvent(ctx context.Context, arg InsertSupportCaseRequestEventParams) error
|
||||
InsertUser(ctx context.Context, arg InsertUserParams) error
|
||||
InvalidateActiveEmailTokens(ctx context.Context, arg InvalidateActiveEmailTokensParams) (int64, error)
|
||||
// Read the latest serialized event so a temporarily regressing application
|
||||
// clock cannot make the next request fall before an event already counted.
|
||||
LatestSupportCaseRequestEvent(ctx context.Context, ownerID pgtype.UUID) (pgtype.Timestamptz, error)
|
||||
// Reads chain headers in creation order. The use case verifies root eligibility
|
||||
// and descending target grades in the domain before it creates a correction.
|
||||
ListAssessmentAttemptChain(ctx context.Context, arg ListAssessmentAttemptChainParams) ([]AssessmentAttempt, error)
|
||||
// Reads private frozen variants and candidate answer bytes in stable order.
|
||||
ListAssessmentAttemptItems(ctx context.Context, attemptID pgtype.UUID) ([]ListAssessmentAttemptItemsRow, error)
|
||||
// Reads roots within the policy horizon and the last header in each correction
|
||||
// chain. It deliberately omits frozen items, answers, and row locks.
|
||||
ListAssessmentAvailabilityRootSummaries(ctx context.Context, arg ListAssessmentAvailabilityRootSummariesParams) ([]ListAssessmentAvailabilityRootSummariesRow, error)
|
||||
// Counts family instances disclosed after the non-repeat boundary. The first
|
||||
// item is disclosed when the attempt is created; each later item is disclosed
|
||||
// when the preceding answer is accepted. This per-item timestamp prevents a
|
||||
// long-running attempt from making later items appear older than they are.
|
||||
// Counting the first unanswered item after expiry is conservative when the
|
||||
// final response was lost, while frozen future items remain excluded.
|
||||
ListAssessmentDisclosedFamilyKeys(ctx context.Context, arg ListAssessmentDisclosedFamilyKeysParams) ([]string, error)
|
||||
// One page of the versions of a category in key and version order, after the
|
||||
// given position; an empty key and version 0 start at the beginning. The
|
||||
// (family_key, version) unique index serves the scan.
|
||||
ListAssessmentFamiliesByCategory(ctx context.Context, arg ListAssessmentFamiliesByCategoryParams) ([]AssessmentFamily, error)
|
||||
// Reads the exact family membership pinned by a training binding.
|
||||
ListAssessmentTrainingBindingFamilies(ctx context.Context, bindingID pgtype.UUID) ([]ListAssessmentTrainingBindingFamiliesRow, error)
|
||||
// Lists only the current candidate's own access history. It deliberately
|
||||
// omits the employee, requested card fields, and search context. The privacy
|
||||
// read adapter resolves an organization name only through this recorded
|
||||
// access relation, which is already visible to the candidate.
|
||||
ListCandidateCardAccessEvents(ctx context.Context, arg ListCandidateCardAccessEventsParams) ([]ListCandidateCardAccessEventsRow, error)
|
||||
// One page of the candidate's hidden organizations, newest first with the
|
||||
// organization identifier as the tie-breaker. The page continues after the
|
||||
// (hidden_at, organization_id) position of the last record of the previous
|
||||
@@ -414,12 +517,22 @@ type Querier interface {
|
||||
// whose records are scoped by invitation); active otherwise. The page continues after the (granted_at, id) position of
|
||||
// the last record of the previous page.
|
||||
ListConsentRecords(ctx context.Context, arg ListConsentRecordsParams) ([]ListConsentRecordsRow, error)
|
||||
// Returns current reviewed grade/language bindings and the live published
|
||||
// family manifest at one caller-supplied database time. The adapter verifies
|
||||
// the pinned manifest hash before exposing only family keys.
|
||||
ListCurrentAssessmentAvailabilitySelections(ctx context.Context, asOf pgtype.Timestamptz) ([]ListCurrentAssessmentAvailabilitySelectionsRow, error)
|
||||
// Lists explicit immutable training bindings for the effective product
|
||||
// policy. Callers reject more than one matching active binding as ambiguous.
|
||||
ListCurrentAssessmentTrainingBindings(ctx context.Context) ([]ListCurrentAssessmentTrainingBindingsRow, error)
|
||||
ListCurrentContactConsentRecords(ctx context.Context, arg ListCurrentContactConsentRecordsParams) ([]ListCurrentContactConsentRecordsRow, error)
|
||||
// Produces current catalog availability in one PostgreSQL statement snapshot.
|
||||
// The adapter compares the ordered live family manifest with the pinned
|
||||
// fingerprint; stale bindings are omitted fail-closed.
|
||||
ListCurrentSpecializationAvailability(ctx context.Context) ([]ListCurrentSpecializationAvailabilityRow, error)
|
||||
ListDeliveryAttempts(ctx context.Context, deliveryID pgtype.UUID) ([]DeliveryAttempt, error)
|
||||
// Read one bounded newest-first page of current needs. Both the organization
|
||||
// scope and the tuple cursor are applied before the limit.
|
||||
ListOrganizationNeeds(ctx context.Context, arg ListOrganizationNeedsParams) ([]ListOrganizationNeedsRow, error)
|
||||
// Lists the organizations where an account has an active membership,
|
||||
// newest membership first. The page continues after the (membership
|
||||
// creation time, organization ID) position of the last item of the
|
||||
@@ -428,10 +541,36 @@ type Querier interface {
|
||||
// Lists the other accounts of a provider that have usage in a month, so
|
||||
// startup can warn about a renamed EMAIL_ACCOUNT.
|
||||
ListOtherMailQuotaAccounts(ctx context.Context, arg ListOtherMailQuotaAccountsParams) ([]string, error)
|
||||
// Owner-scoped newest-first list. It omits descriptions, complaint reason,
|
||||
// and event history. The tuple cursor matches the composite sort key.
|
||||
ListOwnedSupportCases(ctx context.Context, arg ListOwnedSupportCasesParams) ([]ListOwnedSupportCasesRow, error)
|
||||
// Organization-facing anonymous candidate projection inputs. The calling
|
||||
// usecase has already authorized the active organization membership. This
|
||||
// single statement snapshot filters both revoked/unpublished C2 states and
|
||||
// candidates hidden from this organization before any profile value is read.
|
||||
// The projection reads only stack, declared role, and experience dates. It
|
||||
// deliberately excludes names, contacts, salary, location, soft skills,
|
||||
// employer names, summaries, and imported excerpts.
|
||||
ListVisibleCandidateViewSources(ctx context.Context, organizationID pgtype.UUID) ([]ListVisibleCandidateViewSourcesRow, error)
|
||||
// Locks the organization first and then the active membership, using the
|
||||
// same order as organization profile writes. A company operation keeps both
|
||||
// share locks until its transaction commits, so a concurrent revocation
|
||||
// cannot authorize a write after it has committed.
|
||||
LockActiveMembership(ctx context.Context, arg LockActiveMembershipParams) (LockActiveMembershipRow, error)
|
||||
// Locks one owner-scoped attempt while a session command performs its CAS.
|
||||
LockAssessmentAttemptForCandidate(ctx context.Context, arg LockAssessmentAttemptForCandidateParams) (AssessmentAttempt, error)
|
||||
// Serializes root quota checks for one candidate before taking its optional
|
||||
// specialization or training lock. All callers acquire these locks in order.
|
||||
LockAssessmentAttemptScope(ctx context.Context, arg LockAssessmentAttemptScopeParams) error
|
||||
// Serializes the operations that change which versions of a category are
|
||||
// published or open the category, until the transaction ends. The key is
|
||||
// namespaced, so it cannot collide with another use of advisory locks.
|
||||
LockAssessmentCategory(ctx context.Context, category string) error
|
||||
// Lock the account before an organization checks candidate visibility. The
|
||||
// hidden-organization insert trigger takes FOR NO KEY UPDATE on this row, so
|
||||
// a hide either commits before the later visibility recheck or waits for the
|
||||
// read transaction to finish.
|
||||
LockCandidateAccountForView(ctx context.Context, candidateID pgtype.UUID) (pgtype.UUID, error)
|
||||
// Locks the candidate's published row only when it refers to a C2 record
|
||||
// revoked by this transaction. The setting remains linked to that immutable
|
||||
// record; ReadCandidatePublication computes the effective closed state and
|
||||
@@ -452,6 +591,10 @@ type Querier interface {
|
||||
// finally usage rows. The organization lock serializes quota decisions for
|
||||
// the tenant and makes the subsequent count and insert atomic.
|
||||
LockCompanyQuotaOrganization(ctx context.Context, organizationID pgtype.UUID) (LockCompanyQuotaOrganizationRow, error)
|
||||
// Lock the current C2 before locking the publication. C2 revocation updates
|
||||
// this row before it locks the publication, so preserving this order avoids
|
||||
// a lock inversion and makes the current consent stable through the read.
|
||||
LockCurrentC2ForView(ctx context.Context, candidateID pgtype.UUID) (pgtype.UUID, error)
|
||||
// Takes the candidate's current unrevoked C2 record for a publication and
|
||||
// keeps it locked until the transaction ends. The share lock conflicts with
|
||||
// the revocation stamp (an UPDATE of the row), so a revocation either commits
|
||||
@@ -461,6 +604,9 @@ type Querier interface {
|
||||
// publication and must re-read the effective state (ReadCandidatePublication)
|
||||
// in that transaction to build its response.
|
||||
LockCurrentC2Record(ctx context.Context, subjectID pgtype.UUID) (pgtype.UUID, error)
|
||||
// Keeps the current C3 grant stable through a real assessment transaction.
|
||||
// Revocation updates this row and therefore waits until the caller commits.
|
||||
LockCurrentConsentForUse(ctx context.Context, subjectID pgtype.UUID) (LockCurrentConsentForUseRow, error)
|
||||
// Locks the listed window rows until the transaction ends, in
|
||||
// (period_kind, period_start) order, the same order for every caller, and
|
||||
// returns their usage. Under READ COMMITTED a waiting caller reads the usage
|
||||
@@ -482,8 +628,17 @@ type Querier interface {
|
||||
// because aggregate writers check the expected version, so scanning without a
|
||||
// position watermark cannot overtake an earlier version.
|
||||
LockPendingOutboxEvents(ctx context.Context, batchLimit int32) ([]LockPendingOutboxEventsRow, error)
|
||||
// Lock a candidate's current publication for the private preview. This has
|
||||
// no organization context and never enters the employer read quota or audit.
|
||||
LockPublicationForCandidatePreview(ctx context.Context, candidateID pgtype.UUID) (pgtype.UUID, error)
|
||||
// Locks the active registration C1 while its pending registration is applied.
|
||||
LockRegistrationConsentRecord(ctx context.Context, arg LockRegistrationConsentRecordParams) (LockRegistrationConsentRecordRow, error)
|
||||
// Serialize per-owner budget checks even before the first event exists.
|
||||
LockSupportCaseRequestBudget(ctx context.Context, ownerID pgtype.UUID) error
|
||||
// Lock and recheck one candidate's exact current publication only after the
|
||||
// active C2 row is share-locked. No row includes unpublished, revoked, stale
|
||||
// publication, and organization-hidden states.
|
||||
LockVisiblePublicationForView(ctx context.Context, arg LockVisiblePublicationForViewParams) (pgtype.UUID, error)
|
||||
// Notes that a request is about to start, by the database clock, and clears
|
||||
// the count of worker failures. For an operator-authorized send, this sets
|
||||
// its single-use marker without overwriting the original first-send time. The
|
||||
@@ -504,10 +659,16 @@ type Querier interface {
|
||||
// Verifies the email only for the registration version the consumed token
|
||||
// was issued for.
|
||||
MarkUserEmailVerified(ctx context.Context, arg MarkUserEmailVerifiedParams) (User, error)
|
||||
// Case numbers are monotonic and never reused. Sequence gaps on a rolled-back
|
||||
// request are expected and do not expose request contents.
|
||||
NextSupportCaseNumber(ctx context.Context, utcYear string) (interface{}, error)
|
||||
Ping(ctx context.Context) (int32, error)
|
||||
// Reports whether a family has any version without reading a document, so a
|
||||
// caller that only needs presence never depends on decoding.
|
||||
PolicyVersionExists(ctx context.Context, policyKey string) (bool, error)
|
||||
// Keep up to the maximum supported window, regardless of the current policy.
|
||||
// The bounded delete prevents one create from doing unbounded cleanup work.
|
||||
PruneSupportCaseRequestEvents(ctx context.Context, arg PruneSupportCaseRequestEventsParams) (int64, error)
|
||||
// Moves a draft to published by the named operator and returns the row with
|
||||
// the publication time set by the guard trigger. No row means the version
|
||||
// was not a draft any more.
|
||||
@@ -515,6 +676,18 @@ type Querier interface {
|
||||
// Deletes at most batch_limit expired records. Locked rows are skipped, so
|
||||
// the statement never waits for a concurrent reservation.
|
||||
PurgeExpiredIdempotencyRecords(ctx context.Context, arg PurgeExpiredIdempotencyRecordsParams) (int64, error)
|
||||
// Queries of the candidate visibility settings: the publication of
|
||||
// the card, the search status, the hidden organizations, and the history of
|
||||
// these settings. Every statement is scoped by the candidate's user_id, and
|
||||
// no statement selects another account's row. No statement reads or writes a
|
||||
// profile value, a name, or a contact. A candidate with no row is closed, not
|
||||
// looking, and hides nobody; no statement creates a row except an explicit
|
||||
// act of the candidate.
|
||||
// Reads the candidate-owned settings and hidden count from one statement
|
||||
// snapshot. Missing setting rows are restored as the closed/not-looking
|
||||
// defaults in the adapter. The account row scopes the result but does not
|
||||
// expose private profile values.
|
||||
ReadCandidatePrivacySettings(ctx context.Context, userID pgtype.UUID) (ReadCandidatePrivacySettingsRow, error)
|
||||
// Reads the profile row of an account together with every claim in one
|
||||
// statement, so the version and the claims come from one snapshot: a save that
|
||||
// commits between two separate reads could pair version N with the claims of
|
||||
@@ -523,13 +696,6 @@ type Querier interface {
|
||||
// 0). Claims come in a stable order: single fields by kind, list items by
|
||||
// position. Never replace this with two statements.
|
||||
ReadCandidateProfile(ctx context.Context, userID pgtype.UUID) ([]ReadCandidateProfileRow, error)
|
||||
// Queries of the candidate visibility settings: the publication of
|
||||
// the card, the search status, the hidden organizations, and the history of
|
||||
// these settings. Every statement is scoped by the candidate's user_id, and
|
||||
// no statement selects another account's row. No statement reads or writes a
|
||||
// profile value, a name, or a contact. A candidate with no row is closed, not
|
||||
// looking, and hides nobody; no statement creates a row except an explicit
|
||||
// act of the candidate.
|
||||
// Reads the publication with the revocation state of the C2 record behind it
|
||||
// in one statement, so the stored setting and the ledger come from one
|
||||
// snapshot. The effective state is computed from them: published only while
|
||||
@@ -542,10 +708,16 @@ type Querier interface {
|
||||
// lapse is computed by the caller from lapses_at and its clock and is never
|
||||
// written.
|
||||
ReadCandidateSearchStatus(ctx context.Context, userID pgtype.UUID) (CandidateSearchStatus, error)
|
||||
// Read the candidate's current private projection inputs after the caller
|
||||
// locks its active C2 and publication. It selects only fields allowed in the
|
||||
// anonymous-card projection and is never used for employer visibility.
|
||||
ReadCandidateViewSourceForPreview(ctx context.Context, candidateID pgtype.UUID) ([]ReadCandidateViewSourceForPreviewRow, error)
|
||||
// Read one current version with its organization-scoped parent metadata.
|
||||
ReadCurrentOrganizationNeed(ctx context.Context, arg ReadCurrentOrganizationNeedParams) (ReadCurrentOrganizationNeedRow, error)
|
||||
// Read one historical version without exposing another organization's record.
|
||||
ReadOrganizationNeedVersion(ctx context.Context, arg ReadOrganizationNeedVersionParams) (string, error)
|
||||
// Reads a full owner-scoped record. Object values are identifiers only.
|
||||
ReadOwnedSupportCase(ctx context.Context, arg ReadOwnedSupportCaseParams) (SupportCase, error)
|
||||
// The organization-facing read of a candidate's publication: the effective
|
||||
// view (published and backed by an unrevoked C2) and no hiding of the reading
|
||||
// organization. No row means the organization reads nothing, whichever of
|
||||
@@ -557,6 +729,9 @@ type Querier interface {
|
||||
// held by OpenCategory. Published families have passed the independent-review
|
||||
// constraint before this read.
|
||||
ReadPublishedAssessmentCategoryManifest(ctx context.Context, category string) ([]ReadPublishedAssessmentCategoryManifestRow, error)
|
||||
ReadSupportCaseCreateOutcome(ctx context.Context, scopeHash []byte) (ReadSupportCaseCreateOutcomeRow, error)
|
||||
// Reads the immutable public history only after the case owner has matched.
|
||||
ReadSupportCaseEvents(ctx context.Context, caseID pgtype.UUID) ([]ReadSupportCaseEventsRow, error)
|
||||
// Advances a delivery past one attempt and appends the attempt in one
|
||||
// statement, so both happen or neither does, inside or outside a
|
||||
// transaction. The update applies only while the stored version still
|
||||
@@ -609,6 +784,14 @@ type Querier interface {
|
||||
// with GetLiveIdempotencyRecord. Concurrent callers with the same scope wait
|
||||
// on the row of the first one until its transaction ends.
|
||||
ReserveIdempotencyRecord(ctx context.Context, arg ReserveIdempotencyRecordParams) (IdempotencyRecord, error)
|
||||
// Finds candidate-requested selections across currently opened categories.
|
||||
// The adapter validates policy and manifest freshness, locks the category,
|
||||
// then runs this query again before it returns any pinned families.
|
||||
ResolveCurrentAssessmentSelection(ctx context.Context, arg ResolveCurrentAssessmentSelectionParams) ([]ResolveCurrentAssessmentSelectionRow, error)
|
||||
// Lists every current reviewed category binding for one exact public target.
|
||||
// Manual support cases have no task-language selector, so the use case must
|
||||
// accept a rubric only when one distinct current opening matches.
|
||||
ResolveCurrentSupportCaseRubrics(ctx context.Context, arg ResolveCurrentSupportCaseRubricsParams) ([]ResolveCurrentSupportCaseRubricsRow, error)
|
||||
RetireAssessmentFamily(ctx context.Context, arg RetireAssessmentFamilyParams) (AssessmentFamily, error)
|
||||
// Revokes every unrevoked record of a purpose other than C4, superseded ones
|
||||
// included, and returns them. A revocation time before the grant time, from
|
||||
@@ -625,6 +808,10 @@ type Querier interface {
|
||||
// and owner membership. A reused expired scope replaces the snapshot in the
|
||||
// same transaction as the new organization.
|
||||
SaveOrganizationCreationResult(ctx context.Context, arg SaveOrganizationCreationResultParams) error
|
||||
// The generic idempotency scope serializes retries. Replacing the child row
|
||||
// is safe only in the transaction that reserves an expired scope for a new
|
||||
// create; live retries read and return the stored response without writing.
|
||||
SaveOrganizationNeedCreationResult(ctx context.Context, arg SaveOrganizationNeedCreationResultParams) error
|
||||
// Bounds a consumer transaction on the server, local to the transaction.
|
||||
// statement_timeout stops a slow statement; idle_in_transaction_session_timeout
|
||||
// ends the session of a process that froze or lost the network inside the
|
||||
@@ -661,6 +848,14 @@ type Querier interface {
|
||||
// revoked, expired, or idle session is not revived; the update re-checks
|
||||
// those conditions against a concurrent change.
|
||||
TouchSession(ctx context.Context, arg TouchSessionParams) (TouchSessionRow, error)
|
||||
// Stores one final answer before advancing the enclosing attempt version.
|
||||
// The caller holds the owner-scoped attempt row lock for the surrounding unit.
|
||||
UpdateAssessmentAttemptItemAnswer(ctx context.Context, arg UpdateAssessmentAttemptItemAnswerParams) (pgtype.UUID, error)
|
||||
// Applies a versioned session transition after the attempt row is locked.
|
||||
UpdateAssessmentAttemptSession(ctx context.Context, arg UpdateAssessmentAttemptSessionParams) (AssessmentAttempt, error)
|
||||
// Applies an answer, expiry, or finalization transition after the attempt row
|
||||
// is locked. Session limits and all immutable pins remain unchanged.
|
||||
UpdateAssessmentAttemptTransition(ctx context.Context, arg UpdateAssessmentAttemptTransitionParams) (AssessmentAttempt, error)
|
||||
// Replaces the publication over the version the caller read and advances the
|
||||
// version in the same statement. No row returns for a stale version, which
|
||||
// the caller answers as a version conflict. The update time never moves back,
|
||||
|
||||
@@ -0,0 +1,502 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: support_cases.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const countSupportCaseRequestEvents = `-- name: CountSupportCaseRequestEvents :one
|
||||
SELECT count(*)::bigint AS event_count, min(requested_at) AS first_in_window
|
||||
FROM support_case_request_events
|
||||
WHERE owner_id = $1
|
||||
AND requested_at > $2::timestamptz
|
||||
AND requested_at <= $3::timestamptz
|
||||
`
|
||||
|
||||
type CountSupportCaseRequestEventsParams struct {
|
||||
OwnerID pgtype.UUID
|
||||
WindowStart pgtype.Timestamptz
|
||||
At pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type CountSupportCaseRequestEventsRow struct {
|
||||
EventCount int64
|
||||
FirstInWindow interface{}
|
||||
}
|
||||
|
||||
// The strict lower boundary means an event exactly one window old no longer
|
||||
// counts. The use case derives Retry-After from first_in_window.
|
||||
func (q *Queries) CountSupportCaseRequestEvents(ctx context.Context, arg CountSupportCaseRequestEventsParams) (CountSupportCaseRequestEventsRow, error) {
|
||||
row := q.db.QueryRow(ctx, countSupportCaseRequestEvents, arg.OwnerID, arg.WindowStart, arg.At)
|
||||
var i CountSupportCaseRequestEventsRow
|
||||
err := row.Scan(&i.EventCount, &i.FirstInWindow)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const deleteSupportCaseCreateOutcome = `-- name: DeleteSupportCaseCreateOutcome :exec
|
||||
DELETE FROM support_case_create_outcomes
|
||||
WHERE scope_hash = $1
|
||||
`
|
||||
|
||||
// No raw Idempotency-Key or request body reaches these statements. Failure
|
||||
// responses pass {} as case_snapshot and the CASE stores SQL NULL instead.
|
||||
func (q *Queries) DeleteSupportCaseCreateOutcome(ctx context.Context, scopeHash []byte) error {
|
||||
_, err := q.db.Exec(ctx, deleteSupportCaseCreateOutcome, scopeHash)
|
||||
return err
|
||||
}
|
||||
|
||||
const insertSupportCase = `-- name: InsertSupportCase :execrows
|
||||
INSERT INTO support_cases (
|
||||
id, case_number, owner_id, case_type, status, description,
|
||||
object_type, object_id, assessment_specialization, assessment_grade,
|
||||
complaint_reason, rubric_version, rubric_opening_id, rubric_policy_version_id,
|
||||
target_business_days, target_due_at,
|
||||
target_answered_at, target_policy_version, target_calendar_version,
|
||||
decision_outcome, decision_reason, decision_at, created_at, updated_at
|
||||
) VALUES (
|
||||
$1, $2, $3, $4,
|
||||
$5, $6, $7, $8,
|
||||
$9, $10,
|
||||
$11, $12, $13,
|
||||
$14, $15,
|
||||
$16, $17, $18,
|
||||
$19, $20, $21,
|
||||
$22, $23, $24
|
||||
)
|
||||
ON CONFLICT DO NOTHING
|
||||
`
|
||||
|
||||
type InsertSupportCaseParams struct {
|
||||
ID pgtype.UUID
|
||||
CaseNumber string
|
||||
OwnerID pgtype.UUID
|
||||
CaseType string
|
||||
Status string
|
||||
Description string
|
||||
ObjectType pgtype.Text
|
||||
ObjectID pgtype.UUID
|
||||
AssessmentSpecialization pgtype.Text
|
||||
AssessmentGrade pgtype.Text
|
||||
ComplaintReason pgtype.Text
|
||||
RubricVersion pgtype.Int4
|
||||
RubricOpeningID pgtype.UUID
|
||||
RubricPolicyVersionID pgtype.UUID
|
||||
TargetBusinessDays int32
|
||||
TargetDueAt pgtype.Timestamptz
|
||||
TargetAnsweredAt pgtype.Timestamptz
|
||||
TargetPolicyVersion int32
|
||||
TargetCalendarVersion int32
|
||||
DecisionOutcome pgtype.Text
|
||||
DecisionReason pgtype.Text
|
||||
DecisionAt pgtype.Timestamptz
|
||||
CreatedAt pgtype.Timestamptz
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// The initial public history is inserted in the caller's case transaction.
|
||||
// Any unique business conflict leaves the transaction usable so the caller can
|
||||
// store the immutable 409 outcome under the request's idempotency key.
|
||||
func (q *Queries) InsertSupportCase(ctx context.Context, arg InsertSupportCaseParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, insertSupportCase,
|
||||
arg.ID,
|
||||
arg.CaseNumber,
|
||||
arg.OwnerID,
|
||||
arg.CaseType,
|
||||
arg.Status,
|
||||
arg.Description,
|
||||
arg.ObjectType,
|
||||
arg.ObjectID,
|
||||
arg.AssessmentSpecialization,
|
||||
arg.AssessmentGrade,
|
||||
arg.ComplaintReason,
|
||||
arg.RubricVersion,
|
||||
arg.RubricOpeningID,
|
||||
arg.RubricPolicyVersionID,
|
||||
arg.TargetBusinessDays,
|
||||
arg.TargetDueAt,
|
||||
arg.TargetAnsweredAt,
|
||||
arg.TargetPolicyVersion,
|
||||
arg.TargetCalendarVersion,
|
||||
arg.DecisionOutcome,
|
||||
arg.DecisionReason,
|
||||
arg.DecisionAt,
|
||||
arg.CreatedAt,
|
||||
arg.UpdatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const insertSupportCaseCreateOutcome = `-- name: InsertSupportCaseCreateOutcome :exec
|
||||
INSERT INTO support_case_create_outcomes (
|
||||
scope_hash, outcome_kind, case_snapshot, target_was_late, created_at
|
||||
) VALUES (
|
||||
$1, $2,
|
||||
CASE WHEN $2::text = 'created' THEN $3::jsonb END,
|
||||
CASE WHEN $2::text = 'created' THEN $4::boolean END,
|
||||
$5
|
||||
)
|
||||
`
|
||||
|
||||
type InsertSupportCaseCreateOutcomeParams struct {
|
||||
ScopeHash []byte
|
||||
OutcomeKind string
|
||||
CaseSnapshot []byte
|
||||
TargetWasLate bool
|
||||
CreatedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
func (q *Queries) InsertSupportCaseCreateOutcome(ctx context.Context, arg InsertSupportCaseCreateOutcomeParams) error {
|
||||
_, err := q.db.Exec(ctx, insertSupportCaseCreateOutcome,
|
||||
arg.ScopeHash,
|
||||
arg.OutcomeKind,
|
||||
arg.CaseSnapshot,
|
||||
arg.TargetWasLate,
|
||||
arg.CreatedAt,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const insertSupportCaseEvent = `-- name: InsertSupportCaseEvent :exec
|
||||
INSERT INTO support_case_events (
|
||||
case_id, sequence, event_kind, actor_kind, occurred_at, status, message
|
||||
) VALUES (
|
||||
$1, $2, $3, $4,
|
||||
$5, $6, $7
|
||||
)
|
||||
`
|
||||
|
||||
type InsertSupportCaseEventParams struct {
|
||||
CaseID pgtype.UUID
|
||||
Sequence int32
|
||||
EventKind string
|
||||
ActorKind string
|
||||
OccurredAt pgtype.Timestamptz
|
||||
Status pgtype.Text
|
||||
Message pgtype.Text
|
||||
}
|
||||
|
||||
func (q *Queries) InsertSupportCaseEvent(ctx context.Context, arg InsertSupportCaseEventParams) error {
|
||||
_, err := q.db.Exec(ctx, insertSupportCaseEvent,
|
||||
arg.CaseID,
|
||||
arg.Sequence,
|
||||
arg.EventKind,
|
||||
arg.ActorKind,
|
||||
arg.OccurredAt,
|
||||
arg.Status,
|
||||
arg.Message,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const insertSupportCaseRequestEvent = `-- name: InsertSupportCaseRequestEvent :exec
|
||||
INSERT INTO support_case_request_events (owner_id, requested_at)
|
||||
VALUES ($1, $2)
|
||||
`
|
||||
|
||||
type InsertSupportCaseRequestEventParams struct {
|
||||
OwnerID pgtype.UUID
|
||||
RequestedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
func (q *Queries) InsertSupportCaseRequestEvent(ctx context.Context, arg InsertSupportCaseRequestEventParams) error {
|
||||
_, err := q.db.Exec(ctx, insertSupportCaseRequestEvent, arg.OwnerID, arg.RequestedAt)
|
||||
return err
|
||||
}
|
||||
|
||||
const latestSupportCaseRequestEvent = `-- name: LatestSupportCaseRequestEvent :one
|
||||
SELECT requested_at
|
||||
FROM support_case_request_events
|
||||
WHERE owner_id = $1
|
||||
ORDER BY requested_at DESC, id DESC
|
||||
LIMIT 1
|
||||
`
|
||||
|
||||
// Read the latest serialized event so a temporarily regressing application
|
||||
// clock cannot make the next request fall before an event already counted.
|
||||
func (q *Queries) LatestSupportCaseRequestEvent(ctx context.Context, ownerID pgtype.UUID) (pgtype.Timestamptz, error) {
|
||||
row := q.db.QueryRow(ctx, latestSupportCaseRequestEvent, ownerID)
|
||||
var requested_at pgtype.Timestamptz
|
||||
err := row.Scan(&requested_at)
|
||||
return requested_at, err
|
||||
}
|
||||
|
||||
const listOwnedSupportCases = `-- name: ListOwnedSupportCases :many
|
||||
WITH cursor_input AS MATERIALIZED (
|
||||
SELECT
|
||||
$3::timestamptz AS after_created_at,
|
||||
$4::uuid AS after_id
|
||||
)
|
||||
SELECT
|
||||
id, case_number, case_type, status, object_type, object_id,
|
||||
assessment_specialization, assessment_grade, target_business_days,
|
||||
target_due_at, target_answered_at, target_policy_version,
|
||||
target_calendar_version, decision_outcome, created_at, updated_at
|
||||
FROM support_cases
|
||||
CROSS JOIN cursor_input
|
||||
WHERE owner_id = $1
|
||||
AND (
|
||||
cursor_input.after_created_at IS NULL
|
||||
OR (created_at, id) < (
|
||||
cursor_input.after_created_at,
|
||||
cursor_input.after_id
|
||||
)
|
||||
)
|
||||
ORDER BY created_at DESC, id DESC
|
||||
LIMIT $2
|
||||
`
|
||||
|
||||
type ListOwnedSupportCasesParams struct {
|
||||
OwnerID pgtype.UUID
|
||||
RowLimit int32
|
||||
AfterCreatedAt pgtype.Timestamptz
|
||||
AfterID pgtype.UUID
|
||||
}
|
||||
|
||||
type ListOwnedSupportCasesRow struct {
|
||||
ID pgtype.UUID
|
||||
CaseNumber string
|
||||
CaseType string
|
||||
Status string
|
||||
ObjectType pgtype.Text
|
||||
ObjectID pgtype.UUID
|
||||
AssessmentSpecialization pgtype.Text
|
||||
AssessmentGrade pgtype.Text
|
||||
TargetBusinessDays int32
|
||||
TargetDueAt pgtype.Timestamptz
|
||||
TargetAnsweredAt pgtype.Timestamptz
|
||||
TargetPolicyVersion int32
|
||||
TargetCalendarVersion int32
|
||||
DecisionOutcome pgtype.Text
|
||||
CreatedAt pgtype.Timestamptz
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Owner-scoped newest-first list. It omits descriptions, complaint reason,
|
||||
// and event history. The tuple cursor matches the composite sort key.
|
||||
func (q *Queries) ListOwnedSupportCases(ctx context.Context, arg ListOwnedSupportCasesParams) ([]ListOwnedSupportCasesRow, error) {
|
||||
rows, err := q.db.Query(ctx, listOwnedSupportCases,
|
||||
arg.OwnerID,
|
||||
arg.RowLimit,
|
||||
arg.AfterCreatedAt,
|
||||
arg.AfterID,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ListOwnedSupportCasesRow
|
||||
for rows.Next() {
|
||||
var i ListOwnedSupportCasesRow
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.CaseNumber,
|
||||
&i.CaseType,
|
||||
&i.Status,
|
||||
&i.ObjectType,
|
||||
&i.ObjectID,
|
||||
&i.AssessmentSpecialization,
|
||||
&i.AssessmentGrade,
|
||||
&i.TargetBusinessDays,
|
||||
&i.TargetDueAt,
|
||||
&i.TargetAnsweredAt,
|
||||
&i.TargetPolicyVersion,
|
||||
&i.TargetCalendarVersion,
|
||||
&i.DecisionOutcome,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const lockSupportCaseRequestBudget = `-- name: LockSupportCaseRequestBudget :exec
|
||||
SELECT pg_advisory_xact_lock(
|
||||
hashtextextended('lincodex.support.case.requests:' || $1::uuid::text, 0)
|
||||
)
|
||||
`
|
||||
|
||||
// Serialize per-owner budget checks even before the first event exists.
|
||||
func (q *Queries) LockSupportCaseRequestBudget(ctx context.Context, ownerID pgtype.UUID) error {
|
||||
_, err := q.db.Exec(ctx, lockSupportCaseRequestBudget, ownerID)
|
||||
return err
|
||||
}
|
||||
|
||||
const nextSupportCaseNumber = `-- name: NextSupportCaseNumber :one
|
||||
WITH next_value AS MATERIALIZED (
|
||||
SELECT nextval('support_case_number_seq') AS value
|
||||
)
|
||||
SELECT
|
||||
'SC-' || $1::text || '-' ||
|
||||
CASE
|
||||
WHEN next_value.value < 1000000 THEN lpad(next_value.value::text, 6, '0')
|
||||
ELSE next_value.value::text
|
||||
END::text AS case_number
|
||||
FROM next_value
|
||||
`
|
||||
|
||||
// Case numbers are monotonic and never reused. Sequence gaps on a rolled-back
|
||||
// request are expected and do not expose request contents.
|
||||
func (q *Queries) NextSupportCaseNumber(ctx context.Context, utcYear string) (interface{}, error) {
|
||||
row := q.db.QueryRow(ctx, nextSupportCaseNumber, utcYear)
|
||||
var case_number interface{}
|
||||
err := row.Scan(&case_number)
|
||||
return case_number, err
|
||||
}
|
||||
|
||||
const pruneSupportCaseRequestEvents = `-- name: PruneSupportCaseRequestEvents :execrows
|
||||
WITH expired AS MATERIALIZED (
|
||||
SELECT source.id
|
||||
FROM support_case_request_events AS source
|
||||
WHERE source.owner_id = $1
|
||||
AND source.requested_at <= $2::timestamptz - interval '24 hours'
|
||||
ORDER BY source.requested_at, source.id
|
||||
LIMIT 100
|
||||
FOR UPDATE SKIP LOCKED
|
||||
)
|
||||
DELETE FROM support_case_request_events AS event
|
||||
USING expired
|
||||
WHERE event.id = expired.id
|
||||
`
|
||||
|
||||
type PruneSupportCaseRequestEventsParams struct {
|
||||
OwnerID pgtype.UUID
|
||||
At pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Keep up to the maximum supported window, regardless of the current policy.
|
||||
// The bounded delete prevents one create from doing unbounded cleanup work.
|
||||
func (q *Queries) PruneSupportCaseRequestEvents(ctx context.Context, arg PruneSupportCaseRequestEventsParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, pruneSupportCaseRequestEvents, arg.OwnerID, arg.At)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const readOwnedSupportCase = `-- name: ReadOwnedSupportCase :one
|
||||
SELECT
|
||||
id, case_number, owner_id, case_type, status, description,
|
||||
object_type, object_id, assessment_specialization, assessment_grade,
|
||||
complaint_reason, rubric_version, rubric_opening_id, rubric_policy_version_id,
|
||||
target_business_days, target_due_at,
|
||||
target_answered_at, target_policy_version, target_calendar_version,
|
||||
decision_outcome, decision_reason, decision_at, created_at, updated_at
|
||||
FROM support_cases
|
||||
WHERE id = $1 AND owner_id = $2
|
||||
`
|
||||
|
||||
type ReadOwnedSupportCaseParams struct {
|
||||
CaseID pgtype.UUID
|
||||
OwnerID pgtype.UUID
|
||||
}
|
||||
|
||||
// Reads a full owner-scoped record. Object values are identifiers only.
|
||||
func (q *Queries) ReadOwnedSupportCase(ctx context.Context, arg ReadOwnedSupportCaseParams) (SupportCase, error) {
|
||||
row := q.db.QueryRow(ctx, readOwnedSupportCase, arg.CaseID, arg.OwnerID)
|
||||
var i SupportCase
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.CaseNumber,
|
||||
&i.OwnerID,
|
||||
&i.CaseType,
|
||||
&i.Status,
|
||||
&i.Description,
|
||||
&i.ObjectType,
|
||||
&i.ObjectID,
|
||||
&i.AssessmentSpecialization,
|
||||
&i.AssessmentGrade,
|
||||
&i.ComplaintReason,
|
||||
&i.RubricVersion,
|
||||
&i.RubricOpeningID,
|
||||
&i.RubricPolicyVersionID,
|
||||
&i.TargetBusinessDays,
|
||||
&i.TargetDueAt,
|
||||
&i.TargetAnsweredAt,
|
||||
&i.TargetPolicyVersion,
|
||||
&i.TargetCalendarVersion,
|
||||
&i.DecisionOutcome,
|
||||
&i.DecisionReason,
|
||||
&i.DecisionAt,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const readSupportCaseCreateOutcome = `-- name: ReadSupportCaseCreateOutcome :one
|
||||
SELECT outcome_kind, coalesce(case_snapshot::text, '') AS case_snapshot, target_was_late
|
||||
FROM support_case_create_outcomes
|
||||
WHERE scope_hash = $1
|
||||
`
|
||||
|
||||
type ReadSupportCaseCreateOutcomeRow struct {
|
||||
OutcomeKind string
|
||||
CaseSnapshot interface{}
|
||||
TargetWasLate pgtype.Bool
|
||||
}
|
||||
|
||||
func (q *Queries) ReadSupportCaseCreateOutcome(ctx context.Context, scopeHash []byte) (ReadSupportCaseCreateOutcomeRow, error) {
|
||||
row := q.db.QueryRow(ctx, readSupportCaseCreateOutcome, scopeHash)
|
||||
var i ReadSupportCaseCreateOutcomeRow
|
||||
err := row.Scan(&i.OutcomeKind, &i.CaseSnapshot, &i.TargetWasLate)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const readSupportCaseEvents = `-- name: ReadSupportCaseEvents :many
|
||||
SELECT sequence, event_kind, actor_kind, occurred_at, status, message
|
||||
FROM support_case_events
|
||||
WHERE case_id = $1
|
||||
ORDER BY sequence
|
||||
`
|
||||
|
||||
type ReadSupportCaseEventsRow struct {
|
||||
Sequence int32
|
||||
EventKind string
|
||||
ActorKind string
|
||||
OccurredAt pgtype.Timestamptz
|
||||
Status pgtype.Text
|
||||
Message pgtype.Text
|
||||
}
|
||||
|
||||
// Reads the immutable public history only after the case owner has matched.
|
||||
func (q *Queries) ReadSupportCaseEvents(ctx context.Context, caseID pgtype.UUID) ([]ReadSupportCaseEventsRow, error) {
|
||||
rows, err := q.db.Query(ctx, readSupportCaseEvents, caseID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ReadSupportCaseEventsRow
|
||||
for rows.Next() {
|
||||
var i ReadSupportCaseEventsRow
|
||||
if err := rows.Scan(
|
||||
&i.Sequence,
|
||||
&i.EventKind,
|
||||
&i.ActorKind,
|
||||
&i.OccurredAt,
|
||||
&i.Status,
|
||||
&i.Message,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: support_rubrics.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const resolveCurrentSupportCaseRubrics = `-- name: ResolveCurrentSupportCaseRubrics :many
|
||||
WITH current_openings AS (
|
||||
SELECT DISTINCT ON (category)
|
||||
id,
|
||||
category,
|
||||
policy_version_id,
|
||||
required_families
|
||||
FROM assessment_category_openings
|
||||
ORDER BY category, opened_at DESC, id DESC
|
||||
), current_policy AS (
|
||||
SELECT id, version
|
||||
FROM policy_versions
|
||||
WHERE policy_key = 'product' AND effective_at <= statement_timestamp()
|
||||
ORDER BY version DESC
|
||||
LIMIT 1
|
||||
)
|
||||
SELECT
|
||||
opening.id AS opening_id,
|
||||
opening.category,
|
||||
opening.policy_version_id,
|
||||
opening.required_families,
|
||||
COALESCE((
|
||||
SELECT count(DISTINCT family.family_key)::integer
|
||||
FROM assessment_families AS family
|
||||
WHERE family.category = opening.category AND family.lifecycle = 'published'
|
||||
), 0)::integer AS published_count,
|
||||
policy.id AS effective_policy_id,
|
||||
policy.version AS effective_policy_version,
|
||||
binding.specialization,
|
||||
binding.grade,
|
||||
binding.task_languages,
|
||||
binding.published_manifest_sha256,
|
||||
COALESCE((
|
||||
SELECT jsonb_agg(
|
||||
jsonb_build_object(
|
||||
'family_key', family.family_key,
|
||||
'version', family.version,
|
||||
'content_sha256', encode(family.content_sha256, 'hex')
|
||||
) ORDER BY family.family_key, family.version
|
||||
)
|
||||
FROM assessment_families AS family
|
||||
WHERE family.category = opening.category AND family.lifecycle = 'published'
|
||||
), '[]'::jsonb)::text AS published_manifest
|
||||
FROM current_openings AS opening
|
||||
JOIN assessment_category_catalog_bindings AS binding
|
||||
ON binding.opening_id = opening.id
|
||||
LEFT JOIN current_policy AS policy ON true
|
||||
WHERE binding.specialization = $1
|
||||
AND binding.grade = $2
|
||||
ORDER BY opening.category
|
||||
`
|
||||
|
||||
type ResolveCurrentSupportCaseRubricsParams struct {
|
||||
Specialization string
|
||||
Grade string
|
||||
}
|
||||
|
||||
type ResolveCurrentSupportCaseRubricsRow struct {
|
||||
OpeningID pgtype.UUID
|
||||
Category string
|
||||
PolicyVersionID pgtype.UUID
|
||||
RequiredFamilies int32
|
||||
PublishedCount int32
|
||||
EffectivePolicyID pgtype.UUID
|
||||
EffectivePolicyVersion pgtype.Int4
|
||||
Specialization string
|
||||
Grade string
|
||||
TaskLanguages []string
|
||||
PublishedManifestSha256 []byte
|
||||
PublishedManifest string
|
||||
}
|
||||
|
||||
// Lists every current reviewed category binding for one exact public target.
|
||||
// Manual support cases have no task-language selector, so the use case must
|
||||
// accept a rubric only when one distinct current opening matches.
|
||||
func (q *Queries) ResolveCurrentSupportCaseRubrics(ctx context.Context, arg ResolveCurrentSupportCaseRubricsParams) ([]ResolveCurrentSupportCaseRubricsRow, error) {
|
||||
rows, err := q.db.Query(ctx, resolveCurrentSupportCaseRubrics, arg.Specialization, arg.Grade)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ResolveCurrentSupportCaseRubricsRow
|
||||
for rows.Next() {
|
||||
var i ResolveCurrentSupportCaseRubricsRow
|
||||
if err := rows.Scan(
|
||||
&i.OpeningID,
|
||||
&i.Category,
|
||||
&i.PolicyVersionID,
|
||||
&i.RequiredFamilies,
|
||||
&i.PublishedCount,
|
||||
&i.EffectivePolicyID,
|
||||
&i.EffectivePolicyVersion,
|
||||
&i.Specialization,
|
||||
&i.Grade,
|
||||
&i.TaskLanguages,
|
||||
&i.PublishedManifestSha256,
|
||||
&i.PublishedManifest,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
@@ -0,0 +1,618 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const maxSupportCaseSnapshotBytes = 1 << 20
|
||||
|
||||
var supportCaseConstraintErrors = map[constraintViolation]error{
|
||||
{foreignKeyViolationCode, "support_cases_owner_id_fkey"}: outbound.ErrUserNotFound,
|
||||
{foreignKeyViolationCode, "support_case_create_outcomes_scope_hash_fkey"}: outbound.ErrIdempotencyRecordNotFound,
|
||||
}
|
||||
|
||||
var (
|
||||
_ outbound.SupportCaseRepository = supportCaseRepository{}
|
||||
_ outbound.SupportCaseCreateOutcomeRepository = supportCaseRepository{}
|
||||
_ outbound.SupportCaseRequestLimitRepository = supportCaseRepository{}
|
||||
_ outbound.SupportCaseRepositories = (*UnitOfWork)(nil)
|
||||
)
|
||||
|
||||
func (unit *UnitOfWork) SupportCases() outbound.SupportCaseRepository {
|
||||
return supportCaseRepository{queries: unit.queries}
|
||||
}
|
||||
|
||||
func (unit *UnitOfWork) SupportCaseCreateOutcomes() outbound.SupportCaseCreateOutcomeRepository {
|
||||
return supportCaseRepository{queries: unit.queries}
|
||||
}
|
||||
|
||||
func (unit *UnitOfWork) SupportCaseRequestLimits() outbound.SupportCaseRequestLimitRepository {
|
||||
return supportCaseRepository{queries: unit.queries}
|
||||
}
|
||||
|
||||
type supportCaseRepository struct {
|
||||
queries *sqlc.Queries
|
||||
}
|
||||
|
||||
func (repository supportCaseRepository) NextNumber(ctx context.Context, createdAt time.Time) (domain.SupportCaseNumber, error) {
|
||||
const location = "supportCaseRepository.NextNumber"
|
||||
if createdAt.IsZero() || createdAt.Year() < 1 || createdAt.Year() > 9999 {
|
||||
return "", fmt.Errorf("%s - creation time is invalid: %w", location, domain.ErrInvalidSupportCase)
|
||||
}
|
||||
value, err := repository.queries.NextSupportCaseNumber(ctx, fmt.Sprintf("%04d", createdAt.UTC().Year()))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("%s - allocate number: %w", location, mapSupportCaseError(err))
|
||||
}
|
||||
var number string
|
||||
switch stored := value.(type) {
|
||||
case string:
|
||||
number = stored
|
||||
case []byte:
|
||||
number = string(stored)
|
||||
default:
|
||||
return "", fmt.Errorf("%s - database returned an invalid number type", location)
|
||||
}
|
||||
parsed, err := domain.ParseSupportCaseNumber(number)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("%s - database returned an invalid number", location)
|
||||
}
|
||||
return parsed, nil
|
||||
}
|
||||
|
||||
func (repository supportCaseRepository) Create(ctx context.Context, supportCase domain.SupportCase) error {
|
||||
const location = "supportCaseRepository.Create"
|
||||
if supportCase.IsZero() {
|
||||
return fmt.Errorf("%s - case is not initialized: %w", location, domain.ErrInvalidSupportCase)
|
||||
}
|
||||
snapshot := supportCase.Snapshot()
|
||||
validated, err := domain.RestoreSupportCase(snapshot)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - validate case: %w", location, err)
|
||||
}
|
||||
snapshot = validated.Snapshot()
|
||||
row := supportCaseInsertParams(snapshot)
|
||||
inserted, err := repository.queries.InsertSupportCase(ctx, row)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - insert case: %w", location, mapSupportCaseError(err))
|
||||
}
|
||||
if inserted != 1 {
|
||||
return fmt.Errorf("%s - unique business rule rejected the case: %w", location, outbound.ErrSupportCaseConflict)
|
||||
}
|
||||
for _, event := range snapshot.History {
|
||||
if err := repository.queries.InsertSupportCaseEvent(ctx, supportCaseEventParams(snapshot.ID.UUID(), event)); err != nil {
|
||||
return fmt.Errorf("%s - insert public event: %w", location, mapSupportCaseError(err))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository supportCaseRepository) GetOwned(ctx context.Context, ownerID uuid.UUID, caseID domain.SupportCaseID) (domain.SupportCase, error) {
|
||||
const location = "supportCaseRepository.GetOwned"
|
||||
if ownerID == uuid.Nil || caseID.IsZero() {
|
||||
return domain.SupportCase{}, fmt.Errorf("%s - scope identifiers are invalid: %w", location, domain.ErrInvalidSupportCase)
|
||||
}
|
||||
row, err := repository.queries.ReadOwnedSupportCase(ctx, sqlc.ReadOwnedSupportCaseParams{
|
||||
CaseID: pgUUID(caseID.UUID()), OwnerID: pgUUID(ownerID),
|
||||
})
|
||||
if err != nil {
|
||||
return domain.SupportCase{}, fmt.Errorf("%s - read owner-scoped case: %w", location, mapSupportCaseNoRows(err, outbound.ErrSupportCaseNotFound))
|
||||
}
|
||||
events, err := repository.queries.ReadSupportCaseEvents(ctx, pgUUID(caseID.UUID()))
|
||||
if err != nil {
|
||||
return domain.SupportCase{}, fmt.Errorf("%s - read public history: %w", location, mapSupportCaseError(err))
|
||||
}
|
||||
snapshot, err := supportCaseSnapshotFromRow(row, events)
|
||||
if err != nil {
|
||||
return domain.SupportCase{}, fmt.Errorf("%s - restore stored case: %w", location, err)
|
||||
}
|
||||
if snapshot.OwnerID != ownerID || snapshot.ID != caseID {
|
||||
return domain.SupportCase{}, fmt.Errorf("%s - stored case scope does not match query", location)
|
||||
}
|
||||
supportCase, err := domain.RestoreSupportCase(snapshot)
|
||||
if err != nil {
|
||||
return domain.SupportCase{}, fmt.Errorf("%s - validate stored case: %w", location, err)
|
||||
}
|
||||
return supportCase, nil
|
||||
}
|
||||
|
||||
func (repository supportCaseRepository) ListOwned(ctx context.Context, query outbound.SupportCaseListQuery) (outbound.SupportCaseListPage, error) {
|
||||
const location = "supportCaseRepository.ListOwned"
|
||||
if query.OwnerID == uuid.Nil || query.Limit < 1 || query.Limit > outbound.MaxSupportCasePageSize {
|
||||
return outbound.SupportCaseListPage{}, fmt.Errorf("%s - owner and page limit are invalid: %w", location, domain.ErrInvalidSupportCase)
|
||||
}
|
||||
params := sqlc.ListOwnedSupportCasesParams{OwnerID: pgUUID(query.OwnerID), RowLimit: query.Limit + 1}
|
||||
if query.After != nil {
|
||||
if query.After.ID.IsZero() || !validSupportCasePositionTime(query.After.CreatedAt) {
|
||||
return outbound.SupportCaseListPage{}, fmt.Errorf("%s - cursor position is invalid: %w", location, domain.ErrInvalidSupportCase)
|
||||
}
|
||||
params.AfterCreatedAt = pgTime(query.After.CreatedAt.UTC())
|
||||
params.AfterID = pgUUID(query.After.ID.UUID())
|
||||
}
|
||||
rows, err := repository.queries.ListOwnedSupportCases(ctx, params)
|
||||
if err != nil {
|
||||
return outbound.SupportCaseListPage{}, fmt.Errorf("%s - select owner-scoped summaries: %w", location, mapSupportCaseError(err))
|
||||
}
|
||||
page := outbound.SupportCaseListPage{HasMore: len(rows) > int(query.Limit)}
|
||||
if page.HasMore {
|
||||
rows = rows[:query.Limit]
|
||||
}
|
||||
page.Items = make([]domain.SupportCaseSummary, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
summary, err := supportCaseSummaryFromRow(row)
|
||||
if err != nil {
|
||||
return outbound.SupportCaseListPage{}, fmt.Errorf("%s - restore stored summary: %w", location, err)
|
||||
}
|
||||
page.Items = append(page.Items, summary)
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func (repository supportCaseRepository) DeleteCreateOutcome(ctx context.Context, scope [outbound.IdempotencyDigestSize]byte) error {
|
||||
const location = "supportCaseRepository.DeleteCreateOutcome"
|
||||
if scope == ([outbound.IdempotencyDigestSize]byte{}) {
|
||||
return fmt.Errorf("%s - idempotency scope must be set", location)
|
||||
}
|
||||
if err := repository.queries.DeleteSupportCaseCreateOutcome(ctx, scope[:]); err != nil {
|
||||
return fmt.Errorf("%s - delete expired outcome: %w", location, mapSupportCaseError(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository supportCaseRepository) SaveCreateOutcome(
|
||||
ctx context.Context,
|
||||
scope [outbound.IdempotencyDigestSize]byte,
|
||||
outcome domain.SupportCaseCreateOutcome,
|
||||
createdAt time.Time,
|
||||
) error {
|
||||
const location = "supportCaseRepository.SaveCreateOutcome"
|
||||
if scope == ([outbound.IdempotencyDigestSize]byte{}) || !validSupportCasePositionTime(createdAt) {
|
||||
return fmt.Errorf("%s - scope and creation time must be valid", location)
|
||||
}
|
||||
validated, err := domain.RestoreSupportCaseCreateOutcome(outcome.Snapshot())
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - validate outcome: %w", location, err)
|
||||
}
|
||||
snapshot := validated.Snapshot()
|
||||
encoded := []byte(`{}`)
|
||||
var targetWasLate bool
|
||||
if snapshot.Kind == domain.SupportCaseCreateOutcomeCreated {
|
||||
encoded, err = json.Marshal(snapshot.Case)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - encode outcome snapshot", location)
|
||||
}
|
||||
if len(encoded) > maxSupportCaseSnapshotBytes {
|
||||
return fmt.Errorf("%s - outcome snapshot exceeds its storage bound: %w", location, domain.ErrInvalidSupportCase)
|
||||
}
|
||||
targetWasLate = snapshot.TargetWasLate
|
||||
}
|
||||
if err := repository.queries.InsertSupportCaseCreateOutcome(ctx, sqlc.InsertSupportCaseCreateOutcomeParams{
|
||||
ScopeHash: scope[:], OutcomeKind: string(snapshot.Kind), CaseSnapshot: encoded,
|
||||
TargetWasLate: targetWasLate, CreatedAt: pgTime(createdAt.UTC().Truncate(time.Microsecond)),
|
||||
}); err != nil {
|
||||
return fmt.Errorf("%s - insert immutable outcome: %w", location, mapSupportCaseError(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository supportCaseRepository) GetCreateOutcome(
|
||||
ctx context.Context,
|
||||
scope [outbound.IdempotencyDigestSize]byte,
|
||||
) (domain.SupportCaseCreateOutcome, error) {
|
||||
const location = "supportCaseRepository.GetCreateOutcome"
|
||||
if scope == ([outbound.IdempotencyDigestSize]byte{}) {
|
||||
return domain.SupportCaseCreateOutcome{}, fmt.Errorf("%s - idempotency scope must be set", location)
|
||||
}
|
||||
row, err := repository.queries.ReadSupportCaseCreateOutcome(ctx, scope[:])
|
||||
if err != nil {
|
||||
return domain.SupportCaseCreateOutcome{}, fmt.Errorf("%s - read immutable outcome: %w", location, mapSupportCaseNoRows(err, outbound.ErrSupportCaseCreateOutcomeNotFound))
|
||||
}
|
||||
snapshot := domain.SupportCaseCreateOutcomeSnapshot{Kind: domain.SupportCaseCreateOutcomeKind(row.OutcomeKind)}
|
||||
if snapshot.Kind == domain.SupportCaseCreateOutcomeCreated {
|
||||
encoded, ok := supportCaseJSONBytes(row.CaseSnapshot)
|
||||
if !ok || len(encoded) == 0 || len(encoded) > maxSupportCaseSnapshotBytes || !row.TargetWasLate.Valid {
|
||||
return domain.SupportCaseCreateOutcome{}, fmt.Errorf("%s - stored created outcome is invalid", location)
|
||||
}
|
||||
var stored domain.SupportCaseSnapshot
|
||||
if err := decodeSupportCaseJSON(encoded, &stored); err != nil {
|
||||
return domain.SupportCaseCreateOutcome{}, fmt.Errorf("%s - stored case snapshot is invalid", location)
|
||||
}
|
||||
snapshot.Case = &stored
|
||||
snapshot.TargetWasLate = row.TargetWasLate.Bool
|
||||
} else if row.TargetWasLate.Valid {
|
||||
return domain.SupportCaseCreateOutcome{}, fmt.Errorf("%s - stored failure outcome has a late flag", location)
|
||||
}
|
||||
outcome, err := domain.RestoreSupportCaseCreateOutcome(snapshot)
|
||||
if err != nil {
|
||||
return domain.SupportCaseCreateOutcome{}, fmt.Errorf("%s - validate stored outcome: %w", location, err)
|
||||
}
|
||||
return outcome, nil
|
||||
}
|
||||
|
||||
func (repository supportCaseRepository) Consume(
|
||||
ctx context.Context,
|
||||
ownerID uuid.UUID,
|
||||
at time.Time,
|
||||
maxRequests int32,
|
||||
window time.Duration,
|
||||
) (outbound.SupportCaseRequestLimitResult, error) {
|
||||
const location = "supportCaseRepository.Consume"
|
||||
if ownerID == uuid.Nil || !validSupportCasePositionTime(at) || maxRequests < 1 || window < time.Second ||
|
||||
window > domain.MaxSupportRequestWindow || window%time.Second != 0 {
|
||||
return outbound.SupportCaseRequestLimitResult{}, fmt.Errorf("%s - request budget parameters are invalid: %w", location, domain.ErrInvalidSupportCase)
|
||||
}
|
||||
at = at.UTC().Truncate(time.Microsecond)
|
||||
if _, err := repository.queries.PruneSupportCaseRequestEvents(ctx, sqlc.PruneSupportCaseRequestEventsParams{
|
||||
OwnerID: pgUUID(ownerID), At: pgTime(at),
|
||||
}); err != nil {
|
||||
return outbound.SupportCaseRequestLimitResult{}, fmt.Errorf("%s - prune request history: %w", location, mapSupportCaseError(err))
|
||||
}
|
||||
windowStart := at.Add(-window)
|
||||
count, err := repository.queries.CountSupportCaseRequestEvents(ctx, sqlc.CountSupportCaseRequestEventsParams{
|
||||
OwnerID: pgUUID(ownerID), WindowStart: pgTime(windowStart), At: pgTime(at),
|
||||
})
|
||||
if err != nil {
|
||||
return outbound.SupportCaseRequestLimitResult{}, fmt.Errorf("%s - count request history: %w", location, mapSupportCaseError(err))
|
||||
}
|
||||
if count.EventCount >= int64(maxRequests) {
|
||||
first, ok := supportCaseFirstEventTime(count.FirstInWindow)
|
||||
if !ok {
|
||||
return outbound.SupportCaseRequestLimitResult{}, fmt.Errorf("%s - oldest qualifying event is missing", location)
|
||||
}
|
||||
retryAfter := first.Add(window).Sub(at)
|
||||
if retryAfter <= 0 {
|
||||
return outbound.SupportCaseRequestLimitResult{}, fmt.Errorf("%s - retry interval is invalid", location)
|
||||
}
|
||||
return outbound.SupportCaseRequestLimitResult{Allowed: false, RetryAfter: retryAfter}, nil
|
||||
}
|
||||
if err := repository.queries.InsertSupportCaseRequestEvent(ctx, sqlc.InsertSupportCaseRequestEventParams{
|
||||
OwnerID: pgUUID(ownerID), RequestedAt: pgTime(at),
|
||||
}); err != nil {
|
||||
return outbound.SupportCaseRequestLimitResult{}, fmt.Errorf("%s - record request: %w", location, mapSupportCaseError(err))
|
||||
}
|
||||
return outbound.SupportCaseRequestLimitResult{Allowed: true}, nil
|
||||
}
|
||||
|
||||
func (repository supportCaseRepository) LockOwner(ctx context.Context, ownerID uuid.UUID) (time.Time, error) {
|
||||
const location = "supportCaseRepository.LockOwner"
|
||||
if ownerID == uuid.Nil {
|
||||
return time.Time{}, fmt.Errorf("%s - owner ID must be set", location)
|
||||
}
|
||||
if err := repository.queries.LockSupportCaseRequestBudget(ctx, pgUUID(ownerID)); err != nil {
|
||||
return time.Time{}, fmt.Errorf("%s - take transaction lock: %w", location, mapSupportCaseError(err))
|
||||
}
|
||||
latest, err := repository.queries.LatestSupportCaseRequestEvent(ctx, pgUUID(ownerID))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return time.Time{}, nil
|
||||
}
|
||||
if err != nil {
|
||||
return time.Time{}, fmt.Errorf("%s - read latest request timestamp: %w", location, mapSupportCaseError(err))
|
||||
}
|
||||
if !validSupportCasePositionTime(latest.Time) {
|
||||
return time.Time{}, fmt.Errorf("%s - stored request timestamp is invalid", location)
|
||||
}
|
||||
return latest.Time.UTC().Truncate(time.Microsecond), nil
|
||||
}
|
||||
|
||||
func supportCaseInsertParams(snapshot domain.SupportCaseSnapshot) sqlc.InsertSupportCaseParams {
|
||||
return sqlc.InsertSupportCaseParams{
|
||||
ID: pgUUID(snapshot.ID.UUID()), CaseNumber: snapshot.Number.String(), OwnerID: pgUUID(snapshot.OwnerID),
|
||||
CaseType: string(snapshot.Type), Status: string(snapshot.Status), Description: snapshot.Description,
|
||||
ObjectType: optionalSupportText(snapshot.Object, func(value *domain.SupportCaseReference) string { return string(value.Type) }),
|
||||
ObjectID: optionalSupportUUID(snapshot.Object),
|
||||
AssessmentSpecialization: optionalSupportAssessment(snapshot.AssessmentTarget, true),
|
||||
AssessmentGrade: optionalSupportAssessment(snapshot.AssessmentTarget, false),
|
||||
ComplaintReason: optionalSupportComplaint(snapshot.ComplaintReason), RubricVersion: optionalSupportInt32(snapshot.RubricVersion),
|
||||
RubricOpeningID: optionalSupportUUIDPointer(snapshot.RubricOpeningID),
|
||||
RubricPolicyVersionID: optionalSupportPolicyID(snapshot.RubricPolicyID),
|
||||
TargetBusinessDays: int32(snapshot.ResponseTarget.BusinessDays), TargetDueAt: pgTime(snapshot.ResponseTarget.DueAt),
|
||||
TargetAnsweredAt: pgOptionalTime(snapshot.ResponseTarget.AnsweredAt), TargetPolicyVersion: snapshot.ResponseTarget.PolicyVersion,
|
||||
TargetCalendarVersion: snapshot.ResponseTarget.CalendarVersion,
|
||||
DecisionOutcome: optionalSupportDecision(snapshot.Decision, true), DecisionReason: optionalSupportDecision(snapshot.Decision, false),
|
||||
DecisionAt: optionalSupportDecisionTime(snapshot.Decision), CreatedAt: pgTime(snapshot.CreatedAt), UpdatedAt: pgTime(snapshot.UpdatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func supportCaseEventParams(caseID uuid.UUID, event domain.SupportCaseEventSnapshot) sqlc.InsertSupportCaseEventParams {
|
||||
return sqlc.InsertSupportCaseEventParams{
|
||||
CaseID: pgUUID(caseID), Sequence: event.Sequence, EventKind: string(event.Kind), ActorKind: string(event.Actor),
|
||||
OccurredAt: pgTime(event.OccurredAt), Status: optionalSupportEventStatus(event.Status), Message: optionalSupportEventMessage(event.Message),
|
||||
}
|
||||
}
|
||||
|
||||
func supportCaseSnapshotFromRow(row sqlc.SupportCase, events []sqlc.ReadSupportCaseEventsRow) (domain.SupportCaseSnapshot, error) {
|
||||
const location = "supportCaseSnapshotFromRow"
|
||||
if !row.ID.Valid || !row.OwnerID.Valid || !row.TargetDueAt.Valid || !row.CreatedAt.Valid || !row.UpdatedAt.Valid {
|
||||
return domain.SupportCaseSnapshot{}, fmt.Errorf("%s - required stored fields are missing", location)
|
||||
}
|
||||
number, err := domain.ParseSupportCaseNumber(row.CaseNumber)
|
||||
if err != nil {
|
||||
return domain.SupportCaseSnapshot{}, fmt.Errorf("%s - case number is invalid", location)
|
||||
}
|
||||
snapshot := domain.SupportCaseSnapshot{
|
||||
ID: domain.SupportCaseID(uuid.UUID(row.ID.Bytes)), Number: number, OwnerID: uuid.UUID(row.OwnerID.Bytes),
|
||||
Type: domain.SupportCaseType(row.CaseType), Status: domain.SupportCaseStatus(row.Status), Description: row.Description,
|
||||
Object: supportCaseReferenceFromColumns(row.ObjectType, row.ObjectID),
|
||||
AssessmentTarget: supportCaseAssessmentFromColumns(row.AssessmentSpecialization, row.AssessmentGrade),
|
||||
ComplaintReason: optionalSupportCaseComplaint(row.ComplaintReason), RubricVersion: optionalSupportCaseInt4(row.RubricVersion),
|
||||
RubricOpeningID: optionalSupportCaseUUID(row.RubricOpeningID),
|
||||
RubricPolicyID: optionalSupportCasePolicyID(row.RubricPolicyVersionID),
|
||||
ResponseTarget: domain.SupportResponseTargetSnapshot{
|
||||
BusinessDays: domain.BusinessDays(row.TargetBusinessDays), DueAt: row.TargetDueAt.Time,
|
||||
AnsweredAt: optionalTime(row.TargetAnsweredAt), PolicyVersion: row.TargetPolicyVersion,
|
||||
CalendarVersion: row.TargetCalendarVersion,
|
||||
},
|
||||
Decision: supportCaseDecisionFromColumns(row.DecisionOutcome, row.DecisionReason, row.DecisionAt),
|
||||
CreatedAt: row.CreatedAt.Time, UpdatedAt: row.UpdatedAt.Time,
|
||||
History: make([]domain.SupportCaseEventSnapshot, 0, len(events)),
|
||||
}
|
||||
for _, stored := range events {
|
||||
if !stored.OccurredAt.Valid {
|
||||
return domain.SupportCaseSnapshot{}, fmt.Errorf("%s - stored event timestamp is missing", location)
|
||||
}
|
||||
snapshot.History = append(snapshot.History, domain.SupportCaseEventSnapshot{
|
||||
Sequence: stored.Sequence, Kind: domain.SupportCaseEventKind(stored.EventKind), Actor: domain.SupportCaseActorKind(stored.ActorKind),
|
||||
OccurredAt: stored.OccurredAt.Time, Status: optionalSupportCaseStatus(stored.Status), Message: optionalSupportCaseText(stored.Message),
|
||||
})
|
||||
}
|
||||
return snapshot, nil
|
||||
}
|
||||
|
||||
func supportCaseSummaryFromRow(row sqlc.ListOwnedSupportCasesRow) (domain.SupportCaseSummary, error) {
|
||||
const location = "supportCaseSummaryFromRow"
|
||||
if !row.ID.Valid || !row.CreatedAt.Valid || !row.UpdatedAt.Valid || !row.TargetDueAt.Valid {
|
||||
return domain.SupportCaseSummary{}, fmt.Errorf("%s - required stored fields are missing", location)
|
||||
}
|
||||
number, err := domain.ParseSupportCaseNumber(row.CaseNumber)
|
||||
if err != nil {
|
||||
return domain.SupportCaseSummary{}, fmt.Errorf("%s - case number is invalid", location)
|
||||
}
|
||||
summary := domain.SupportCaseSummary{
|
||||
ID: domain.SupportCaseID(uuid.UUID(row.ID.Bytes)), Number: number, Type: domain.SupportCaseType(row.CaseType),
|
||||
Status: domain.SupportCaseStatus(row.Status), Object: supportCaseReferenceFromColumns(row.ObjectType, row.ObjectID),
|
||||
AssessmentTarget: supportCaseAssessmentFromColumns(row.AssessmentSpecialization, row.AssessmentGrade),
|
||||
ResponseTarget: domain.SupportResponseTargetSnapshot{
|
||||
BusinessDays: domain.BusinessDays(row.TargetBusinessDays), DueAt: row.TargetDueAt.Time,
|
||||
AnsweredAt: optionalTime(row.TargetAnsweredAt), PolicyVersion: row.TargetPolicyVersion,
|
||||
CalendarVersion: row.TargetCalendarVersion,
|
||||
},
|
||||
CreatedAt: row.CreatedAt.Time, UpdatedAt: row.UpdatedAt.Time,
|
||||
}
|
||||
if row.DecisionOutcome.Valid {
|
||||
outcome := domain.SupportCaseDecisionOutcome(row.DecisionOutcome.String)
|
||||
summary.DecisionOutcome = &outcome
|
||||
}
|
||||
return domain.RestoreSupportCaseSummary(summary)
|
||||
}
|
||||
|
||||
func supportCaseReferenceFromColumns(objectType pgtype.Text, objectID pgtype.UUID) *domain.SupportCaseReference {
|
||||
if !objectType.Valid && !objectID.Valid {
|
||||
return nil
|
||||
}
|
||||
return &domain.SupportCaseReference{Type: domain.SupportCaseObjectType(objectType.String), ID: uuid.UUID(objectID.Bytes)}
|
||||
}
|
||||
|
||||
func supportCaseAssessmentFromColumns(specialization, grade pgtype.Text) *domain.SupportCaseAssessmentTarget {
|
||||
if !specialization.Valid && !grade.Valid {
|
||||
return nil
|
||||
}
|
||||
return &domain.SupportCaseAssessmentTarget{
|
||||
Specialization: domain.SpecializationCode(specialization.String), Grade: domain.GradeCode(grade.String),
|
||||
}
|
||||
}
|
||||
|
||||
func supportCaseDecisionFromColumns(outcome, reason pgtype.Text, at pgtype.Timestamptz) *domain.SupportCaseDecisionSnapshot {
|
||||
if !outcome.Valid && !reason.Valid && !at.Valid {
|
||||
return nil
|
||||
}
|
||||
return &domain.SupportCaseDecisionSnapshot{
|
||||
Outcome: domain.SupportCaseDecisionOutcome(outcome.String), Reason: reason.String, DecidedAt: at.Time,
|
||||
}
|
||||
}
|
||||
|
||||
func optionalSupportText[T any](value *T, selectValue func(*T) string) pgtype.Text {
|
||||
if value == nil {
|
||||
return pgtype.Text{}
|
||||
}
|
||||
return pgText(selectValue(value))
|
||||
}
|
||||
|
||||
func optionalSupportUUID(reference *domain.SupportCaseReference) pgtype.UUID {
|
||||
if reference == nil {
|
||||
return pgtype.UUID{}
|
||||
}
|
||||
return pgUUID(reference.ID)
|
||||
}
|
||||
|
||||
func optionalSupportUUIDPointer(value *uuid.UUID) pgtype.UUID {
|
||||
if value == nil {
|
||||
return pgtype.UUID{}
|
||||
}
|
||||
return pgUUID(*value)
|
||||
}
|
||||
|
||||
func optionalSupportPolicyID(value *domain.PolicyVersionID) pgtype.UUID {
|
||||
if value == nil {
|
||||
return pgtype.UUID{}
|
||||
}
|
||||
return pgUUID(value.UUID())
|
||||
}
|
||||
|
||||
func optionalSupportAssessment(target *domain.SupportCaseAssessmentTarget, specialization bool) pgtype.Text {
|
||||
if target == nil {
|
||||
return pgtype.Text{}
|
||||
}
|
||||
if specialization {
|
||||
return pgText(string(target.Specialization))
|
||||
}
|
||||
return pgText(string(target.Grade))
|
||||
}
|
||||
|
||||
func optionalSupportComplaint(reason *domain.SupportCaseComplaintReason) pgtype.Text {
|
||||
if reason == nil {
|
||||
return pgtype.Text{}
|
||||
}
|
||||
return pgText(string(*reason))
|
||||
}
|
||||
|
||||
func optionalSupportInt32(value *int32) pgtype.Int4 {
|
||||
if value == nil {
|
||||
return pgtype.Int4{}
|
||||
}
|
||||
return pgtype.Int4{Int32: *value, Valid: true}
|
||||
}
|
||||
|
||||
func optionalSupportDecision(decision *domain.SupportCaseDecisionSnapshot, outcome bool) pgtype.Text {
|
||||
if decision == nil {
|
||||
return pgtype.Text{}
|
||||
}
|
||||
if outcome {
|
||||
return pgText(string(decision.Outcome))
|
||||
}
|
||||
return pgText(decision.Reason)
|
||||
}
|
||||
|
||||
func optionalSupportDecisionTime(decision *domain.SupportCaseDecisionSnapshot) pgtype.Timestamptz {
|
||||
if decision == nil {
|
||||
return pgtype.Timestamptz{}
|
||||
}
|
||||
return pgTime(decision.DecidedAt)
|
||||
}
|
||||
|
||||
func optionalSupportEventStatus(status *domain.SupportCaseStatus) pgtype.Text {
|
||||
if status == nil {
|
||||
return pgtype.Text{}
|
||||
}
|
||||
return pgText(string(*status))
|
||||
}
|
||||
|
||||
func optionalSupportEventMessage(message *string) pgtype.Text {
|
||||
if message == nil {
|
||||
return pgtype.Text{}
|
||||
}
|
||||
return pgText(*message)
|
||||
}
|
||||
|
||||
func optionalSupportCaseComplaint(value pgtype.Text) *domain.SupportCaseComplaintReason {
|
||||
if !value.Valid {
|
||||
return nil
|
||||
}
|
||||
result := domain.SupportCaseComplaintReason(value.String)
|
||||
return &result
|
||||
}
|
||||
|
||||
func optionalSupportCaseInt4(value pgtype.Int4) *int32 {
|
||||
if !value.Valid {
|
||||
return nil
|
||||
}
|
||||
return &value.Int32
|
||||
}
|
||||
|
||||
func optionalSupportCaseUUID(value pgtype.UUID) *uuid.UUID {
|
||||
if !value.Valid {
|
||||
return nil
|
||||
}
|
||||
result := uuid.UUID(value.Bytes)
|
||||
return &result
|
||||
}
|
||||
|
||||
func optionalSupportCasePolicyID(value pgtype.UUID) *domain.PolicyVersionID {
|
||||
if !value.Valid {
|
||||
return nil
|
||||
}
|
||||
result := domain.PolicyVersionID(value.Bytes)
|
||||
return &result
|
||||
}
|
||||
|
||||
func optionalSupportCaseStatus(value pgtype.Text) *domain.SupportCaseStatus {
|
||||
if !value.Valid {
|
||||
return nil
|
||||
}
|
||||
result := domain.SupportCaseStatus(value.String)
|
||||
return &result
|
||||
}
|
||||
|
||||
func optionalSupportCaseText(value pgtype.Text) *string {
|
||||
if !value.Valid {
|
||||
return nil
|
||||
}
|
||||
result := value.String
|
||||
return &result
|
||||
}
|
||||
|
||||
func supportCaseFirstEventTime(value any) (time.Time, bool) {
|
||||
switch typed := value.(type) {
|
||||
case time.Time:
|
||||
return typed, !typed.IsZero()
|
||||
case pgtype.Timestamptz:
|
||||
return typed.Time, typed.Valid && !typed.Time.IsZero()
|
||||
case *time.Time:
|
||||
if typed != nil {
|
||||
return *typed, !typed.IsZero()
|
||||
}
|
||||
case nil:
|
||||
return time.Time{}, false
|
||||
}
|
||||
return time.Time{}, false
|
||||
}
|
||||
|
||||
func supportCaseJSONBytes(value any) ([]byte, bool) {
|
||||
switch typed := value.(type) {
|
||||
case string:
|
||||
return []byte(typed), true
|
||||
case []byte:
|
||||
return typed, true
|
||||
default:
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
|
||||
func decodeSupportCaseJSON(encoded []byte, destination any) error {
|
||||
decoder := json.NewDecoder(bytes.NewReader(encoded))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(destination); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := decoder.Decode(new(any)); !errors.Is(err, io.EOF) {
|
||||
return errors.New("stored support case snapshot contains trailing data")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validSupportCasePositionTime(value time.Time) bool {
|
||||
return !value.IsZero() && value.Year() >= 1 && value.Year() <= 9999 && value.Unix() >= 0 &&
|
||||
value.Nanosecond()%int(time.Microsecond) == 0
|
||||
}
|
||||
|
||||
func mapSupportCaseNoRows(err, sentinel error) error {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return sentinel
|
||||
}
|
||||
return mapSupportCaseError(err)
|
||||
}
|
||||
|
||||
func mapSupportCaseError(err error) error {
|
||||
var pgError *pgconn.PgError
|
||||
if !errors.As(err, &pgError) {
|
||||
return sanitizeConnectError(err)
|
||||
}
|
||||
key := constraintViolation{code: pgError.Code, constraint: pgError.ConstraintName}
|
||||
if sentinel, ok := supportCaseConstraintErrors[key]; ok {
|
||||
return fmt.Errorf("postgres.mapSupportCaseError - violate constraint %s: %w", pgError.ConstraintName, sentinel)
|
||||
}
|
||||
return markTransactionConflict(&databaseError{code: pgError.Code, constraint: pgError.ConstraintName})
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
var _ outbound.SupportCaseRubricRepository = supportCaseRubricRepository{}
|
||||
|
||||
type supportCaseRubricRepository struct {
|
||||
queries *sqlc.Queries
|
||||
bank assessmentBankRepository
|
||||
}
|
||||
|
||||
func (unit *UnitOfWork) SupportCaseRubrics() outbound.SupportCaseRubricRepository {
|
||||
return supportCaseRubricRepository{
|
||||
queries: unit.queries,
|
||||
bank: assessmentBankRepository{queries: unit.queries, transactional: true},
|
||||
}
|
||||
}
|
||||
|
||||
func (repository supportCaseRubricRepository) ResolveCurrent(
|
||||
ctx context.Context,
|
||||
specialization domain.SpecializationCode,
|
||||
grade domain.GradeCode,
|
||||
) (*outbound.SupportCaseRubric, error) {
|
||||
const location = "supportCaseRubricRepository.ResolveCurrent"
|
||||
if !repository.bank.transactional {
|
||||
return nil, fmt.Errorf("%s - rubric resolution needs a transaction: %w", location, outbound.ErrAssessmentLockOutsideTransaction)
|
||||
}
|
||||
if !specialization.IsKnown() || !grade.IsKnown() {
|
||||
return nil, fmt.Errorf("%s - target is invalid: %w", location, domain.ErrInvalidAssessmentFamily)
|
||||
}
|
||||
row, available, err := repository.currentUniqueOpening(ctx, specialization, grade)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - resolve current target opening: %w", location, err)
|
||||
}
|
||||
if !available {
|
||||
return nil, nil
|
||||
}
|
||||
selectionRow := supportRubricSelectionRow(row)
|
||||
selection, err := repository.bank.currentSelectionFromRow(ctx, selectionRow)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - validate reviewed rubric manifest: %w", location, err)
|
||||
}
|
||||
if !supportRubricSelectionMatches(selection, row) {
|
||||
return nil, fmt.Errorf("%s - current rubric pin changed during resolution: %w", location, outbound.ErrAssessmentSelectionUnavailable)
|
||||
}
|
||||
|
||||
return &outbound.SupportCaseRubric{
|
||||
Version: selection.ProductPolicyVersion,
|
||||
OpeningID: selection.Opening.ID,
|
||||
PolicyVersionID: selection.Opening.PolicyVersionID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (repository supportCaseRubricRepository) currentUniqueOpening(
|
||||
ctx context.Context,
|
||||
specialization domain.SpecializationCode,
|
||||
grade domain.GradeCode,
|
||||
) (sqlc.ResolveCurrentSupportCaseRubricsRow, bool, error) {
|
||||
initial, err := repository.currentRows(ctx, specialization, grade)
|
||||
if err != nil {
|
||||
return sqlc.ResolveCurrentSupportCaseRubricsRow{}, false, fmt.Errorf("read current target bindings: %w", err)
|
||||
}
|
||||
initialRow, unique := uniqueSupportRubricOpening(initial)
|
||||
if !unique {
|
||||
return sqlc.ResolveCurrentSupportCaseRubricsRow{}, false, nil
|
||||
}
|
||||
category, err := domain.ParseAssessmentCategory(initialRow.Category)
|
||||
if err != nil {
|
||||
return sqlc.ResolveCurrentSupportCaseRubricsRow{}, false, fmt.Errorf("parse current category: %w", domain.ErrInvalidAssessmentFamily)
|
||||
}
|
||||
if err := repository.bank.LockCategory(ctx, category); err != nil {
|
||||
return sqlc.ResolveCurrentSupportCaseRubricsRow{}, false, fmt.Errorf("lock current category: %w", err)
|
||||
}
|
||||
current, err := repository.currentRows(ctx, specialization, grade)
|
||||
if err != nil {
|
||||
return sqlc.ResolveCurrentSupportCaseRubricsRow{}, false, fmt.Errorf("recheck current target bindings: %w", err)
|
||||
}
|
||||
currentRow, unique := uniqueSupportRubricOpening(current)
|
||||
if !unique || currentRow.OpeningID.Bytes != initialRow.OpeningID.Bytes {
|
||||
return sqlc.ResolveCurrentSupportCaseRubricsRow{}, false, nil
|
||||
}
|
||||
return currentRow, true, nil
|
||||
}
|
||||
|
||||
func supportRubricSelectionMatches(
|
||||
selection outbound.AssessmentBankSelection,
|
||||
row sqlc.ResolveCurrentSupportCaseRubricsRow,
|
||||
) bool {
|
||||
return selection.ProductPolicyVersion > 0 && !selection.Opening.PolicyVersionID.IsZero() &&
|
||||
selection.Opening.ID == row.OpeningID.Bytes &&
|
||||
selection.Opening.PolicyVersionID == domain.PolicyVersionID(row.PolicyVersionID.Bytes) &&
|
||||
selection.ProductPolicyVersion == row.EffectivePolicyVersion.Int32
|
||||
}
|
||||
|
||||
func (repository supportCaseRubricRepository) currentRows(
|
||||
ctx context.Context,
|
||||
specialization domain.SpecializationCode,
|
||||
grade domain.GradeCode,
|
||||
) ([]sqlc.ResolveCurrentSupportCaseRubricsRow, error) {
|
||||
rows, err := repository.queries.ResolveCurrentSupportCaseRubrics(ctx, sqlc.ResolveCurrentSupportCaseRubricsParams{
|
||||
Specialization: string(specialization), Grade: string(grade),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, mapAssessmentError(err)
|
||||
}
|
||||
current := make([]sqlc.ResolveCurrentSupportCaseRubricsRow, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
metadata, available, err := currentAssessmentSelectionMetadata(supportRubricSelectionRow(row))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("validate current catalog binding: %w", err)
|
||||
}
|
||||
if !available || metadata.Specialization() != specialization || metadata.Grade() != grade {
|
||||
continue
|
||||
}
|
||||
current = append(current, row)
|
||||
}
|
||||
return current, nil
|
||||
}
|
||||
|
||||
func supportRubricSelectionRow(row sqlc.ResolveCurrentSupportCaseRubricsRow) sqlc.ResolveCurrentAssessmentSelectionRow {
|
||||
return sqlc.ResolveCurrentAssessmentSelectionRow(row)
|
||||
}
|
||||
|
||||
func uniqueSupportRubricOpening(
|
||||
rows []sqlc.ResolveCurrentSupportCaseRubricsRow,
|
||||
) (sqlc.ResolveCurrentSupportCaseRubricsRow, bool) {
|
||||
var selected sqlc.ResolveCurrentSupportCaseRubricsRow
|
||||
seen := make(map[uuid.UUID]struct{}, len(rows))
|
||||
for _, row := range rows {
|
||||
if !row.OpeningID.Valid || row.OpeningID.Bytes == uuid.Nil {
|
||||
continue
|
||||
}
|
||||
if _, exists := seen[row.OpeningID.Bytes]; exists {
|
||||
continue
|
||||
}
|
||||
seen[row.OpeningID.Bytes] = struct{}{}
|
||||
if len(seen) > 1 {
|
||||
return sqlc.ResolveCurrentSupportCaseRubricsRow{}, false
|
||||
}
|
||||
selected = row
|
||||
}
|
||||
return selected, len(seen) == 1
|
||||
}
|
||||
@@ -37,6 +37,7 @@ func NewTransactor(pool *pgxpool.Pool) *Transactor {
|
||||
}
|
||||
|
||||
var _ outbound.Transactor = (*Transactor)(nil)
|
||||
var _ outbound.ReadOnlySnapshotTransactor = (*Transactor)(nil)
|
||||
|
||||
// transactionContextKey marks a context passed to a transaction callback so a
|
||||
// nested WithinTransaction call fails instead of opening a second connection.
|
||||
@@ -81,6 +82,42 @@ func (transactor *Transactor) WithinTransaction(
|
||||
return nil
|
||||
}
|
||||
|
||||
// WithinReadOnlySnapshot runs a callback against one repeatable-read snapshot.
|
||||
// PostgreSQL rejects writes made through the supplied UnitOfWork.
|
||||
func (transactor *Transactor) WithinReadOnlySnapshot(
|
||||
ctx context.Context,
|
||||
fn func(ctx context.Context, unit outbound.UnitOfWork) error,
|
||||
) error {
|
||||
if ctx.Value(transactionContextKey{}) != nil {
|
||||
return fmt.Errorf("Transactor.WithinReadOnlySnapshot - begin transaction: %w", outbound.ErrNestedTransaction)
|
||||
}
|
||||
options := pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly}
|
||||
tx, err := transactor.pool.BeginTx(ctx, options)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Transactor.WithinReadOnlySnapshot - begin transaction: %w", sanitizeConnectError(err))
|
||||
}
|
||||
finished := false
|
||||
defer func() {
|
||||
if !finished {
|
||||
_ = rollback(ctx, tx)
|
||||
}
|
||||
}()
|
||||
|
||||
fnErr := fn(context.WithValue(ctx, transactionContextKey{}, true), &UnitOfWork{tx: tx, queries: sqlc.New(tx)})
|
||||
finished = true
|
||||
if fnErr != nil {
|
||||
fnErr = markTransactionConflict(fnErr)
|
||||
if rollbackErr := rollback(ctx, tx); rollbackErr != nil {
|
||||
return errors.Join(fnErr, fmt.Errorf("Transactor.WithinReadOnlySnapshot - roll back transaction: %w", rollbackErr))
|
||||
}
|
||||
return fnErr
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return fmt.Errorf("Transactor.WithinReadOnlySnapshot - commit transaction: %w", markTransactionConflict(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func rollback(ctx context.Context, tx pgx.Tx) error {
|
||||
rollbackContext, cancel := context.WithTimeout(context.WithoutCancel(ctx), rollbackTimeout)
|
||||
defer cancel()
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
package bootstrap
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/config"
|
||||
v1 "lincodex/backend/internal/adapter/primary/http/v1"
|
||||
"lincodex/backend/internal/adapter/secondary/postgres"
|
||||
"lincodex/backend/internal/usecase/assessment"
|
||||
"lincodex/backend/internal/usecase/identity"
|
||||
)
|
||||
|
||||
const assessmentPoolMaxConns = 8
|
||||
|
||||
func newAssessmentHandler(
|
||||
ctx context.Context,
|
||||
settings config.Config,
|
||||
logger *slog.Logger,
|
||||
keyring *identity.Keyring,
|
||||
) (*v1.AssessmentHandler, func(), error) {
|
||||
if settings.DatabaseURL == "" {
|
||||
logger.Warn("assessment operations are not served because DATABASE_URL is not set")
|
||||
return nil, func() {}, nil
|
||||
}
|
||||
if keyring == nil {
|
||||
return nil, nil, fmt.Errorf("bootstrap.newAssessmentHandler - identity keyring must be set")
|
||||
}
|
||||
pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, assessmentPoolMaxConns)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("bootstrap.newAssessmentHandler - create pool: %w", err)
|
||||
}
|
||||
transactor := postgres.NewTransactor(pool)
|
||||
service, err := assessment.NewAttemptService(transactor, transactor, keyring, time.Now)
|
||||
if err != nil {
|
||||
pool.Close()
|
||||
return nil, nil, fmt.Errorf("bootstrap.newAssessmentHandler - create service: %w", err)
|
||||
}
|
||||
return v1.NewAssessmentHandler(service), pool.Close, nil
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package bootstrap
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/config"
|
||||
v1 "lincodex/backend/internal/adapter/primary/http/v1"
|
||||
"lincodex/backend/internal/adapter/secondary/postgres"
|
||||
"lincodex/backend/internal/usecase/assessment"
|
||||
"lincodex/backend/internal/usecase/identity"
|
||||
)
|
||||
|
||||
func newAssessmentSignalHandler(
|
||||
ctx context.Context,
|
||||
settings config.Config,
|
||||
logger *slog.Logger,
|
||||
keyring *identity.Keyring,
|
||||
) (*v1.AssessmentSignalHandler, func(), error) {
|
||||
if settings.DatabaseURL == "" {
|
||||
logger.Warn("assessment signal operations are not served because DATABASE_URL is not set")
|
||||
return nil, func() {}, nil
|
||||
}
|
||||
if keyring == nil {
|
||||
return nil, nil, fmt.Errorf("bootstrap.newAssessmentSignalHandler - identity keyring must be set")
|
||||
}
|
||||
pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, assessmentPoolMaxConns)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("bootstrap.newAssessmentSignalHandler - create pool: %w", err)
|
||||
}
|
||||
service, err := assessment.NewSignalService(postgres.NewTransactor(pool), keyring, time.Now)
|
||||
if err != nil {
|
||||
pool.Close()
|
||||
return nil, nil, fmt.Errorf("bootstrap.newAssessmentSignalHandler - create service: %w", err)
|
||||
}
|
||||
return v1.NewAssessmentSignalHandler(service), pool.Close, nil
|
||||
}
|
||||
@@ -40,6 +40,11 @@ func newAPIHandler(
|
||||
questionnaireHandler *v1.QuestionnaireHandler,
|
||||
catalogHandler *v1.CatalogHandler,
|
||||
organizationHandler *v1.OrganizationHandler,
|
||||
needHandler *v1.NeedHandler,
|
||||
supportHandler *v1.SupportHandler,
|
||||
assessmentHandler *v1.AssessmentHandler,
|
||||
assessmentSignalHandler *v1.AssessmentSignalHandler,
|
||||
privacyHandler *v1.PrivacyHandler,
|
||||
) *v1.Handler {
|
||||
return v1.NewHandler(health, problems,
|
||||
v1.WithIdentity(identityHandler),
|
||||
@@ -48,6 +53,11 @@ func newAPIHandler(
|
||||
v1.WithQuestionnaire(questionnaireHandler),
|
||||
v1.WithCatalog(catalogHandler),
|
||||
v1.WithOrganization(organizationHandler),
|
||||
v1.WithNeed(needHandler),
|
||||
v1.WithSupport(supportHandler),
|
||||
v1.WithAssessment(assessmentHandler),
|
||||
v1.WithAssessmentSignals(assessmentSignalHandler),
|
||||
v1.WithPrivacy(privacyHandler),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -157,7 +167,7 @@ func newIdentityHandler(
|
||||
// IDENTITY_ALLOW_EPHEMERAL_KEY, which the configuration check demands for an
|
||||
// unset secret, a random one is drawn for this process. Idempotency records and
|
||||
// counters no longer match after restart, and CSRF tokens differ between
|
||||
// restarts and instances.
|
||||
// restarts and instances. Candidate aliases also change with the secret.
|
||||
func newIdentityKeyring(settings config.Config, logger *slog.Logger) (*identity.Keyring, error) {
|
||||
if settings.DatabaseURL == "" {
|
||||
return nil, nil
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
package bootstrap
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/config"
|
||||
v1 "lincodex/backend/internal/adapter/primary/http/v1"
|
||||
"lincodex/backend/internal/adapter/secondary/postgres"
|
||||
"lincodex/backend/internal/usecase/identity"
|
||||
"lincodex/backend/internal/usecase/need"
|
||||
)
|
||||
|
||||
const needPoolMaxConns = 8
|
||||
|
||||
func newNeedHandler(
|
||||
ctx context.Context,
|
||||
settings config.Config,
|
||||
logger *slog.Logger,
|
||||
keyring *identity.Keyring,
|
||||
) (*v1.NeedHandler, func(), error) {
|
||||
if settings.DatabaseURL == "" {
|
||||
logger.Warn("need operations are not served because DATABASE_URL is not set")
|
||||
return nil, func() {}, nil
|
||||
}
|
||||
if keyring == nil {
|
||||
return nil, nil, fmt.Errorf("bootstrap.newNeedHandler - identity keyring must be set")
|
||||
}
|
||||
pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, needPoolMaxConns)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("bootstrap.newNeedHandler - create pool: %w", err)
|
||||
}
|
||||
service, err := need.NewService(need.Dependencies{
|
||||
Transactor: postgres.NewTransactor(pool),
|
||||
Keyring: keyring,
|
||||
Clock: time.Now,
|
||||
})
|
||||
if err != nil {
|
||||
pool.Close()
|
||||
return nil, nil, fmt.Errorf("bootstrap.newNeedHandler - create service: %w", err)
|
||||
}
|
||||
return v1.NewNeedHandler(service), pool.Close, nil
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package bootstrap
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/config"
|
||||
v1 "lincodex/backend/internal/adapter/primary/http/v1"
|
||||
"lincodex/backend/internal/adapter/secondary/postgres"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/usecase/anonymousprofile"
|
||||
"lincodex/backend/internal/usecase/candidateprivacy"
|
||||
"lincodex/backend/internal/usecase/candidateview"
|
||||
"lincodex/backend/internal/usecase/companyquota"
|
||||
"lincodex/backend/internal/usecase/identity"
|
||||
)
|
||||
|
||||
const privacyPoolMaxConns = 4
|
||||
|
||||
func newPrivacyHandler(
|
||||
ctx context.Context,
|
||||
settings config.Config,
|
||||
logger *slog.Logger,
|
||||
keyring *identity.Keyring,
|
||||
) (*v1.PrivacyHandler, func(), error) {
|
||||
if settings.DatabaseURL == "" {
|
||||
logger.Warn("privacy operations are not served because DATABASE_URL is not set")
|
||||
return nil, func() {}, nil
|
||||
}
|
||||
key, err := keyring.CandidateViewPseudonymKey()
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("bootstrap.newPrivacyHandler - derive projection key: %w", err)
|
||||
}
|
||||
pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, privacyPoolMaxConns)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("bootstrap.newPrivacyHandler - create pool: %w", err)
|
||||
}
|
||||
transactor := postgres.NewTransactor(pool)
|
||||
projector := anonymousprofile.NewService(postgres.NewPrivacyCohortStore(pool), key, time.Now)
|
||||
quota := companyquota.NewService(time.Now)
|
||||
views, err := candidateview.NewService(candidateview.Dependencies{
|
||||
Transactor: transactor, Projector: projector, PseudonymKey: key, Clock: time.Now,
|
||||
Quota: func(ctx context.Context, unit outbound.UnitOfWork, organization domain.Organization, candidateID uuid.UUID) (outbound.CompanyQuotaDecision, error) {
|
||||
return quota.ReserveCardView(ctx, unit, organization, candidateID)
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
pool.Close()
|
||||
return nil, nil, fmt.Errorf("bootstrap.newPrivacyHandler - create view service: %w", err)
|
||||
}
|
||||
privacy, err := candidateprivacy.NewService(candidateprivacy.Dependencies{Transactor: transactor, Clock: time.Now})
|
||||
if err != nil {
|
||||
pool.Close()
|
||||
return nil, nil, fmt.Errorf("bootstrap.newPrivacyHandler - create settings service: %w", err)
|
||||
}
|
||||
return v1.NewPrivacyHandler(views, privacy, settings.AppPublicURL), pool.Close, nil
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package bootstrap
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/config"
|
||||
v1 "lincodex/backend/internal/adapter/primary/http/v1"
|
||||
"lincodex/backend/internal/adapter/secondary/postgres"
|
||||
"lincodex/backend/internal/usecase/identity"
|
||||
"lincodex/backend/internal/usecase/supportcase"
|
||||
)
|
||||
|
||||
const supportPoolMaxConns = 8
|
||||
|
||||
func newSupportHandler(
|
||||
ctx context.Context,
|
||||
settings config.Config,
|
||||
logger *slog.Logger,
|
||||
keyring *identity.Keyring,
|
||||
) (*v1.SupportHandler, func(), error) {
|
||||
if settings.DatabaseURL == "" {
|
||||
logger.Warn("support operations are not served because DATABASE_URL is not set")
|
||||
return nil, func() {}, nil
|
||||
}
|
||||
if keyring == nil {
|
||||
return nil, nil, fmt.Errorf("bootstrap.newSupportHandler - identity keyring must be set")
|
||||
}
|
||||
pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, supportPoolMaxConns)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("bootstrap.newSupportHandler - create pool: %w", err)
|
||||
}
|
||||
service, err := supportcase.NewService(supportcase.Dependencies{
|
||||
Transactor: postgres.NewTransactor(pool),
|
||||
Keyring: keyring,
|
||||
Clock: time.Now,
|
||||
})
|
||||
if err != nil {
|
||||
pool.Close()
|
||||
return nil, nil, fmt.Errorf("bootstrap.newSupportHandler - create service: %w", err)
|
||||
}
|
||||
return v1.NewSupportHandler(service), pool.Close, nil
|
||||
}
|
||||
@@ -52,6 +52,11 @@ func initialize(
|
||||
newQuestionnaireHandler,
|
||||
newCatalogHandler,
|
||||
newOrganizationHandler,
|
||||
newNeedHandler,
|
||||
newSupportHandler,
|
||||
newAssessmentHandler,
|
||||
newAssessmentSignalHandler,
|
||||
newPrivacyHandler,
|
||||
newSessionSecurity,
|
||||
newRouter,
|
||||
newOutboxRelay,
|
||||
|
||||
@@ -109,10 +109,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
handler := newAPIHandler(healthHandler, responder, identityHandler, consentHandler, profileHandler, questionnaireHandler, catalogHandler, organizationHandler)
|
||||
sessionSecurity := newSessionSecurity(identityHandler)
|
||||
v := newTrustedProxies(config2)
|
||||
httpHandler, err := newRouter(healthHandler, handler, sessionSecurity, responder, metrics, logger, v, organizationHandler)
|
||||
needHandler, cleanup10, err := newNeedHandler(ctx, config2, logger, keyring)
|
||||
if err != nil {
|
||||
cleanup9()
|
||||
cleanup8()
|
||||
@@ -125,20 +122,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
relay, cleanup10, err := newOutboxRelay(ctx, config2, logger, metrics)
|
||||
if err != nil {
|
||||
cleanup9()
|
||||
cleanup8()
|
||||
cleanup7()
|
||||
cleanup6()
|
||||
cleanup5()
|
||||
cleanup4()
|
||||
cleanup3()
|
||||
cleanup2()
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
bootstrapEventConsumers, cleanup11, err := newEventConsumers(ctx, config2, logger, metrics)
|
||||
supportHandler, cleanup11, err := newSupportHandler(ctx, config2, logger, keyring)
|
||||
if err != nil {
|
||||
cleanup10()
|
||||
cleanup9()
|
||||
@@ -152,7 +136,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
worker, cleanup12, err := newJobWorker(ctx, config2, logger, metrics)
|
||||
assessmentHandler, cleanup12, err := newAssessmentHandler(ctx, config2, logger, keyring)
|
||||
if err != nil {
|
||||
cleanup11()
|
||||
cleanup10()
|
||||
@@ -167,7 +151,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
mailsenderWorker, cleanup13, err := newMailSenderWorker(ctx, config2, logger, metrics, mailSender)
|
||||
assessmentSignalHandler, cleanup13, err := newAssessmentSignalHandler(ctx, config2, logger, keyring)
|
||||
if err != nil {
|
||||
cleanup12()
|
||||
cleanup11()
|
||||
@@ -183,7 +167,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
sampler, cleanup14, err := newDeliveryMetrics(ctx, config2, logger, metrics)
|
||||
privacyHandler, cleanup14, err := newPrivacyHandler(ctx, config2, logger, keyring)
|
||||
if err != nil {
|
||||
cleanup13()
|
||||
cleanup12()
|
||||
@@ -200,8 +184,134 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
handler := newAPIHandler(healthHandler, responder, identityHandler, consentHandler, profileHandler, questionnaireHandler, catalogHandler, organizationHandler, needHandler, supportHandler, assessmentHandler, assessmentSignalHandler, privacyHandler)
|
||||
sessionSecurity := newSessionSecurity(identityHandler)
|
||||
v := newTrustedProxies(config2)
|
||||
httpHandler, err := newRouter(healthHandler, handler, sessionSecurity, responder, metrics, logger, v, organizationHandler)
|
||||
if err != nil {
|
||||
cleanup14()
|
||||
cleanup13()
|
||||
cleanup12()
|
||||
cleanup11()
|
||||
cleanup10()
|
||||
cleanup9()
|
||||
cleanup8()
|
||||
cleanup7()
|
||||
cleanup6()
|
||||
cleanup5()
|
||||
cleanup4()
|
||||
cleanup3()
|
||||
cleanup2()
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
relay, cleanup15, err := newOutboxRelay(ctx, config2, logger, metrics)
|
||||
if err != nil {
|
||||
cleanup14()
|
||||
cleanup13()
|
||||
cleanup12()
|
||||
cleanup11()
|
||||
cleanup10()
|
||||
cleanup9()
|
||||
cleanup8()
|
||||
cleanup7()
|
||||
cleanup6()
|
||||
cleanup5()
|
||||
cleanup4()
|
||||
cleanup3()
|
||||
cleanup2()
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
bootstrapEventConsumers, cleanup16, err := newEventConsumers(ctx, config2, logger, metrics)
|
||||
if err != nil {
|
||||
cleanup15()
|
||||
cleanup14()
|
||||
cleanup13()
|
||||
cleanup12()
|
||||
cleanup11()
|
||||
cleanup10()
|
||||
cleanup9()
|
||||
cleanup8()
|
||||
cleanup7()
|
||||
cleanup6()
|
||||
cleanup5()
|
||||
cleanup4()
|
||||
cleanup3()
|
||||
cleanup2()
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
worker, cleanup17, err := newJobWorker(ctx, config2, logger, metrics)
|
||||
if err != nil {
|
||||
cleanup16()
|
||||
cleanup15()
|
||||
cleanup14()
|
||||
cleanup13()
|
||||
cleanup12()
|
||||
cleanup11()
|
||||
cleanup10()
|
||||
cleanup9()
|
||||
cleanup8()
|
||||
cleanup7()
|
||||
cleanup6()
|
||||
cleanup5()
|
||||
cleanup4()
|
||||
cleanup3()
|
||||
cleanup2()
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
mailsenderWorker, cleanup18, err := newMailSenderWorker(ctx, config2, logger, metrics, mailSender)
|
||||
if err != nil {
|
||||
cleanup17()
|
||||
cleanup16()
|
||||
cleanup15()
|
||||
cleanup14()
|
||||
cleanup13()
|
||||
cleanup12()
|
||||
cleanup11()
|
||||
cleanup10()
|
||||
cleanup9()
|
||||
cleanup8()
|
||||
cleanup7()
|
||||
cleanup6()
|
||||
cleanup5()
|
||||
cleanup4()
|
||||
cleanup3()
|
||||
cleanup2()
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
sampler, cleanup19, err := newDeliveryMetrics(ctx, config2, logger, metrics)
|
||||
if err != nil {
|
||||
cleanup18()
|
||||
cleanup17()
|
||||
cleanup16()
|
||||
cleanup15()
|
||||
cleanup14()
|
||||
cleanup13()
|
||||
cleanup12()
|
||||
cleanup11()
|
||||
cleanup10()
|
||||
cleanup9()
|
||||
cleanup8()
|
||||
cleanup7()
|
||||
cleanup6()
|
||||
cleanup5()
|
||||
cleanup4()
|
||||
cleanup3()
|
||||
cleanup2()
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
application := NewApplication(config2, httpHandler, metrics, logger, mailSender, relay, bootstrapEventConsumers, worker, mailsenderWorker, sampler)
|
||||
return application, func() {
|
||||
cleanup19()
|
||||
cleanup18()
|
||||
cleanup17()
|
||||
cleanup16()
|
||||
cleanup15()
|
||||
cleanup14()
|
||||
cleanup13()
|
||||
cleanup12()
|
||||
|
||||
@@ -0,0 +1,657 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// AssessmentBasicScore is the reproducible raw result of a demo_basic run.
|
||||
type AssessmentBasicScore struct {
|
||||
Points int32 `json:"points"`
|
||||
MaxPoints int32 `json:"max_points"`
|
||||
PassPoints int32 `json:"pass_points"`
|
||||
}
|
||||
|
||||
// AssessmentAttemptDecision is the immutable completion data derived from
|
||||
// answers and the policy pinned to the attempt.
|
||||
type AssessmentAttemptDecision struct {
|
||||
Outcome AssessmentAttemptOutcome
|
||||
Score *AssessmentBasicScore
|
||||
Rationale AssessmentAttemptDecisionRationale
|
||||
}
|
||||
|
||||
type numberAssessmentAnswer struct {
|
||||
Format string `json:"format"`
|
||||
Number json.RawMessage `json:"number"`
|
||||
}
|
||||
|
||||
type orderAssessmentAnswer struct {
|
||||
Format string `json:"format"`
|
||||
ElementIDs []string `json:"element_ids"`
|
||||
}
|
||||
|
||||
// CanonicalAssessmentAnswer validates and canonicalizes a request answer
|
||||
// before its idempotency fingerprint is created.
|
||||
func CanonicalAssessmentAnswer(answer json.RawMessage) (json.RawMessage, error) {
|
||||
const location = "domain.CanonicalAssessmentAnswer"
|
||||
format, err := assessmentAnswerFormat(answer)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - answer format is invalid: %w", location, ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
switch format {
|
||||
case "number":
|
||||
canonical, err := canonicalNumberAssessmentAnswer(answer)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - number answer is invalid or exceeds its bound: %w", location, err)
|
||||
}
|
||||
return canonical, nil
|
||||
case "order":
|
||||
canonical, err := canonicalOrderAssessmentAnswer(answer)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - order answer is invalid or exceeds its bound: %w", location, err)
|
||||
}
|
||||
return canonical, nil
|
||||
default:
|
||||
return nil, fmt.Errorf("%s - answer format is not supported by the current bank: %w", location, ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
}
|
||||
|
||||
func assessmentAnswerFormat(answer json.RawMessage) (string, error) {
|
||||
if len(answer) == 0 || len(answer) > maxAssessmentAttemptAnswerBytes {
|
||||
return "", ErrInvalidAssessmentAttempt
|
||||
}
|
||||
var header struct {
|
||||
Format string `json:"format"`
|
||||
}
|
||||
if err := json.Unmarshal(answer, &header); err != nil || header.Format == "" {
|
||||
return "", ErrInvalidAssessmentAttempt
|
||||
}
|
||||
return header.Format, nil
|
||||
}
|
||||
|
||||
func canonicalNumberAssessmentAnswer(answer []byte) ([]byte, error) {
|
||||
var submitted numberAssessmentAnswer
|
||||
if err := decodeStrictAssessmentAnswer(answer, &submitted); err != nil || len(submitted.Number) == 0 {
|
||||
return nil, ErrInvalidAssessmentAttempt
|
||||
}
|
||||
number, err := canonicalAssessmentNumber(submitted.Number)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
canonical, err := json.Marshal(struct {
|
||||
Format string `json:"format"`
|
||||
Number json.RawMessage `json:"number"`
|
||||
}{Format: "number", Number: json.RawMessage(number)})
|
||||
if err != nil || len(canonical) > maxAssessmentAttemptAnswerBytes {
|
||||
return nil, ErrInvalidAssessmentAttempt
|
||||
}
|
||||
return canonical, nil
|
||||
}
|
||||
|
||||
func canonicalOrderAssessmentAnswer(answer []byte) ([]byte, error) {
|
||||
var submitted orderAssessmentAnswer
|
||||
if err := decodeStrictAssessmentAnswer(answer, &submitted); err != nil || len(submitted.ElementIDs) < 2 || len(submitted.ElementIDs) > 20 {
|
||||
return nil, ErrInvalidAssessmentAttempt
|
||||
}
|
||||
if err := validateAssessmentOrderElements(submitted.ElementIDs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
canonical, err := json.Marshal(map[string]any{"format": "order", "element_ids": submitted.ElementIDs})
|
||||
if err != nil || len(canonical) > maxAssessmentAttemptAnswerBytes {
|
||||
return nil, ErrInvalidAssessmentAttempt
|
||||
}
|
||||
return canonical, nil
|
||||
}
|
||||
|
||||
func validateAssessmentOrderElements(elementIDs []string) error {
|
||||
seen := make(map[string]struct{}, len(elementIDs))
|
||||
for _, elementID := range elementIDs {
|
||||
if !assessmentPublicTaskElementIDPattern.MatchString(elementID) {
|
||||
return ErrInvalidAssessmentAttempt
|
||||
}
|
||||
if _, exists := seen[elementID]; exists {
|
||||
return ErrInvalidAssessmentAttempt
|
||||
}
|
||||
seen[elementID] = struct{}{}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CanonicalAssessmentAnswerForVariant accepts only the answer formats
|
||||
// currently produced by the reviewed assessment bank. The returned JSON is
|
||||
// stable for idempotency and preserves exact sequence semantics for orders.
|
||||
func CanonicalAssessmentAnswerForVariant(answer json.RawMessage, variant AssessmentVariant) (json.RawMessage, bool, error) {
|
||||
const location = "domain.CanonicalAssessmentAnswerForVariant"
|
||||
canonical, err := CanonicalAssessmentAnswer(answer)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("%s - canonicalize answer: %w", location, err)
|
||||
}
|
||||
switch variant.AnswerFormat {
|
||||
case AnswerFormatInteger:
|
||||
correct, err := assessmentIntegerAnswerIsCorrect(canonical, variant.ReferenceAnswer)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("%s - compare frozen integer key: %w", location, err)
|
||||
}
|
||||
return canonical, correct, nil
|
||||
case AnswerFormatIntegerSequence:
|
||||
correct, err := assessmentOrderAnswerIsCorrect(canonical, variant)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("%s - compare frozen order key: %w", location, err)
|
||||
}
|
||||
return canonical, correct, nil
|
||||
default:
|
||||
return nil, false, fmt.Errorf("%s - frozen answer format is unsupported: %w", location, ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
}
|
||||
|
||||
func assessmentIntegerAnswerIsCorrect(canonical []byte, referenceAnswer string) (bool, error) {
|
||||
var submitted numberAssessmentAnswer
|
||||
if err := decodeStrictAssessmentAnswer(canonical, &submitted); err != nil || submitted.Format != "number" || len(submitted.Number) == 0 {
|
||||
return false, ErrInvalidAssessmentAttempt
|
||||
}
|
||||
reference, err := strconv.ParseInt(referenceAnswer, 10, 64)
|
||||
if err != nil {
|
||||
return false, ErrInvalidAssessmentAttempt
|
||||
}
|
||||
return string(submitted.Number) == strconv.FormatInt(reference, 10), nil
|
||||
}
|
||||
|
||||
func assessmentOrderAnswerIsCorrect(canonical []byte, variant AssessmentVariant) (bool, error) {
|
||||
var submitted orderAssessmentAnswer
|
||||
if err := decodeStrictAssessmentAnswer(canonical, &submitted); err != nil || submitted.Format != "order" {
|
||||
return false, ErrInvalidAssessmentAttempt
|
||||
}
|
||||
taskCount, ok := variant.Parameters["tasks"]
|
||||
if !ok || taskCount < 2 || taskCount > 20 || len(submitted.ElementIDs) != int(taskCount) {
|
||||
return false, ErrInvalidAssessmentAttempt
|
||||
}
|
||||
if err := validateAssessmentOrderElements(submitted.ElementIDs); err != nil || !assessmentOrderHasEveryTask(submitted.ElementIDs, taskCount) {
|
||||
return false, ErrInvalidAssessmentAttempt
|
||||
}
|
||||
return assessmentOrderMatchesReference(submitted.ElementIDs, variant.ReferenceAnswer, taskCount)
|
||||
}
|
||||
|
||||
func assessmentOrderHasEveryTask(elementIDs []string, taskCount int32) bool {
|
||||
seen := make(map[string]struct{}, len(elementIDs))
|
||||
for _, elementID := range elementIDs {
|
||||
seen[elementID] = struct{}{}
|
||||
}
|
||||
for ordinal := int32(1); ordinal <= taskCount; ordinal++ {
|
||||
if _, exists := seen["job_"+strconv.FormatInt(int64(ordinal), 10)]; !exists {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func assessmentOrderMatchesReference(elementIDs []string, referenceAnswer string, taskCount int32) (bool, error) {
|
||||
reference := strings.Fields(referenceAnswer)
|
||||
if len(reference) != int(taskCount) {
|
||||
return false, ErrInvalidAssessmentAttempt
|
||||
}
|
||||
for index, token := range reference {
|
||||
ordinal, err := strconv.ParseInt(token, 10, 32)
|
||||
if err != nil || ordinal < 1 || ordinal > int64(taskCount) {
|
||||
return false, ErrInvalidAssessmentAttempt
|
||||
}
|
||||
if elementIDs[index] != "job_"+strconv.FormatInt(ordinal, 10) {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func decodeStrictAssessmentAnswer(encoded []byte, target any) error {
|
||||
if len(encoded) == 0 || len(encoded) > maxAssessmentAttemptAnswerBytes || !json.Valid(encoded) {
|
||||
return ErrInvalidAssessmentAttempt
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewReader(encoded))
|
||||
decoder.UseNumber()
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(target); err != nil {
|
||||
return errors.Join(ErrInvalidAssessmentAttempt, err)
|
||||
}
|
||||
var extra any
|
||||
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
|
||||
return ErrInvalidAssessmentAttempt
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func canonicalAssessmentNumber(encoded json.RawMessage) (string, error) {
|
||||
if len(encoded) == 0 || len(encoded) > maxAssessmentAttemptAnswerBytes || !json.Valid(encoded) {
|
||||
return "", ErrInvalidAssessmentAttempt
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewReader(encoded))
|
||||
decoder.UseNumber()
|
||||
var value any
|
||||
if err := decoder.Decode(&value); err != nil {
|
||||
return "", ErrInvalidAssessmentAttempt
|
||||
}
|
||||
number, ok := value.(json.Number)
|
||||
if !ok {
|
||||
return "", ErrInvalidAssessmentAttempt
|
||||
}
|
||||
digits, scale, negative, err := assessmentDecimalParts(number.String())
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return formatAssessmentDecimal(digits, scale, negative)
|
||||
}
|
||||
|
||||
func assessmentDecimalParts(text string) (string, int64, bool, error) {
|
||||
negative := strings.HasPrefix(text, "-")
|
||||
if negative {
|
||||
text = text[1:]
|
||||
}
|
||||
mantissa, exponent, err := assessmentDecimalMantissaAndExponent(text)
|
||||
if err != nil {
|
||||
return "", 0, false, err
|
||||
}
|
||||
integerDigits := mantissa
|
||||
fractionDigits := ""
|
||||
if point := strings.IndexByte(mantissa, '.'); point >= 0 {
|
||||
integerDigits = mantissa[:point]
|
||||
fractionDigits = mantissa[point+1:]
|
||||
}
|
||||
digits := integerDigits + fractionDigits
|
||||
scale := int64(len(fractionDigits)) - exponent
|
||||
if scale > maxAssessmentAttemptAnswerBytes || scale < -maxAssessmentAttemptAnswerBytes {
|
||||
return "", 0, false, ErrInvalidAssessmentAttempt
|
||||
}
|
||||
digits = strings.TrimLeft(digits, "0")
|
||||
for len(digits) > 0 && scale > 0 && digits[len(digits)-1] == '0' {
|
||||
digits = digits[:len(digits)-1]
|
||||
scale--
|
||||
}
|
||||
return digits, scale, negative, nil
|
||||
}
|
||||
|
||||
func assessmentDecimalMantissaAndExponent(text string) (string, int64, error) {
|
||||
decimalAt := strings.IndexAny(text, ".eE")
|
||||
mantissa := text
|
||||
exponent := int64(0)
|
||||
if decimalAt >= 0 {
|
||||
if text[decimalAt] == '.' {
|
||||
exponentAt := strings.IndexAny(text[decimalAt+1:], "eE")
|
||||
if exponentAt >= 0 {
|
||||
exponentAt += decimalAt + 1
|
||||
parsed, err := parseAssessmentExponent(text[exponentAt+1:])
|
||||
if err != nil {
|
||||
return "", 0, err
|
||||
}
|
||||
exponent = parsed
|
||||
mantissa = text[:exponentAt]
|
||||
}
|
||||
} else {
|
||||
mantissa = text[:decimalAt]
|
||||
parsed, err := parseAssessmentExponent(text[decimalAt+1:])
|
||||
if err != nil {
|
||||
return "", 0, err
|
||||
}
|
||||
exponent = parsed
|
||||
}
|
||||
}
|
||||
return mantissa, exponent, nil
|
||||
}
|
||||
|
||||
func parseAssessmentExponent(value string) (int64, error) {
|
||||
exponent, err := strconv.ParseInt(value, 10, 64)
|
||||
if err != nil || exponent > maxAssessmentAttemptAnswerBytes || exponent < -maxAssessmentAttemptAnswerBytes {
|
||||
return 0, ErrInvalidAssessmentAttempt
|
||||
}
|
||||
return exponent, nil
|
||||
}
|
||||
|
||||
func formatAssessmentDecimal(digits string, scale int64, negative bool) (string, error) {
|
||||
if digits == "" {
|
||||
return "0", nil
|
||||
}
|
||||
outputLength := len(digits)
|
||||
switch {
|
||||
case scale <= 0:
|
||||
outputLength += int(-scale)
|
||||
case int64(len(digits)) <= scale:
|
||||
outputLength += int(scale-int64(len(digits))) + 2
|
||||
default:
|
||||
outputLength++
|
||||
}
|
||||
if negative {
|
||||
outputLength++
|
||||
}
|
||||
if outputLength > maxAssessmentAttemptAnswerBytes {
|
||||
return "", ErrInvalidAssessmentAttempt
|
||||
}
|
||||
var canonical string
|
||||
switch {
|
||||
case scale <= 0:
|
||||
canonical = digits + strings.Repeat("0", int(-scale))
|
||||
case int64(len(digits)) <= scale:
|
||||
canonical = "0." + strings.Repeat("0", int(scale-int64(len(digits)))) + digits
|
||||
default:
|
||||
point := len(digits) - int(scale)
|
||||
canonical = digits[:point] + "." + digits[point:]
|
||||
}
|
||||
if negative {
|
||||
canonical = "-" + canonical
|
||||
}
|
||||
return canonical, nil
|
||||
}
|
||||
|
||||
// SubmitAnswer stores one final answer to the current frozen item. Identical
|
||||
// repeats are no-ops even when their expected version is stale.
|
||||
func (attempt AssessmentAttempt) SubmitAnswer(
|
||||
expectedVersion int64,
|
||||
itemID uuid.UUID,
|
||||
answer json.RawMessage,
|
||||
at time.Time,
|
||||
) (AssessmentAttempt, bool, error) {
|
||||
const location = "AssessmentAttempt.SubmitAnswer"
|
||||
if attempt.IsZero() || itemID == uuid.Nil || at.IsZero() {
|
||||
return AssessmentAttempt{}, false, fmt.Errorf("%s - attempt, item, and time are required: %w", location, ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
index := attempt.itemIndex(itemID)
|
||||
if index < 0 {
|
||||
return AssessmentAttempt{}, false, fmt.Errorf("%s - item is not part of this attempt: %w", location, ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
return attempt.submitAnswerToItem(expectedVersion, index, answer, canonicalAssessmentTime(at))
|
||||
}
|
||||
|
||||
func (attempt AssessmentAttempt) submitAnswerToItem(
|
||||
expectedVersion int64,
|
||||
index int,
|
||||
answer json.RawMessage,
|
||||
answeredAt time.Time,
|
||||
) (AssessmentAttempt, bool, error) {
|
||||
const location = "AssessmentAttempt.submitAnswerToItem"
|
||||
item := attempt.snapshot.Items[index]
|
||||
canonical, _, err := CanonicalAssessmentAnswerForVariant(answer, item.Variant)
|
||||
if err != nil {
|
||||
return AssessmentAttempt{}, false, fmt.Errorf("%s - validate answer: %w", location, err)
|
||||
}
|
||||
replayed, err := assessmentAnswerReplay(item, canonical, expectedVersion, attempt.snapshot.Version)
|
||||
if err != nil {
|
||||
return AssessmentAttempt{}, false, fmt.Errorf("%s - check existing answer: %w", location, err)
|
||||
}
|
||||
if replayed {
|
||||
return attempt, false, nil
|
||||
}
|
||||
if err := validateNewAssessmentAnswer(attempt.snapshot, index, expectedVersion, answeredAt); err != nil {
|
||||
return AssessmentAttempt{}, false, fmt.Errorf("%s - validate lifecycle: %w", location, err)
|
||||
}
|
||||
return storeAssessmentAttemptAnswer(attempt, index, canonical, answeredAt)
|
||||
}
|
||||
|
||||
func assessmentAnswerReplay(
|
||||
item AssessmentAttemptItemSnapshot,
|
||||
canonical []byte,
|
||||
expectedVersion, currentVersion int64,
|
||||
) (bool, error) {
|
||||
if len(item.Answer) == 0 {
|
||||
return false, nil
|
||||
}
|
||||
if bytes.Equal(item.Answer, canonical) {
|
||||
return true, nil
|
||||
}
|
||||
if expectedVersion != currentVersion {
|
||||
return false, ErrAssessmentAttemptVersionConflict
|
||||
}
|
||||
return false, ErrAssessmentAttemptNotActive
|
||||
}
|
||||
|
||||
func validateNewAssessmentAnswer(
|
||||
snapshot AssessmentAttemptSnapshot,
|
||||
index int,
|
||||
expectedVersion int64,
|
||||
answeredAt time.Time,
|
||||
) error {
|
||||
if expectedVersion != snapshot.Version {
|
||||
return ErrAssessmentAttemptVersionConflict
|
||||
}
|
||||
if snapshot.State != AssessmentAttemptStateInProgress ||
|
||||
!answeredAt.Before(snapshot.ExpiresAt) || !snapshot.ChainDeadline.IsZero() && !answeredAt.Before(snapshot.ChainDeadline) {
|
||||
return ErrAssessmentAttemptNotActive
|
||||
}
|
||||
idleAt := snapshot.LastActivityAt.Add(time.Duration(snapshot.IdleTimeoutSeconds) * time.Second)
|
||||
if !answeredAt.Before(idleAt) {
|
||||
return ErrAssessmentAttemptNotActive
|
||||
}
|
||||
if answeredAt.Before(snapshot.LastActivityAt) {
|
||||
return ErrInvalidAssessmentAttempt
|
||||
}
|
||||
if index != firstUnansweredAssessmentItemIndex(snapshot.Items) {
|
||||
return ErrAssessmentAttemptNotActive
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func storeAssessmentAttemptAnswer(
|
||||
attempt AssessmentAttempt,
|
||||
index int,
|
||||
canonical []byte,
|
||||
answeredAt time.Time,
|
||||
) (AssessmentAttempt, bool, error) {
|
||||
next := attempt.Snapshot()
|
||||
next.Items[index].Answer = canonical
|
||||
next.Items[index].AnsweredAt = answeredAt
|
||||
next.LastActivityAt = answeredAt
|
||||
next.UpdatedAt = answeredAt
|
||||
next.Version++
|
||||
if allAssessmentAttemptItemsAnswered(next.Items) {
|
||||
next.State = AssessmentAttemptStateReadyToFinalize
|
||||
}
|
||||
updated, err := RestoreAssessmentAttempt(next)
|
||||
return updated, true, err
|
||||
}
|
||||
|
||||
func (attempt AssessmentAttempt) itemIndex(itemID uuid.UUID) int {
|
||||
for index, item := range attempt.snapshot.Items {
|
||||
if item.ID == itemID {
|
||||
return index
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func firstUnansweredAssessmentItemIndex(items []AssessmentAttemptItemSnapshot) int {
|
||||
for index, item := range items {
|
||||
if len(item.Answer) == 0 {
|
||||
return index
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func allAssessmentAttemptItemsAnswered(items []AssessmentAttemptItemSnapshot) bool {
|
||||
if len(items) == 0 {
|
||||
return false
|
||||
}
|
||||
for _, item := range items {
|
||||
if len(item.Answer) == 0 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// ExpireIfDue records the terminal deadline transition for an incomplete
|
||||
// in-progress attempt. It does not advance time for read operations.
|
||||
func (attempt AssessmentAttempt) ExpireIfDue(at time.Time) (AssessmentAttempt, bool, error) {
|
||||
const location = "AssessmentAttempt.ExpireIfDue"
|
||||
if attempt.IsZero() || at.IsZero() {
|
||||
return AssessmentAttempt{}, false, fmt.Errorf("%s - attempt and time are required: %w", location, ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
if attempt.snapshot.State != AssessmentAttemptStateInProgress {
|
||||
return attempt, false, nil
|
||||
}
|
||||
expiredAt := canonicalAssessmentTime(at)
|
||||
if expiredAt.Before(attempt.snapshot.LastActivityAt) {
|
||||
return AssessmentAttempt{}, false, fmt.Errorf("%s - expiry time predates activity: %w", location, ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
if expiredAt.Before(attempt.snapshot.ExpiresAt) &&
|
||||
(attempt.snapshot.ChainDeadline.IsZero() || expiredAt.Before(attempt.snapshot.ChainDeadline)) {
|
||||
return attempt, false, nil
|
||||
}
|
||||
next := attempt.Snapshot()
|
||||
next.State = AssessmentAttemptStateExpired
|
||||
next.UpdatedAt = expiredAt
|
||||
next.EndedAt = expiredAt
|
||||
next.Version++
|
||||
updated, err := RestoreAssessmentAttempt(next)
|
||||
return updated, true, err
|
||||
}
|
||||
|
||||
// FinalizeDemo applies only the explicit demo_basic pass mark or returns a
|
||||
// separate demonstration outcome for demo_express. Adaptive scoring is not
|
||||
// inferred from a basic score.
|
||||
func (attempt AssessmentAttempt) FinalizeDemo(
|
||||
expectedVersion int64,
|
||||
policy AssessmentPolicy,
|
||||
at time.Time,
|
||||
) (AssessmentAttempt, bool, AssessmentAttemptDecision, error) {
|
||||
const location = "AssessmentAttempt.FinalizeDemo"
|
||||
if attempt.IsZero() || at.IsZero() {
|
||||
return AssessmentAttempt{}, false, AssessmentAttemptDecision{}, fmt.Errorf("%s - attempt and time are required: %w", location, ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
if attempt.snapshot.State == AssessmentAttemptStateCompleted {
|
||||
decision, err := decisionForCompletedAttempt(attempt, policy)
|
||||
return attempt, false, decision, err
|
||||
}
|
||||
if expectedVersion != attempt.snapshot.Version {
|
||||
return AssessmentAttempt{}, false, AssessmentAttemptDecision{}, fmt.Errorf("%s - expected version is stale: %w", location, ErrAssessmentAttemptVersionConflict)
|
||||
}
|
||||
if attempt.snapshot.State != AssessmentAttemptStateReadyToFinalize || !allAssessmentAttemptItemsAnswered(attempt.snapshot.Items) {
|
||||
return AssessmentAttempt{}, false, AssessmentAttemptDecision{}, fmt.Errorf("%s - required assessment answers are incomplete: %w", location, ErrAssessmentAttemptNotActive)
|
||||
}
|
||||
finalizedAt := canonicalAssessmentTime(at)
|
||||
if finalizedAt.Before(attempt.snapshot.LastActivityAt) {
|
||||
return AssessmentAttempt{}, false, AssessmentAttemptDecision{}, fmt.Errorf("%s - decision time predates answer activity: %w", location, ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
idleAt := attempt.snapshot.LastActivityAt.Add(time.Duration(attempt.snapshot.IdleTimeoutSeconds) * time.Second)
|
||||
deadlineDue := !finalizedAt.Before(attempt.snapshot.ExpiresAt) ||
|
||||
!attempt.snapshot.ChainDeadline.IsZero() && !finalizedAt.Before(attempt.snapshot.ChainDeadline)
|
||||
if !finalizedAt.Before(idleAt) && !deadlineDue {
|
||||
return AssessmentAttempt{}, false, AssessmentAttemptDecision{}, fmt.Errorf("%s - work session is idle: %w", location, ErrAssessmentAttemptNotActive)
|
||||
}
|
||||
decision, err := assessmentAttemptDecision(attempt.snapshot, policy)
|
||||
if err != nil {
|
||||
return AssessmentAttempt{}, false, AssessmentAttemptDecision{}, fmt.Errorf("%s - calculate pinned demo decision: %w", location, err)
|
||||
}
|
||||
next := attempt.Snapshot()
|
||||
next.State = AssessmentAttemptStateCompleted
|
||||
next.Outcome = decision.Outcome
|
||||
next.EndedAt = finalizedAt
|
||||
next.UpdatedAt = finalizedAt
|
||||
next.Version++
|
||||
updated, err := RestoreAssessmentAttempt(next)
|
||||
return updated, true, decision, err
|
||||
}
|
||||
|
||||
func decisionForCompletedAttempt(attempt AssessmentAttempt, policy AssessmentPolicy) (AssessmentAttemptDecision, error) {
|
||||
return assessmentAttemptDecision(attempt.snapshot, policy)
|
||||
}
|
||||
|
||||
func assessmentAttemptDecision(snapshot AssessmentAttemptSnapshot, policy AssessmentPolicy) (AssessmentAttemptDecision, error) {
|
||||
if snapshot.Kind == AssessmentAttemptKindDemoExpress {
|
||||
return assessmentTrainingDecision(snapshot, policy)
|
||||
}
|
||||
if snapshot.Kind != AssessmentAttemptKindRoot && snapshot.Kind != AssessmentAttemptKindCorrective {
|
||||
return AssessmentAttemptDecision{}, ErrAssessmentAttemptNotActive
|
||||
}
|
||||
return assessmentBasicDecision(snapshot, policy)
|
||||
}
|
||||
|
||||
func assessmentTrainingDecision(snapshot AssessmentAttemptSnapshot, policy AssessmentPolicy) (AssessmentAttemptDecision, error) {
|
||||
if policy.Training == nil || !allAssessmentAttemptItemsAnswered(snapshot.Items) ||
|
||||
snapshot.State == AssessmentAttemptStateCompleted && snapshot.Outcome != AssessmentAttemptOutcomeDemonstration ||
|
||||
snapshot.State != AssessmentAttemptStateCompleted && snapshot.State != AssessmentAttemptStateReadyToFinalize {
|
||||
return AssessmentAttemptDecision{}, ErrInvalidAssessmentAttempt
|
||||
}
|
||||
return AssessmentAttemptDecision{
|
||||
Outcome: AssessmentAttemptOutcomeDemonstration,
|
||||
Rationale: AssessmentAttemptDecisionRationale{Rule: assessmentResultRuleTrainingOnly},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func assessmentBasicDecision(snapshot AssessmentAttemptSnapshot, policy AssessmentPolicy) (AssessmentAttemptDecision, error) {
|
||||
maxScored, passMark, err := assessmentBasicDecisionInputs(snapshot, policy)
|
||||
if err != nil {
|
||||
return AssessmentAttemptDecision{}, err
|
||||
}
|
||||
points, err := scoreAssessmentAttemptItems(snapshot.Items, maxScored)
|
||||
if err != nil {
|
||||
return AssessmentAttemptDecision{}, err
|
||||
}
|
||||
passPoints64 := (int64(maxScored)*int64(passMark) + int64(basisPointsPerUnit) - 1) / int64(basisPointsPerUnit)
|
||||
if passPoints64 < 1 || passPoints64 > int64(maxScored) || passPoints64 > math.MaxInt32 {
|
||||
return AssessmentAttemptDecision{}, ErrInvalidAssessmentAttempt
|
||||
}
|
||||
passPoints := int32(passPoints64)
|
||||
outcome, err := assessmentBasicOutcome(snapshot, points, passPoints)
|
||||
if err != nil {
|
||||
return AssessmentAttemptDecision{}, err
|
||||
}
|
||||
return AssessmentAttemptDecision{
|
||||
Outcome: outcome,
|
||||
Score: &AssessmentBasicScore{Points: points, MaxPoints: maxScored, PassPoints: passPoints},
|
||||
Rationale: AssessmentAttemptDecisionRationale{
|
||||
Rule: assessmentResultRuleBasicPassMark, PassMarkBasisPoints: int32(passMark),
|
||||
PassPoints: passPoints, ScoredItems: maxScored,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func assessmentBasicDecisionInputs(snapshot AssessmentAttemptSnapshot, policy AssessmentPolicy) (int32, BasisPoints, error) {
|
||||
if snapshot.Mode != AssessmentAttemptModeDemoBasic || policy.Attempt == nil || !allAssessmentAttemptItemsAnswered(snapshot.Items) {
|
||||
return 0, 0, ErrAssessmentAttemptNotActive
|
||||
}
|
||||
maxScored := policy.StopRule.MaxScoredItems
|
||||
seedCount := policy.StopRule.SeedItems
|
||||
if maxScored < 1 || seedCount < 0 || int64(maxScored)+int64(seedCount) != int64(len(snapshot.Items)) {
|
||||
return 0, 0, ErrInvalidAssessmentAttempt
|
||||
}
|
||||
passMark := policy.Attempt.BasicPassMark
|
||||
if passMark < 1 || passMark > basisPointsPerUnit {
|
||||
return 0, 0, ErrInvalidAssessmentAttempt
|
||||
}
|
||||
return maxScored, passMark, nil
|
||||
}
|
||||
|
||||
func assessmentBasicOutcome(
|
||||
snapshot AssessmentAttemptSnapshot,
|
||||
points int32,
|
||||
passPoints int32,
|
||||
) (AssessmentAttemptOutcome, error) {
|
||||
outcome := AssessmentAttemptOutcomeNotConfirmed
|
||||
if points >= passPoints {
|
||||
outcome = AssessmentAttemptOutcomeConfirmed
|
||||
}
|
||||
if snapshot.State == AssessmentAttemptStateCompleted && snapshot.Outcome != outcome {
|
||||
return "", ErrInvalidAssessmentAttempt
|
||||
}
|
||||
return outcome, nil
|
||||
}
|
||||
|
||||
func scoreAssessmentAttemptItems(items []AssessmentAttemptItemSnapshot, scoredItems int32) (int32, error) {
|
||||
var points int32
|
||||
for index := int32(0); index < scoredItems; index++ {
|
||||
item := items[index]
|
||||
_, correct, err := CanonicalAssessmentAnswerForVariant(item.Answer, item.Variant)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if correct {
|
||||
points++
|
||||
}
|
||||
}
|
||||
return points, nil
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestAssessmentAnswerCanonicalizesNumericEqualityAndScoresOnlyPinnedItems(t *testing.T) {
|
||||
policy := testAssessmentAttemptPolicyVersion(t)
|
||||
assessmentPolicy := policy.Policy().Assessment
|
||||
assessmentPolicy.StopRule.MaxScoredItems = 1
|
||||
assessmentPolicy.StopRule.SeedItems = 1
|
||||
attempt := testAttemptWithPolicy(t, policy, AssessmentAttemptKindRoot, 2)
|
||||
created := attempt.Snapshot().CreatedAt
|
||||
items := attempt.Snapshot().Items
|
||||
|
||||
wrong := fmt.Sprintf(`{"format":"number","number":%s}`, items[0].Variant.ReferenceAnswer+"1")
|
||||
updated, changed, err := attempt.SubmitAnswer(attempt.Version(), items[0].ID, json.RawMessage(wrong), created.Add(time.Second))
|
||||
if err != nil || !changed || updated.State() != AssessmentAttemptStateInProgress || updated.Version() != 2 {
|
||||
t.Fatalf("SubmitAnswer(first) = (%v, %v, %v), want one in-progress transition", updated, changed, err)
|
||||
}
|
||||
|
||||
reference := items[0].Variant.ReferenceAnswer
|
||||
canonicalA, correct, err := CanonicalAssessmentAnswerForVariant(json.RawMessage(fmt.Sprintf(`{"format":"number","number":%s}`, reference)), items[0].Variant)
|
||||
if err != nil || !correct {
|
||||
t.Fatalf("CanonicalAssessmentAnswerForVariant(reference) = (%s, %v, %v), want correct", canonicalA, correct, err)
|
||||
}
|
||||
canonicalB, _, err := CanonicalAssessmentAnswerForVariant(json.RawMessage(fmt.Sprintf(`{"format":"number","number":%s.0}`, reference)), items[0].Variant)
|
||||
if err != nil || string(canonicalA) != string(canonicalB) {
|
||||
t.Fatalf("numeric equivalents canonicalized to %s and %s, error %v", canonicalA, canonicalB, err)
|
||||
}
|
||||
|
||||
seed := items[1]
|
||||
seedAnswer := json.RawMessage(fmt.Sprintf(`{"format":"number","number":%s}`, seed.Variant.ReferenceAnswer))
|
||||
ready, changed, err := updated.SubmitAnswer(updated.Version(), seed.ID, seedAnswer, created.Add(2*time.Second))
|
||||
if err != nil || !changed || ready.State() != AssessmentAttemptStateReadyToFinalize || ready.Version() != 3 {
|
||||
t.Fatalf("SubmitAnswer(seed) = (%v, %v, %v), want ready_to_finalize", ready, changed, err)
|
||||
}
|
||||
|
||||
final, changed, decision, err := ready.FinalizeDemo(ready.Version(), assessmentPolicy, created.Add(3*time.Second))
|
||||
if err != nil || !changed || final.State() != AssessmentAttemptStateCompleted || decision.Score == nil ||
|
||||
decision.Score.Points != 0 || decision.Score.MaxPoints != 1 || decision.Score.PassPoints != 1 ||
|
||||
decision.Outcome != AssessmentAttemptOutcomeNotConfirmed {
|
||||
t.Fatalf("FinalizeDemo() = (%v, %v, %+v, %v), want wrong scored item and ignored correct seed", final, changed, decision, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAssessmentNumberEqualityPreservesExactDecimalPrecision(t *testing.T) {
|
||||
canonicalOne, err := CanonicalAssessmentAnswer(json.RawMessage(`{"format":"number","number":1}`))
|
||||
if err != nil {
|
||||
t.Fatalf("CanonicalAssessmentAnswer(1) error = %v", err)
|
||||
}
|
||||
canonicalDecimal, err := CanonicalAssessmentAnswer(json.RawMessage(`{"format":"number","number":1.0}`))
|
||||
if err != nil || string(canonicalOne) != string(canonicalDecimal) {
|
||||
t.Fatalf("canonical 1 and 1.0 = %s and %s, error %v", canonicalOne, canonicalDecimal, err)
|
||||
}
|
||||
canonicalPrecise, err := CanonicalAssessmentAnswer(json.RawMessage(`{"format":"number","number":1.0000000000000001}`))
|
||||
if err != nil || string(canonicalPrecise) == string(canonicalOne) {
|
||||
t.Fatalf("canonical precise decimal = %s, error %v; want a value distinct from %s", canonicalPrecise, err, canonicalOne)
|
||||
}
|
||||
if _, err := CanonicalAssessmentAnswer(json.RawMessage(`{"format":"number","number":1e999999999}`)); !errors.Is(err, ErrInvalidAssessmentAttempt) {
|
||||
t.Fatalf("CanonicalAssessmentAnswer(oversized exponent) error = %v, want bounded invalid answer", err)
|
||||
}
|
||||
for _, input := range []string{
|
||||
`{"format":"number","number":null}`,
|
||||
`{"format":"number","number":"1"}`,
|
||||
`{"format":"number","number":true}`,
|
||||
} {
|
||||
if _, err := CanonicalAssessmentAnswer(json.RawMessage(input)); !errors.Is(err, ErrInvalidAssessmentAttempt) {
|
||||
t.Errorf("CanonicalAssessmentAnswer(%s) error = %v, want invalid attempt", input, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAssessmentAttemptResultSnapshotRetainsRationaleAndRejectsCorruption(t *testing.T) {
|
||||
policy := testAssessmentAttemptPolicyVersion(t)
|
||||
assessmentPolicy := policy.Policy().Assessment
|
||||
assessmentPolicy.StopRule.MaxScoredItems = 2
|
||||
assessmentPolicy.StopRule.SeedItems = 0
|
||||
attempt := testAttemptWithPolicy(t, policy, AssessmentAttemptKindRoot, 2)
|
||||
createdAt := attempt.Snapshot().CreatedAt
|
||||
for index, item := range attempt.Snapshot().Items {
|
||||
answer := correctAssessmentTestAnswer(t, item.Variant)
|
||||
updated, changed, err := attempt.SubmitAnswer(attempt.Version(), item.ID, answer, createdAt.Add(time.Duration(index+1)*time.Second))
|
||||
if err != nil || !changed {
|
||||
t.Fatalf("SubmitAnswer(item %d) = changed %v, error %v", index, changed, err)
|
||||
}
|
||||
attempt = updated
|
||||
}
|
||||
finalized, changed, decision, err := attempt.FinalizeDemo(
|
||||
attempt.Version(), assessmentPolicy, createdAt.Add(3*time.Second),
|
||||
)
|
||||
if err != nil || !changed {
|
||||
t.Fatalf("FinalizeDemo() = changed %v, error %v", changed, err)
|
||||
}
|
||||
result, err := NewAssessmentAttemptResultSnapshot(
|
||||
finalized, decision, "", []string{"uncalibrated_thresholds", "demo_bank"},
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("NewAssessmentAttemptResultSnapshot() error = %v", err)
|
||||
}
|
||||
if err := ValidateAssessmentAttemptResultSnapshot(result); err != nil {
|
||||
t.Fatalf("ValidateAssessmentAttemptResultSnapshot() error = %v", err)
|
||||
}
|
||||
if result.BasicScore == nil || result.BasicScore.Points != 2 || result.BasicScore.MaxPoints != 2 ||
|
||||
result.BasicScore.PassPoints != 2 || result.Rationale.PassMarkBasisPoints != 8000 ||
|
||||
result.Rationale.ScoredItems != 2 || result.Rationale.PassPoints != 2 ||
|
||||
result.Pins.ProductPolicyVersionID != policy.ID() || result.DecidedAt != createdAt.Add(3*time.Second) {
|
||||
t.Fatalf("persisted decision snapshot = %+v, want raw score, rationale and pins", result)
|
||||
}
|
||||
|
||||
corruptions := []func(*AssessmentAttemptResultSnapshot){
|
||||
func(snapshot *AssessmentAttemptResultSnapshot) { snapshot.Rationale.PassPoints-- },
|
||||
func(snapshot *AssessmentAttemptResultSnapshot) { snapshot.Rationale.ScoredItems++ },
|
||||
func(snapshot *AssessmentAttemptResultSnapshot) { snapshot.BasicScore.Points-- },
|
||||
func(snapshot *AssessmentAttemptResultSnapshot) { snapshot.Pins.BankVersion = "other.bank" },
|
||||
}
|
||||
for index, corrupt := range corruptions {
|
||||
bad := result
|
||||
bad.Limitations = append([]string{}, result.Limitations...)
|
||||
bad.BasicScore = clonePointer(result.BasicScore)
|
||||
corrupt(&bad)
|
||||
if err := ValidateAssessmentAttemptResultSnapshot(bad); !errors.Is(err, ErrInvalidAssessmentAttempt) {
|
||||
t.Errorf("corrupted result %d error = %v, want invalid result", index, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAssessmentBasicScoreDoesNotDependOnAnswerElapsedTime(t *testing.T) {
|
||||
policy := testAssessmentAttemptPolicyVersion(t)
|
||||
assessmentPolicy := policy.Policy().Assessment
|
||||
assessmentPolicy.StopRule.MaxScoredItems = 2
|
||||
assessmentPolicy.StopRule.SeedItems = 0
|
||||
items := testAssessmentAttemptItems(t, 2)
|
||||
versions := testAssessmentAttemptVersions(t, policy)
|
||||
specialization, grade := SpecializationBackend, GradeJunior
|
||||
durations := [][]time.Duration{
|
||||
{time.Second, 2 * time.Second},
|
||||
{15 * time.Minute, 30 * time.Minute},
|
||||
}
|
||||
decisions := make([]AssessmentAttemptDecision, 0, len(durations))
|
||||
for runIndex, answerTimes := range durations {
|
||||
attempt, err := NewAssessmentAttempt(NewAssessmentAttemptInput{
|
||||
UserID: uuid.New(), Kind: AssessmentAttemptKindRoot, BankCategory: "unit-category",
|
||||
Specialization: &specialization, TargetGrade: &grade, Versions: versions,
|
||||
Policy: policy, CreatedAt: testAssessmentAttemptCreatedAt, Items: items,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewAssessmentAttempt(run %d) error = %v", runIndex, err)
|
||||
}
|
||||
for index, item := range attempt.Snapshot().Items {
|
||||
answer := correctAssessmentTestAnswer(t, item.Variant)
|
||||
if index == 0 {
|
||||
answer = incorrectAssessmentTestAnswer(t, item.Variant)
|
||||
}
|
||||
updated, changed, err := attempt.SubmitAnswer(
|
||||
attempt.Version(), item.ID, answer, testAssessmentAttemptCreatedAt.Add(answerTimes[index]),
|
||||
)
|
||||
if err != nil || !changed {
|
||||
t.Fatalf("SubmitAnswer(run %d item %d) = changed %v, error %v", runIndex, index, changed, err)
|
||||
}
|
||||
attempt = updated
|
||||
}
|
||||
finalized, changed, decision, err := attempt.FinalizeDemo(
|
||||
attempt.Version(), assessmentPolicy, testAssessmentAttemptCreatedAt.Add(answerTimes[len(answerTimes)-1]+time.Second),
|
||||
)
|
||||
if err != nil || !changed || finalized.State() != AssessmentAttemptStateCompleted {
|
||||
t.Fatalf("FinalizeDemo(run %d) = changed %v state %s error %v", runIndex, changed, finalized.State(), err)
|
||||
}
|
||||
decisions = append(decisions, decision)
|
||||
}
|
||||
fast, slow := decisions[0], decisions[1]
|
||||
if fast.Outcome != slow.Outcome || fast.Score == nil || slow.Score == nil || *fast.Score != *slow.Score || fast.Rationale != slow.Rationale {
|
||||
t.Fatalf("same answers at different elapsed times scored differently: fast=%+v slow=%+v", fast, slow)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExpressResultSnapshotHasNoScoringOrGrade(t *testing.T) {
|
||||
policy := testTrainingOnlyAssessmentPolicyVersion(t)
|
||||
attempt := testAttemptWithPolicy(t, policy, AssessmentAttemptKindDemoExpress, 1)
|
||||
createdAt := attempt.Snapshot().CreatedAt
|
||||
for index, item := range attempt.Snapshot().Items {
|
||||
updated, changed, err := attempt.SubmitAnswer(
|
||||
attempt.Version(), item.ID, correctAssessmentTestAnswer(t, item.Variant),
|
||||
createdAt.Add(time.Duration(index+1)*time.Second),
|
||||
)
|
||||
if err != nil || !changed {
|
||||
t.Fatalf("SubmitAnswer(express item %d) = changed %v, error %v", index, changed, err)
|
||||
}
|
||||
attempt = updated
|
||||
}
|
||||
finalized, changed, decision, err := attempt.FinalizeDemo(
|
||||
attempt.Version(), policy.Policy().Assessment, createdAt.Add(4*time.Second),
|
||||
)
|
||||
if err != nil || !changed || decision.Score != nil || decision.Outcome != AssessmentAttemptOutcomeDemonstration {
|
||||
t.Fatalf("FinalizeDemo(express) = changed %v decision %+v error %v", changed, decision, err)
|
||||
}
|
||||
result, err := NewAssessmentAttemptResultSnapshot(
|
||||
finalized, decision, "This training run is educational only.", []string{"demonstration_only"},
|
||||
)
|
||||
if err != nil || result.BasicScore != nil || result.Attempt.TargetGrade != nil ||
|
||||
result.Attempt.Specialization != nil || result.Outcome != AssessmentAttemptOutcomeDemonstration {
|
||||
t.Fatalf("express result = %+v, error %v", result, err)
|
||||
}
|
||||
}
|
||||
|
||||
func correctAssessmentTestAnswer(t *testing.T, variant AssessmentVariant) json.RawMessage {
|
||||
t.Helper()
|
||||
switch variant.AnswerFormat {
|
||||
case AnswerFormatInteger:
|
||||
return json.RawMessage(fmt.Sprintf(`{"format":"number","number":%s}`, variant.ReferenceAnswer))
|
||||
case AnswerFormatIntegerSequence:
|
||||
elements := make([]string, 0, len(strings.Fields(variant.ReferenceAnswer)))
|
||||
for _, ordinal := range strings.Fields(variant.ReferenceAnswer) {
|
||||
elements = append(elements, "job_"+ordinal)
|
||||
}
|
||||
encoded, err := json.Marshal(orderAssessmentAnswer{Format: "order", ElementIDs: elements})
|
||||
if err != nil {
|
||||
t.Fatalf("json.Marshal(order answer) error = %v", err)
|
||||
}
|
||||
return encoded
|
||||
default:
|
||||
t.Fatalf("unsupported test answer format %q", variant.AnswerFormat)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func incorrectAssessmentTestAnswer(t *testing.T, variant AssessmentVariant) json.RawMessage {
|
||||
t.Helper()
|
||||
switch variant.AnswerFormat {
|
||||
case AnswerFormatInteger:
|
||||
reference, err := strconv.ParseInt(variant.ReferenceAnswer, 10, 64)
|
||||
if err != nil {
|
||||
t.Fatalf("parse frozen numeric key %q: %v", variant.ReferenceAnswer, err)
|
||||
}
|
||||
return json.RawMessage(fmt.Sprintf(`{"format":"number","number":%d}`, reference+1))
|
||||
case AnswerFormatIntegerSequence:
|
||||
var answer orderAssessmentAnswer
|
||||
if err := json.Unmarshal(correctAssessmentTestAnswer(t, variant), &answer); err != nil || len(answer.ElementIDs) < 2 {
|
||||
t.Fatalf("decode frozen order key: %v", err)
|
||||
}
|
||||
answer.ElementIDs[0], answer.ElementIDs[1] = answer.ElementIDs[1], answer.ElementIDs[0]
|
||||
encoded, err := json.Marshal(answer)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal incorrect order answer: %v", err)
|
||||
}
|
||||
return encoded
|
||||
default:
|
||||
t.Fatalf("unsupported test answer format %q", variant.AnswerFormat)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func TestAssessmentAnswerDuplicateIsCanonicalNoOpEvenWithStaleVersion(t *testing.T) {
|
||||
policy := testAssessmentAttemptPolicyVersion(t)
|
||||
attempt := testAttemptWithPolicy(t, policy, AssessmentAttemptKindRoot, 1)
|
||||
item := attempt.Snapshot().Items[0]
|
||||
answer := json.RawMessage(fmt.Sprintf(`{"format":"number","number":%s}`, item.Variant.ReferenceAnswer))
|
||||
updated, changed, err := attempt.SubmitAnswer(attempt.Version(), item.ID, answer, attempt.Snapshot().CreatedAt.Add(time.Second))
|
||||
if err != nil || !changed {
|
||||
t.Fatalf("SubmitAnswer() = (%v, %v, %v), want saved answer", updated, changed, err)
|
||||
}
|
||||
answerWithDecimal := json.RawMessage(fmt.Sprintf(`{"format":"number","number":%s.0}`, item.Variant.ReferenceAnswer))
|
||||
replayed, changed, err := updated.SubmitAnswer(attempt.Version(), item.ID, answerWithDecimal, updated.Snapshot().LastActivityAt.Add(time.Second))
|
||||
if err != nil || changed || replayed.Version() != updated.Version() || replayed.Snapshot().Items[0].AnsweredAt != updated.Snapshot().Items[0].AnsweredAt {
|
||||
t.Fatalf("SubmitAnswer(duplicate) = (%v, %v, %v), want unchanged canonical replay", replayed, changed, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAssessmentOrderAnswerRequiresExactPermutationAndScoresFrozenSequence(t *testing.T) {
|
||||
input := testAssessmentInput()
|
||||
input.Key = "ordered-assessment-family"
|
||||
input.Generator = AssessmentSeedGenerator{
|
||||
Algorithm: "dependency_order.v1",
|
||||
Parameters: map[string]AssessmentParameterRange{
|
||||
"tasks": {Min: 4, Max: 4}, "links": {Min: 0, Max: 0},
|
||||
},
|
||||
StatementTemplate: "Order tasks {{.tasks}} with dependencies {{.dependencies}}.",
|
||||
}
|
||||
input.AnswerKey.AnswerFormat = AnswerFormatIntegerSequence
|
||||
family := restoreAssessment(t, input)
|
||||
variant, err := family.NewVariant(VariantSeed(22))
|
||||
if err != nil {
|
||||
t.Fatalf("NewVariant() error = %v", err)
|
||||
}
|
||||
ordered := make([]string, 0, 4)
|
||||
for _, token := range strings.Fields(variant.ReferenceAnswer) {
|
||||
ordered = append(ordered, "job_"+token)
|
||||
}
|
||||
wrongOrder := append([]string(nil), ordered...)
|
||||
wrongOrder[0], wrongOrder[1] = wrongOrder[1], wrongOrder[0]
|
||||
wrongAnswer, err := json.Marshal(orderAssessmentAnswer{Format: "order", ElementIDs: wrongOrder})
|
||||
if err != nil {
|
||||
t.Fatalf("json.Marshal(wrong order) error = %v", err)
|
||||
}
|
||||
wrong, correct, err := CanonicalAssessmentAnswerForVariant(wrongAnswer, variant)
|
||||
if err != nil || correct || len(wrong) == 0 {
|
||||
t.Fatalf("CanonicalAssessmentAnswerForVariant(wrong permutation) = (%s, %v, %v)", wrong, correct, err)
|
||||
}
|
||||
if _, _, err := CanonicalAssessmentAnswerForVariant(
|
||||
json.RawMessage(`{"format":"order","element_ids":["job_1","job_1","job_3","job_4"]}`), variant,
|
||||
); !errors.Is(err, ErrInvalidAssessmentAttempt) {
|
||||
t.Fatalf("duplicate order token error = %v, want invalid attempt", err)
|
||||
}
|
||||
correctAnswer, err := json.Marshal(orderAssessmentAnswer{Format: "order", ElementIDs: ordered})
|
||||
if err != nil {
|
||||
t.Fatalf("json.Marshal(reference order) error = %v", err)
|
||||
}
|
||||
_, correct, err = CanonicalAssessmentAnswerForVariant(correctAnswer, variant)
|
||||
if err != nil || !correct {
|
||||
t.Fatalf("CanonicalAssessmentAnswerForVariant(reference order) = (correct=%v, err=%v)", correct, err)
|
||||
}
|
||||
}
|
||||
|
||||
func testAttemptWithPolicy(
|
||||
t *testing.T,
|
||||
policy PolicyVersion,
|
||||
kind AssessmentAttemptKind,
|
||||
itemCount int,
|
||||
) AssessmentAttempt {
|
||||
t.Helper()
|
||||
items := testAssessmentAttemptItems(t, itemCount)
|
||||
if kind == AssessmentAttemptKindDemoExpress {
|
||||
items = testAssessmentAttemptItems(t, int(policy.Policy().Assessment.Training.DemoExpressItemCount))
|
||||
}
|
||||
input := NewAssessmentAttemptInput{
|
||||
UserID: uuid.New(), Kind: kind, BankCategory: "unit-category", Policy: policy,
|
||||
CreatedAt: testAssessmentAttemptCreatedAt, Items: items,
|
||||
}
|
||||
if kind == AssessmentAttemptKindDemoExpress {
|
||||
input.Versions = testTrainingAssessmentAttemptVersions(policy)
|
||||
} else {
|
||||
specialization, grade := SpecializationBackend, GradeJunior
|
||||
input.Specialization, input.TargetGrade = &specialization, &grade
|
||||
input.Versions = testAssessmentAttemptVersions(t, policy)
|
||||
}
|
||||
attempt, err := NewAssessmentAttempt(input)
|
||||
if err != nil {
|
||||
t.Fatalf("NewAssessmentAttempt() error = %v", err)
|
||||
}
|
||||
return attempt
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,556 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var testAssessmentAttemptCreatedAt = time.Date(2026, time.October, 7, 10, 0, 0, 0, time.UTC)
|
||||
|
||||
func testAssessmentAttemptPolicyVersion(t *testing.T) PolicyVersion {
|
||||
t.Helper()
|
||||
draft := mustDraft(t, NewPolicyVersionDraftInput{
|
||||
Key: ProductPolicyKey, Kind: PolicyKindDemo, Author: DemoPolicySeedAuthor, Policy: DemoProductPolicyV2(),
|
||||
}, 2)
|
||||
return mustRestore(t, storedFrom(draft))
|
||||
}
|
||||
|
||||
func testTrainingOnlyAssessmentPolicyVersion(t *testing.T) PolicyVersion {
|
||||
t.Helper()
|
||||
policy := DemoProductPolicyV2()
|
||||
policy.Assessment.Attempt = nil
|
||||
draft := mustDraft(t, NewPolicyVersionDraftInput{
|
||||
Key: ProductPolicyKey, Kind: PolicyKindDemo, Author: DemoPolicySeedAuthor, Policy: policy,
|
||||
}, 2)
|
||||
return mustRestore(t, storedFrom(draft))
|
||||
}
|
||||
|
||||
func testAssessmentAttemptVersions(t *testing.T, policy PolicyVersion) AssessmentAttemptVersions {
|
||||
t.Helper()
|
||||
gradingID, err := NewPolicyVersionID()
|
||||
if err != nil {
|
||||
t.Fatalf("NewPolicyVersionID() error = %v", err)
|
||||
}
|
||||
return AssessmentAttemptVersions{
|
||||
ProductPolicyVersionID: policy.ID(), ProductPolicyVersion: policy.Version(),
|
||||
GradingPolicyVersionID: gradingID, OpeningID: uuid.New(), OpeningManifestHash: testManifestHash(1),
|
||||
BankVersion: "backend-demo.2026-10.1", AlgorithmVersion: "assessment.v1",
|
||||
}
|
||||
}
|
||||
|
||||
func testTrainingAssessmentAttemptVersions(policy PolicyVersion) AssessmentAttemptVersions {
|
||||
return AssessmentAttemptVersions{
|
||||
ProductPolicyVersionID: policy.ID(), ProductPolicyVersion: policy.Version(),
|
||||
TrainingBindingID: uuid.New(), TrainingManifestHash: testManifestHash(2),
|
||||
BankVersion: "training-demo.2026-10.1", AlgorithmVersion: "assessment.v1",
|
||||
}
|
||||
}
|
||||
|
||||
func testManifestHash(value byte) [32]byte {
|
||||
var digest [32]byte
|
||||
digest[0] = value
|
||||
return digest
|
||||
}
|
||||
|
||||
func testAssessmentAttemptItems(t *testing.T, count int) []AssessmentAttemptItemInput {
|
||||
t.Helper()
|
||||
items := make([]AssessmentAttemptItemInput, count)
|
||||
for index := range items {
|
||||
input := testAssessmentInput()
|
||||
input.Key = AssessmentFamilyKey(fmt.Sprintf("unit-test-family-%d", index))
|
||||
family := restoreAssessment(t, input)
|
||||
variant, err := family.NewVariant(VariantSeed(index + 1))
|
||||
if err != nil {
|
||||
t.Fatalf("NewVariant() error = %v", err)
|
||||
}
|
||||
items[index] = AssessmentAttemptItemInput{Variant: variant}
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
func testRootAssessmentAttempt(t *testing.T, userID uuid.UUID, grade GradeCode) AssessmentAttempt {
|
||||
t.Helper()
|
||||
policy := testAssessmentAttemptPolicyVersion(t)
|
||||
items := testAssessmentAttemptItems(t, 2)
|
||||
specialization := SpecializationBackend
|
||||
attempt, err := NewAssessmentAttempt(NewAssessmentAttemptInput{
|
||||
UserID: userID, Kind: AssessmentAttemptKindRoot, BankCategory: "unit-category",
|
||||
Specialization: &specialization, TargetGrade: &grade,
|
||||
Versions: testAssessmentAttemptVersions(t, policy), Policy: policy,
|
||||
CreatedAt: testAssessmentAttemptCreatedAt, Items: items,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewAssessmentAttempt(root) error = %v", err)
|
||||
}
|
||||
return attempt
|
||||
}
|
||||
|
||||
func terminalAssessmentAttempt(t *testing.T, attempt AssessmentAttempt, state AssessmentAttemptState, outcome AssessmentAttemptOutcome, endedAt time.Time) AssessmentAttempt {
|
||||
t.Helper()
|
||||
snapshot := attempt.Snapshot()
|
||||
snapshot.State = state
|
||||
snapshot.Outcome = outcome
|
||||
snapshot.EndedAt = endedAt
|
||||
snapshot.UpdatedAt = endedAt
|
||||
restored, err := RestoreAssessmentAttempt(snapshot)
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreAssessmentAttempt(terminal) error = %v", err)
|
||||
}
|
||||
return restored
|
||||
}
|
||||
|
||||
func TestNewAssessmentAttemptPinsPolicyVersionsAndFrozenVariants(t *testing.T) {
|
||||
userID := uuid.New()
|
||||
attempt := testRootAssessmentAttempt(t, userID, GradeJunior)
|
||||
snapshot := attempt.Snapshot()
|
||||
if attempt.IsZero() || attempt.UserID() != userID || attempt.Kind() != AssessmentAttemptKindRoot ||
|
||||
attempt.Mode() != AssessmentAttemptModeDemoBasic || attempt.State() != AssessmentAttemptStateInProgress ||
|
||||
attempt.Version() != 1 || attempt.SessionsUsed() != 1 || attempt.MaxSessions() != 2 ||
|
||||
attempt.IdleTimeoutSeconds() != 1800 || attempt.RootAttemptID() != attempt.ID() {
|
||||
t.Fatalf("new root attempt has unexpected identity or session state: %+v", snapshot)
|
||||
}
|
||||
wantDeadline := testAssessmentAttemptCreatedAt.Add(72 * time.Hour)
|
||||
if !attempt.ExpiresAt().Equal(wantDeadline) || !attempt.ChainDeadline().Equal(wantDeadline) {
|
||||
t.Fatalf("attempt expires %s and chain ends %s, want %s", attempt.ExpiresAt(), attempt.ChainDeadline(), wantDeadline)
|
||||
}
|
||||
if len(snapshot.Items) != 2 || snapshot.Items[0].Ordinal != 1 || snapshot.Items[1].Ordinal != 2 ||
|
||||
snapshot.Items[0].Variant.Statement == "" || snapshot.Items[0].Variant.ReferenceAnswer == "" {
|
||||
t.Fatalf("frozen item snapshots = %+v, want ordered variants with reference answers", snapshot.Items)
|
||||
}
|
||||
if snapshot.Versions.ProductPolicyVersionID == snapshot.Versions.GradingPolicyVersionID {
|
||||
t.Fatal("test fixture should prove product and opening grading versions are preserved separately")
|
||||
}
|
||||
if snapshot.Versions.OpeningID == uuid.Nil || snapshot.Versions.OpeningManifestHash == [32]byte{} {
|
||||
t.Fatal("real attempt did not pin its reviewed opening and manifest")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewAssessmentAttemptRefusesLegacyPolicyWithoutAttemptSettings(t *testing.T) {
|
||||
legacyDraft := mustDraft(t, NewPolicyVersionDraftInput{
|
||||
Key: ProductPolicyKey, Kind: PolicyKindDemo, Author: DemoPolicySeedAuthor, Policy: DemoProductPolicyV1(),
|
||||
}, 1)
|
||||
legacyPolicy := mustRestore(t, storedFrom(legacyDraft))
|
||||
specialization, grade := SpecializationBackend, GradeJunior
|
||||
_, err := NewAssessmentAttempt(NewAssessmentAttemptInput{
|
||||
UserID: uuid.New(), Kind: AssessmentAttemptKindRoot, BankCategory: "unit-category",
|
||||
Specialization: &specialization, TargetGrade: &grade,
|
||||
Versions: testAssessmentAttemptVersions(t, legacyPolicy), Policy: legacyPolicy,
|
||||
CreatedAt: testAssessmentAttemptCreatedAt, Items: testAssessmentAttemptItems(t, 1),
|
||||
})
|
||||
if !errors.Is(err, ErrInvalidAssessmentAttempt) {
|
||||
t.Fatalf("NewAssessmentAttempt(legacy policy) error = %v, want fail-closed invalid attempt", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCorrectiveAttemptSharesRootDeadlineAndRejectsForeignOrInvalidRoot(t *testing.T) {
|
||||
userID := uuid.New()
|
||||
root := terminalAssessmentAttempt(t, testRootAssessmentAttempt(t, userID, GradeSenior),
|
||||
AssessmentAttemptStateCompleted, AssessmentAttemptOutcomeNotConfirmed, testAssessmentAttemptCreatedAt.Add(time.Hour))
|
||||
policy := testAssessmentAttemptPolicyVersion(t)
|
||||
specialization, grade, language := SpecializationBackend, GradeMiddle, TaskLanguageGo
|
||||
input := NewAssessmentAttemptInput{
|
||||
UserID: userID, Kind: AssessmentAttemptKindCorrective, BankCategory: "unit-category",
|
||||
Specialization: &specialization, TargetGrade: &grade, TaskLanguage: &language,
|
||||
Chain: []AssessmentAttempt{root}, Versions: testAssessmentAttemptVersions(t, policy), Policy: policy,
|
||||
CreatedAt: testAssessmentAttemptCreatedAt.Add(12 * time.Hour), Items: testAssessmentAttemptItems(t, 1),
|
||||
}
|
||||
attempt, err := NewAssessmentAttempt(input)
|
||||
if err != nil {
|
||||
t.Fatalf("NewAssessmentAttempt(corrective) error = %v", err)
|
||||
}
|
||||
if attempt.RootAttemptID() != root.ID() || !attempt.ChainDeadline().Equal(root.ChainDeadline()) ||
|
||||
!attempt.ExpiresAt().Equal(root.ChainDeadline()) {
|
||||
t.Fatalf("corrective attempt does not share the root deadline: %+v", attempt.Snapshot())
|
||||
}
|
||||
|
||||
foreign := terminalAssessmentAttempt(t, testRootAssessmentAttempt(t, uuid.New(), GradeSenior),
|
||||
AssessmentAttemptStateExpired, "", testAssessmentAttemptCreatedAt.Add(time.Hour))
|
||||
input.Chain = []AssessmentAttempt{foreign}
|
||||
if _, err := NewAssessmentAttempt(input); !errors.Is(err, ErrInvalidAssessmentAttempt) {
|
||||
t.Fatalf("NewAssessmentAttempt(foreign root) error = %v, want ErrInvalidAssessmentAttempt", err)
|
||||
}
|
||||
|
||||
input.Chain = []AssessmentAttempt{root}
|
||||
input.TargetGrade = ptr(GradeSenior)
|
||||
if _, err := NewAssessmentAttempt(input); !errors.Is(err, ErrInvalidAssessmentAttempt) {
|
||||
t.Fatalf("NewAssessmentAttempt(non-lower grade) error = %v, want ErrInvalidAssessmentAttempt", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCorrectiveAttemptRequiresTerminalPredecessorAndStrictlyDescendingGrades(t *testing.T) {
|
||||
userID := uuid.New()
|
||||
activeRoot := testRootAssessmentAttempt(t, userID, GradeSenior)
|
||||
policy := testAssessmentAttemptPolicyVersion(t)
|
||||
specialization, grade := SpecializationBackend, GradeMiddle
|
||||
input := NewAssessmentAttemptInput{
|
||||
UserID: userID, Kind: AssessmentAttemptKindCorrective, BankCategory: "unit-category",
|
||||
Specialization: &specialization, TargetGrade: &grade,
|
||||
Chain: []AssessmentAttempt{activeRoot}, Versions: testAssessmentAttemptVersions(t, policy), Policy: policy,
|
||||
CreatedAt: testAssessmentAttemptCreatedAt.Add(time.Hour), Items: testAssessmentAttemptItems(t, 1),
|
||||
}
|
||||
if _, err := NewAssessmentAttempt(input); !errors.Is(err, ErrInvalidAssessmentAttempt) {
|
||||
t.Fatalf("corrective attempt from active root error = %v, want ErrInvalidAssessmentAttempt", err)
|
||||
}
|
||||
|
||||
root := terminalAssessmentAttempt(t, activeRoot, AssessmentAttemptStateExpired, "", testAssessmentAttemptCreatedAt.Add(time.Hour))
|
||||
input.Chain = []AssessmentAttempt{root}
|
||||
input.CreatedAt = testAssessmentAttemptCreatedAt.Add(2 * time.Hour)
|
||||
input.TargetGrade = ptr(GradeSenior)
|
||||
if _, err := NewAssessmentAttempt(input); !errors.Is(err, ErrInvalidAssessmentAttempt) {
|
||||
t.Fatalf("expired root with non-lower grade error = %v, want ErrInvalidAssessmentAttempt", err)
|
||||
}
|
||||
|
||||
input.TargetGrade = ptr(GradeMiddle)
|
||||
corrective, err := NewAssessmentAttempt(input)
|
||||
if err != nil {
|
||||
t.Fatalf("corrective attempt after early root expiry error = %v", err)
|
||||
}
|
||||
ended := terminalAssessmentAttempt(t, corrective, AssessmentAttemptStateCompleted,
|
||||
AssessmentAttemptOutcomeNotDetermined, testAssessmentAttemptCreatedAt.Add(3*time.Hour))
|
||||
input.Chain = []AssessmentAttempt{root, ended}
|
||||
input.TargetGrade = ptr(GradeJunior)
|
||||
input.CreatedAt = testAssessmentAttemptCreatedAt.Add(4 * time.Hour)
|
||||
if _, err := NewAssessmentAttempt(input); err != nil {
|
||||
t.Fatalf("lower corrective attempt after eligible predecessor error = %v", err)
|
||||
}
|
||||
input.TargetGrade = ptr(GradeMiddle)
|
||||
if _, err := NewAssessmentAttempt(input); !errors.Is(err, ErrInvalidAssessmentAttempt) {
|
||||
t.Fatalf("repeated chain grade error = %v, want ErrInvalidAssessmentAttempt", err)
|
||||
}
|
||||
|
||||
input.TargetGrade = ptr(GradeIntern)
|
||||
if _, err := NewAssessmentAttempt(input); err != nil {
|
||||
t.Fatalf("strictly lower final grade error = %v", err)
|
||||
}
|
||||
|
||||
confirmedRoot := terminalAssessmentAttempt(t, activeRoot, AssessmentAttemptStateCompleted,
|
||||
AssessmentAttemptOutcomeConfirmed, testAssessmentAttemptCreatedAt.Add(time.Hour))
|
||||
input.Chain = []AssessmentAttempt{confirmedRoot}
|
||||
input.TargetGrade = ptr(GradeMiddle)
|
||||
if _, err := NewAssessmentAttempt(input); !errors.Is(err, ErrInvalidAssessmentAttempt) {
|
||||
t.Fatalf("confirmed root correction error = %v, want ErrInvalidAssessmentAttempt", err)
|
||||
}
|
||||
|
||||
input.Chain = []AssessmentAttempt{root, ended}
|
||||
input.CreatedAt = root.ChainDeadline()
|
||||
if _, err := NewAssessmentAttempt(input); !errors.Is(err, ErrInvalidAssessmentAttempt) {
|
||||
t.Fatalf("corrective attempt at chain deadline error = %v, want ErrInvalidAssessmentAttempt", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDemoExpressAttemptHasNoQualificationTrackAndUsesExplicitDuration(t *testing.T) {
|
||||
policy := testTrainingOnlyAssessmentPolicyVersion(t)
|
||||
attempt, err := NewAssessmentAttempt(NewAssessmentAttemptInput{
|
||||
UserID: uuid.New(), Kind: AssessmentAttemptKindDemoExpress, BankCategory: "unit-training-category",
|
||||
Versions: testTrainingAssessmentAttemptVersions(policy), Policy: policy,
|
||||
CreatedAt: testAssessmentAttemptCreatedAt, Items: testAssessmentAttemptItems(t, 3),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewAssessmentAttempt(express) error = %v", err)
|
||||
}
|
||||
if attempt.Mode() != AssessmentAttemptModeDemoExpress || !attempt.RootAttemptID().IsZero() ||
|
||||
!attempt.ChainDeadline().IsZero() || !attempt.ExpiresAt().Equal(testAssessmentAttemptCreatedAt.Add(240*time.Second)) {
|
||||
t.Fatalf("express attempt has qualification fields or wrong duration: %+v", attempt.Snapshot())
|
||||
}
|
||||
if attempt.MaxSessions() != 1 || attempt.IdleTimeoutSeconds() != 240 {
|
||||
t.Fatalf("express session limits = %d sessions / %d seconds, want the explicit training policy values", attempt.MaxSessions(), attempt.IdleTimeoutSeconds())
|
||||
}
|
||||
if versions := attempt.Snapshot().Versions; !versions.GradingPolicyVersionID.IsZero() || versions.OpeningID != uuid.Nil ||
|
||||
versions.TrainingBindingID == uuid.Nil || versions.TrainingManifestHash == [32]byte{} {
|
||||
t.Fatalf("express attempt must pin only its separate reviewed training source: %+v", versions)
|
||||
}
|
||||
|
||||
specialization := SpecializationBackend
|
||||
_, err = NewAssessmentAttempt(NewAssessmentAttemptInput{
|
||||
UserID: uuid.New(), Kind: AssessmentAttemptKindDemoExpress, BankCategory: "unit-training-category", Specialization: &specialization,
|
||||
Versions: testTrainingAssessmentAttemptVersions(policy), Policy: policy,
|
||||
CreatedAt: testAssessmentAttemptCreatedAt, Items: testAssessmentAttemptItems(t, 3),
|
||||
})
|
||||
if !errors.Is(err, ErrInvalidAssessmentAttempt) {
|
||||
t.Fatalf("express attempt with category error = %v, want ErrInvalidAssessmentAttempt", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAttemptCreationRequiresRealFrozenItemsAndDistinctFamilies(t *testing.T) {
|
||||
userID := uuid.New()
|
||||
policy := testAssessmentAttemptPolicyVersion(t)
|
||||
specialization, grade := SpecializationBackend, GradeJunior
|
||||
input := NewAssessmentAttemptInput{
|
||||
UserID: userID, Kind: AssessmentAttemptKindRoot, BankCategory: "unit-category",
|
||||
Specialization: &specialization, TargetGrade: &grade,
|
||||
Versions: testAssessmentAttemptVersions(t, policy), Policy: policy,
|
||||
CreatedAt: testAssessmentAttemptCreatedAt,
|
||||
}
|
||||
if _, err := NewAssessmentAttempt(input); !errors.Is(err, ErrInvalidAssessmentAttempt) {
|
||||
t.Fatalf("NewAssessmentAttempt(empty bank) error = %v, want ErrInvalidAssessmentAttempt", err)
|
||||
}
|
||||
item := testAssessmentAttemptItems(t, 1)[0]
|
||||
input.Items = []AssessmentAttemptItemInput{item, item}
|
||||
if _, err := NewAssessmentAttempt(input); !errors.Is(err, ErrInvalidAssessmentAttempt) {
|
||||
t.Fatalf("NewAssessmentAttempt(repeated family) error = %v, want ErrInvalidAssessmentAttempt", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAttemptSnapshotCopiesAndRedactsFrozenContent(t *testing.T) {
|
||||
attempt := testRootAssessmentAttempt(t, uuid.New(), GradeJunior)
|
||||
first := attempt.Snapshot()
|
||||
statement := first.Items[0].Variant.Statement
|
||||
answer := first.Items[0].Variant.ReferenceAnswer
|
||||
first.Items[0].Variant.Statement = "changed"
|
||||
first.Items[0].Variant.Parameters["capacity"] = 999
|
||||
if second := attempt.Snapshot(); second.Items[0].Variant.Statement != statement || second.Items[0].Variant.Parameters["capacity"] == 999 {
|
||||
t.Fatal("mutating a snapshot changed the attempt's frozen variant")
|
||||
}
|
||||
if got := fmt.Sprint(attempt); got != redactedAssessmentAttempt {
|
||||
t.Fatalf("attempt String() = %q, want redacted marker", got)
|
||||
}
|
||||
if got := fmt.Sprint(first.Items[0]); got != redactedAssessmentAttempt {
|
||||
t.Fatalf("item String() = %q, want redacted marker", got)
|
||||
}
|
||||
if got := fmt.Sprint(first); got != redactedAssessmentAttempt {
|
||||
t.Fatalf("snapshot String() = %q, want redacted marker", got)
|
||||
}
|
||||
if answer == "" {
|
||||
t.Fatal("test variant has no reference answer")
|
||||
}
|
||||
publicJSON, err := json.Marshal(attempt.PublicSnapshot())
|
||||
if err != nil {
|
||||
t.Fatalf("json.Marshal(PublicSnapshot) error = %v", err)
|
||||
}
|
||||
for _, privateName := range []string{"reference_answer", "answer", "seed", "family_key", "user_id", "opening_id", "rubric"} {
|
||||
if strings.Contains(string(publicJSON), `"`+privateName+`"`) {
|
||||
t.Fatalf("public attempt snapshot contains private field %q: %s", privateName, publicJSON)
|
||||
}
|
||||
}
|
||||
if public := attempt.PublicSnapshot(); public.CurrentItem == nil || public.CurrentItem.Prompt != statement ||
|
||||
public.CurrentItem.ID != first.Items[0].ID || public.AnsweredItems != 0 {
|
||||
t.Fatalf("public attempt projection = %+v, want the current prompt without answers", public)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFrozenVariantStorageBoundCoversWorstCaseJSONEscaping(t *testing.T) {
|
||||
key, err := ParseAssessmentFamilyKey("max-content-family")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
criteria := make([]AssessmentRubricCriterion, maxAssessmentRubricCriteria)
|
||||
for index := range criteria {
|
||||
criteria[index] = AssessmentRubricCriterion{
|
||||
ID: fmt.Sprintf("criterion_%d", index), Description: strings.Repeat("<", maxAssessmentTextLength),
|
||||
}
|
||||
}
|
||||
variant := AssessmentVariant{
|
||||
FamilyID: AssessmentFamilyID(uuid.New()), FamilyKey: key, FamilyVersion: 1,
|
||||
Seed: 1, Parameters: map[string]int32{"value": 1},
|
||||
Statement: strings.Repeat("<", maxStatementBytes), ReferenceAnswer: strings.Repeat("<", maxAssessmentTextLength),
|
||||
AnswerFormat: AnswerFormatInteger,
|
||||
Rubric: AssessmentRubric{Principle: strings.Repeat("<", maxAssessmentTextLength), Criteria: criteria},
|
||||
}
|
||||
encoded, err := MarshalAssessmentAttemptVariant(variant)
|
||||
if err != nil {
|
||||
t.Fatalf("json.Marshal(maximum valid variant) error = %v", err)
|
||||
}
|
||||
if len(encoded) <= 256<<10 || len(encoded) > maxAssessmentAttemptVariantBytes || !validFrozenVariant(variant) {
|
||||
t.Fatalf("worst-case encoded variant size = %d bytes; want above 256 KiB, within %d bytes, and valid", len(encoded), maxAssessmentAttemptVariantBytes)
|
||||
}
|
||||
|
||||
variant.Statement = string([]byte{0xff})
|
||||
if validFrozenVariant(variant) {
|
||||
t.Fatal("invalid UTF-8 statement was accepted")
|
||||
}
|
||||
variant.Statement = "valid"
|
||||
variant.Parameters = map[string]int32{strings.Repeat("x", maxAssessmentAttemptVariantBytes): 1}
|
||||
if validFrozenVariant(variant) {
|
||||
t.Fatal("variant exceeding the persisted JSON byte cap was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartOrResumeSessionIsExplicitVersionedAndBounded(t *testing.T) {
|
||||
attempt := testRootAssessmentAttempt(t, uuid.New(), GradeJunior)
|
||||
|
||||
unchanged, changed, err := attempt.StartOrResumeSession(1, testAssessmentAttemptCreatedAt.Add(time.Minute))
|
||||
if err != nil || changed || unchanged.Version() != 1 || unchanged.SessionsUsed() != 1 {
|
||||
t.Fatalf("active-session repeat = version %d, sessions %d, changed %t, err %v", unchanged.Version(), unchanged.SessionsUsed(), changed, err)
|
||||
}
|
||||
|
||||
resumedAt := testAssessmentAttemptCreatedAt.Add(30 * time.Minute)
|
||||
resumed, changed, err := attempt.StartOrResumeSession(1, resumedAt)
|
||||
if err != nil || !changed || resumed.Version() != 2 || resumed.SessionsUsed() != 2 || !resumed.Snapshot().SessionStartedAt.Equal(resumedAt) {
|
||||
t.Fatalf("first resume = version %d, sessions %d, changed %t, err %v", resumed.Version(), resumed.SessionsUsed(), changed, err)
|
||||
}
|
||||
|
||||
endedAt := resumedAt.Add(30 * time.Minute)
|
||||
expired, changed, err := resumed.StartOrResumeSession(2, endedAt)
|
||||
if err != nil || !changed || expired.State() != AssessmentAttemptStateExpired || expired.Version() != 3 || expired.SessionsUsed() != 2 {
|
||||
t.Fatalf("session-budget end = state %s, version %d, sessions %d, changed %t, err %v", expired.State(), expired.Version(), expired.SessionsUsed(), changed, err)
|
||||
}
|
||||
if _, _, err := attempt.StartOrResumeSession(0, resumedAt); !errors.Is(err, ErrAssessmentAttemptVersionConflict) {
|
||||
t.Fatalf("stale session version error = %v, want ErrAssessmentAttemptVersionConflict", err)
|
||||
}
|
||||
terminal, changed, err := expired.StartOrResumeSession(3, endedAt.Add(time.Hour))
|
||||
if err != nil || changed || terminal.Version() != expired.Version() ||
|
||||
!terminal.Snapshot().UpdatedAt.Equal(expired.Snapshot().UpdatedAt) {
|
||||
t.Fatalf("terminal session command = version %d, changed %t, err %v; want unchanged stored snapshot", terminal.Version(), changed, err)
|
||||
}
|
||||
if _, _, err := expired.StartOrResumeSession(2, endedAt.Add(time.Hour)); !errors.Is(err, ErrAssessmentAttemptVersionConflict) {
|
||||
t.Fatalf("stale terminal session version error = %v, want version conflict", err)
|
||||
}
|
||||
|
||||
completed := terminalAssessmentAttempt(t, attempt, AssessmentAttemptStateCompleted,
|
||||
AssessmentAttemptOutcomeNotConfirmed, testAssessmentAttemptCreatedAt.Add(time.Hour))
|
||||
finished, changed, err := completed.StartOrResumeSession(completed.Version(), testAssessmentAttemptCreatedAt.Add(2*time.Hour))
|
||||
if err != nil || changed || finished.Version() != completed.Version() ||
|
||||
!finished.Snapshot().EndedAt.Equal(completed.Snapshot().EndedAt) {
|
||||
t.Fatalf("completed session command = version %d, changed %t, err %v; want unchanged stored snapshot", finished.Version(), changed, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartOrResumeSessionExpiresAtAttemptDeadlineWithoutExtendingIt(t *testing.T) {
|
||||
attempt := testRootAssessmentAttempt(t, uuid.New(), GradeJunior)
|
||||
attemptExpiry := attempt.ExpiresAt()
|
||||
expired, changed, err := attempt.StartOrResumeSession(1, attemptExpiry)
|
||||
if err != nil || !changed || expired.State() != AssessmentAttemptStateExpired || expired.Version() != 2 ||
|
||||
!expired.ExpiresAt().Equal(attemptExpiry) || !expired.Snapshot().EndedAt.Equal(attemptExpiry) {
|
||||
t.Fatalf("deadline transition = %+v, changed %t, err %v", expired.Snapshot(), changed, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartOrResumeSessionDoesNotExpirePendingLifecycleStates(t *testing.T) {
|
||||
for _, state := range []AssessmentAttemptState{
|
||||
AssessmentAttemptStatePracticePending,
|
||||
AssessmentAttemptStateAdditionalPracticePending,
|
||||
AssessmentAttemptStateReadyToFinalize,
|
||||
} {
|
||||
t.Run(string(state), func(t *testing.T) {
|
||||
attempt := testRootAssessmentAttempt(t, uuid.New(), GradeJunior)
|
||||
snapshot := attempt.Snapshot()
|
||||
snapshot.State = state
|
||||
if state == AssessmentAttemptStateReadyToFinalize {
|
||||
answeredAt := snapshot.CreatedAt.Add(time.Second)
|
||||
for index := range snapshot.Items {
|
||||
item := &snapshot.Items[index]
|
||||
answer := json.RawMessage(fmt.Sprintf(`{"format":"number","number":%s}`, item.Variant.ReferenceAnswer))
|
||||
canonical, _, err := CanonicalAssessmentAnswerForVariant(answer, item.Variant)
|
||||
if err != nil {
|
||||
t.Fatalf("CanonicalAssessmentAnswerForVariant() error = %v", err)
|
||||
}
|
||||
item.Answer, item.AnsweredAt = canonical, answeredAt
|
||||
}
|
||||
snapshot.LastActivityAt, snapshot.UpdatedAt = answeredAt, answeredAt
|
||||
}
|
||||
attempt, err := RestoreAssessmentAttempt(snapshot)
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreAssessmentAttempt() error = %v", err)
|
||||
}
|
||||
|
||||
result, changed, err := attempt.StartOrResumeSession(attempt.Version(), attempt.ExpiresAt())
|
||||
if err != nil || changed || result.State() != state || result.Version() != attempt.Version() ||
|
||||
result.SessionsUsed() != attempt.SessionsUsed() ||
|
||||
!result.Snapshot().UpdatedAt.Equal(attempt.Snapshot().UpdatedAt) ||
|
||||
!result.Snapshot().EndedAt.IsZero() {
|
||||
t.Fatalf("session transition = state %s, version %d, sessions %d, changed %t, err %v; want unchanged %s",
|
||||
result.State(), result.Version(), result.SessionsUsed(), changed, err, state)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAssessmentAttemptCanonicalizesTimesAndBoundsStoredAnswers(t *testing.T) {
|
||||
userID := uuid.New()
|
||||
policy := testAssessmentAttemptPolicyVersion(t)
|
||||
specialization, grade := SpecializationBackend, GradeJunior
|
||||
created := time.Date(2026, time.October, 7, 12, 0, 0, 123456789, time.FixedZone("test", 3*60*60))
|
||||
attempt, err := NewAssessmentAttempt(NewAssessmentAttemptInput{
|
||||
UserID: userID, Kind: AssessmentAttemptKindRoot, BankCategory: "unit-category",
|
||||
Specialization: &specialization, TargetGrade: &grade,
|
||||
Versions: testAssessmentAttemptVersions(t, policy), Policy: policy,
|
||||
CreatedAt: created, Items: testAssessmentAttemptItems(t, 1),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewAssessmentAttempt() error = %v", err)
|
||||
}
|
||||
wantCreated := time.UnixMicro(created.UTC().UnixMicro()).UTC()
|
||||
if got := attempt.Snapshot().CreatedAt; !got.Equal(wantCreated) || got.Location() != time.UTC || got.Nanosecond()%1000 != 0 {
|
||||
t.Fatalf("created time = %s (%s), want canonical UTC microseconds %s", got, got.Location(), wantCreated)
|
||||
}
|
||||
|
||||
snapshot := attempt.Snapshot()
|
||||
snapshot.UpdatedAt = snapshot.CreatedAt.Add(time.Minute)
|
||||
sourceAnswer, err := json.Marshal(struct {
|
||||
Format string `json:"format"`
|
||||
SourceCode string `json:"source_code"`
|
||||
}{Format: "practice", SourceCode: strings.Repeat("<", 65536)})
|
||||
if err != nil {
|
||||
t.Fatalf("json.Marshal(maximum escaped source answer) error = %v", err)
|
||||
}
|
||||
snapshot.Items[0].Answer, err = CanonicalAssessmentAttemptAnswer(sourceAnswer)
|
||||
if err != nil {
|
||||
t.Fatalf("CanonicalAssessmentAttemptAnswer(maximum escaped source) error = %v", err)
|
||||
}
|
||||
if len(snapshot.Items[0].Answer) <= 6*65536 {
|
||||
t.Fatalf("canonical source answer length = %d, want HTML escaping overhead", len(snapshot.Items[0].Answer))
|
||||
}
|
||||
snapshot.Items[0].AnsweredAt = snapshot.CreatedAt.Add(30 * time.Second)
|
||||
withAnswer, err := RestoreAssessmentAttempt(snapshot)
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreAssessmentAttempt(maximum escaped source answer) error = %v", err)
|
||||
}
|
||||
|
||||
controlAnswer, err := json.Marshal(struct {
|
||||
Format string `json:"format"`
|
||||
Config string `json:"config"`
|
||||
}{Format: "configuration", Config: string([]byte{0, '\n', '\t'})})
|
||||
if err != nil {
|
||||
t.Fatalf("json.Marshal(schema-valid control characters) error = %v", err)
|
||||
}
|
||||
snapshot.Items[0].Answer, err = CanonicalAssessmentAttemptAnswer(controlAnswer)
|
||||
if err != nil {
|
||||
t.Fatalf("CanonicalAssessmentAttemptAnswer(schema-valid control characters) error = %v", err)
|
||||
}
|
||||
if !bytes.Contains(snapshot.Items[0].Answer, []byte(`\u0000`)) {
|
||||
t.Fatalf("canonical answer did not preserve escaped NUL: %q", snapshot.Items[0].Answer)
|
||||
}
|
||||
snapshot.Items[0].AnsweredAt = snapshot.CreatedAt.Add(45 * time.Second)
|
||||
if _, err := RestoreAssessmentAttempt(snapshot); err != nil {
|
||||
t.Fatalf("RestoreAssessmentAttempt(schema-valid escaped control characters) error = %v", err)
|
||||
}
|
||||
|
||||
stored := withAnswer.Snapshot()
|
||||
stored.Items[0].Answer[0] = '['
|
||||
if withAnswer.Snapshot().Items[0].Answer[0] != '{' {
|
||||
t.Fatal("mutating a returned answer snapshot changed the attempt")
|
||||
}
|
||||
|
||||
snapshot.Items[0].AnsweredAt = snapshot.UpdatedAt.Add(time.Microsecond)
|
||||
if _, err := RestoreAssessmentAttempt(snapshot); !errors.Is(err, ErrInvalidAssessmentAttempt) {
|
||||
t.Fatalf("answer after attempt update error = %v, want invalid attempt", err)
|
||||
}
|
||||
snapshot.Items[0].AnsweredAt = snapshot.ExpiresAt
|
||||
if _, err := RestoreAssessmentAttempt(snapshot); !errors.Is(err, ErrInvalidAssessmentAttempt) {
|
||||
t.Fatalf("answer at attempt expiry error = %v, want invalid attempt", err)
|
||||
}
|
||||
snapshot.Items[0].AnsweredAt = snapshot.CreatedAt.Add(time.Second)
|
||||
oversizedAnswer, err := json.Marshal(struct {
|
||||
Format string `json:"format"`
|
||||
SourceCode string `json:"source_code"`
|
||||
}{Format: "practice", SourceCode: strings.Repeat("<", maxAssessmentAttemptAnswerBytes/6+1)})
|
||||
if err != nil {
|
||||
t.Fatalf("json.Marshal(oversized answer) error = %v", err)
|
||||
}
|
||||
if _, err := CanonicalAssessmentAttemptAnswer(oversizedAnswer); !errors.Is(err, ErrInvalidAssessmentAttempt) {
|
||||
t.Fatalf("CanonicalAssessmentAttemptAnswer(oversized) error = %v, want invalid attempt", err)
|
||||
}
|
||||
snapshot.Items[0].Answer = oversizedAnswer
|
||||
if _, err := RestoreAssessmentAttempt(snapshot); !errors.Is(err, ErrInvalidAssessmentAttempt) {
|
||||
t.Fatalf("oversized answer error = %v, want invalid attempt", err)
|
||||
}
|
||||
}
|
||||
|
||||
func ptr[T any](value T) *T { return &value }
|
||||
@@ -0,0 +1,222 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const (
|
||||
assessmentResultSchemaVersion int32 = 1
|
||||
assessmentResultRuleBasicPassMark = "demo_basic_pass_mark"
|
||||
assessmentResultRuleTrainingOnly = "demonstration_only"
|
||||
)
|
||||
|
||||
// AssessmentAttemptResultPins retain the private immutable source identities
|
||||
// behind a candidate-visible result.
|
||||
type AssessmentAttemptResultPins struct {
|
||||
ProductPolicyVersionID PolicyVersionID `json:"product_policy_version_id"`
|
||||
ProductPolicyVersion int32 `json:"product_policy_version"`
|
||||
GradingPolicyVersionID PolicyVersionID `json:"grading_policy_version_id"`
|
||||
OpeningID uuid.UUID `json:"opening_id"`
|
||||
OpeningManifestHash [32]byte `json:"opening_manifest_sha256"`
|
||||
TrainingBindingID uuid.UUID `json:"training_binding_id"`
|
||||
TrainingManifestHash [32]byte `json:"training_manifest_sha256"`
|
||||
BankVersion string `json:"bank_version"`
|
||||
AlgorithmVersion string `json:"algorithm_version"`
|
||||
}
|
||||
|
||||
// AssessmentAttemptDecisionRationale records the exact basic rule and policy
|
||||
// threshold used by the server. It contains no answer keys or per-item data.
|
||||
type AssessmentAttemptDecisionRationale struct {
|
||||
Rule string `json:"rule"`
|
||||
PassMarkBasisPoints int32 `json:"pass_mark_basis_points"`
|
||||
PassPoints int32 `json:"pass_points"`
|
||||
ScoredItems int32 `json:"scored_items"`
|
||||
}
|
||||
|
||||
// AssessmentAttemptResultSnapshot is the immutable persisted result for one
|
||||
// completed attempt. It is separate from mutable attempt progress and stores
|
||||
// only an allowlisted public projection plus private version pins and rationale.
|
||||
type AssessmentAttemptResultSnapshot struct {
|
||||
SchemaVersion int32 `json:"schema_version"`
|
||||
Attempt AssessmentAttemptPublicSnapshot `json:"attempt"`
|
||||
Pins AssessmentAttemptResultPins `json:"pins"`
|
||||
Outcome AssessmentAttemptOutcome `json:"outcome"`
|
||||
NotDeterminedReason string `json:"not_determined_reason,omitempty"`
|
||||
BasicScore *AssessmentBasicScore `json:"basic_score,omitempty"`
|
||||
Rationale AssessmentAttemptDecisionRationale `json:"rationale"`
|
||||
Limitations []string `json:"limitations"`
|
||||
Summary string `json:"summary,omitempty"`
|
||||
DecidedAt time.Time `json:"decided_at"`
|
||||
}
|
||||
|
||||
// NewAssessmentAttemptResultSnapshot binds a finalized domain decision to the
|
||||
// immutable attempt and its pinned product, bank, and grading versions.
|
||||
func NewAssessmentAttemptResultSnapshot(
|
||||
attempt AssessmentAttempt,
|
||||
decision AssessmentAttemptDecision,
|
||||
summary string,
|
||||
limitations []string,
|
||||
) (AssessmentAttemptResultSnapshot, error) {
|
||||
const location = "domain.NewAssessmentAttemptResultSnapshot"
|
||||
snapshot := attempt.Snapshot()
|
||||
if attempt.IsZero() || snapshot.State != AssessmentAttemptStateCompleted || snapshot.EndedAt.IsZero() {
|
||||
return AssessmentAttemptResultSnapshot{}, fmt.Errorf("%s - completed attempt is required: %w", location, ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
result := AssessmentAttemptResultSnapshot{
|
||||
SchemaVersion: assessmentResultSchemaVersion, Attempt: attempt.PublicSnapshot(),
|
||||
Pins: assessmentResultPins(snapshot.Versions), Outcome: decision.Outcome,
|
||||
BasicScore: clonePointer(decision.Score), Rationale: decision.Rationale,
|
||||
Limitations: append([]string{}, limitations...), Summary: summary,
|
||||
DecidedAt: canonicalAssessmentTime(snapshot.EndedAt),
|
||||
}
|
||||
if err := ValidateAssessmentAttemptResultSnapshot(result); err != nil {
|
||||
return AssessmentAttemptResultSnapshot{}, fmt.Errorf("%s - validate result: %w", location, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func assessmentResultPins(versions AssessmentAttemptVersions) AssessmentAttemptResultPins {
|
||||
return AssessmentAttemptResultPins(versions)
|
||||
}
|
||||
|
||||
// RestoreAssessmentAttemptResultSnapshot detaches slices and validates a
|
||||
// stored result before it crosses the use-case boundary.
|
||||
func RestoreAssessmentAttemptResultSnapshot(
|
||||
result AssessmentAttemptResultSnapshot,
|
||||
) (AssessmentAttemptResultSnapshot, error) {
|
||||
public, err := RestoreAssessmentAttemptPublicSnapshot(result.Attempt)
|
||||
if err != nil {
|
||||
return AssessmentAttemptResultSnapshot{}, fmt.Errorf("domain.RestoreAssessmentAttemptResultSnapshot - restore public attempt: %w", err)
|
||||
}
|
||||
result.Attempt = public
|
||||
result.BasicScore = clonePointer(result.BasicScore)
|
||||
result.Limitations = append([]string{}, result.Limitations...)
|
||||
result.DecidedAt = canonicalAssessmentTime(result.DecidedAt)
|
||||
if err := ValidateAssessmentAttemptResultSnapshot(result); err != nil {
|
||||
return AssessmentAttemptResultSnapshot{}, err
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// ValidateAssessmentAttemptResultSnapshot checks stored pins, policy rationale,
|
||||
// and the reproducible basic score without loading a current policy.
|
||||
func ValidateAssessmentAttemptResultSnapshot(result AssessmentAttemptResultSnapshot) error {
|
||||
const location = "domain.ValidateAssessmentAttemptResultSnapshot"
|
||||
public, err := RestoreAssessmentAttemptPublicSnapshot(result.Attempt)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - public attempt projection is invalid: %w", location, ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
if !validAssessmentResultIdentity(result, public) {
|
||||
return fmt.Errorf("%s - result identity, versions, or timestamp are invalid: %w", location, ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
if !validAssessmentResultLimitations(result.Limitations) {
|
||||
return fmt.Errorf("%s - result limitations are not a bounded set: %w", location, ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
if err := validateAssessmentResultKind(result, public.Kind); err != nil {
|
||||
return fmt.Errorf("%s - result decision is invalid: %w", location, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validAssessmentResultIdentity(result AssessmentAttemptResultSnapshot, public AssessmentAttemptPublicSnapshot) bool {
|
||||
return result.SchemaVersion == assessmentResultSchemaVersion &&
|
||||
public.State == AssessmentAttemptStateCompleted && public.FinishedAt != nil &&
|
||||
!result.DecidedAt.IsZero() && public.FinishedAt.Equal(result.DecidedAt) &&
|
||||
result.Pins.ProductPolicyVersionID != PolicyVersionID(uuid.Nil) &&
|
||||
result.Pins.ProductPolicyVersion == public.PolicyVersion &&
|
||||
result.Pins.BankVersion == public.BankVersion && result.Pins.AlgorithmVersion == public.AlgorithmVersion &&
|
||||
assessmentVersionLabelPattern.MatchString(result.Pins.BankVersion) &&
|
||||
assessmentVersionLabelPattern.MatchString(result.Pins.AlgorithmVersion)
|
||||
}
|
||||
|
||||
func validAssessmentResultLimitations(limitations []string) bool {
|
||||
if limitations == nil || len(limitations) > 10 {
|
||||
return false
|
||||
}
|
||||
seen := make(map[string]struct{}, len(limitations))
|
||||
for _, limitation := range limitations {
|
||||
if limitation == "" || len(limitation) > 64 {
|
||||
return false
|
||||
}
|
||||
if _, exists := seen[limitation]; exists {
|
||||
return false
|
||||
}
|
||||
seen[limitation] = struct{}{}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func validateAssessmentResultKind(result AssessmentAttemptResultSnapshot, kind AssessmentAttemptKind) error {
|
||||
switch kind {
|
||||
case AssessmentAttemptKindRoot, AssessmentAttemptKindCorrective:
|
||||
return validateBasicAssessmentResult(result)
|
||||
case AssessmentAttemptKindDemoExpress:
|
||||
return validateTrainingAssessmentResult(result)
|
||||
default:
|
||||
return fmt.Errorf("domain.validateAssessmentResultKind - result kind is invalid: %w", ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
}
|
||||
|
||||
func validateBasicAssessmentResult(result AssessmentAttemptResultSnapshot) error {
|
||||
if !validBasicResultPins(result.Pins) || !validBasicResultContent(result) {
|
||||
return ErrInvalidAssessmentAttempt
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validBasicResultPins(pins AssessmentAttemptResultPins) bool {
|
||||
return pins.GradingPolicyVersionID != PolicyVersionID(uuid.Nil) && pins.OpeningID != uuid.Nil &&
|
||||
pins.OpeningManifestHash != [32]byte{} && pins.TrainingBindingID == uuid.Nil && pins.TrainingManifestHash == [32]byte{}
|
||||
}
|
||||
|
||||
func validBasicResultContent(result AssessmentAttemptResultSnapshot) bool {
|
||||
if result.Attempt.Mode != AssessmentAttemptModeDemoBasic ||
|
||||
result.Outcome != AssessmentAttemptOutcomeConfirmed && result.Outcome != AssessmentAttemptOutcomeNotConfirmed ||
|
||||
result.BasicScore == nil || result.NotDeterminedReason != "" || result.Summary != "" ||
|
||||
result.Rationale.Rule != assessmentResultRuleBasicPassMark ||
|
||||
result.Rationale.PassMarkBasisPoints < 1 || result.Rationale.PassMarkBasisPoints > int32(basisPointsPerUnit) {
|
||||
return false
|
||||
}
|
||||
return result.Rationale.ScoredItems >= 1 && result.Rationale.ScoredItems <= result.Attempt.MaxItems &&
|
||||
result.Rationale.ScoredItems == result.BasicScore.MaxPoints &&
|
||||
result.Rationale.PassPoints == result.BasicScore.PassPoints &&
|
||||
validStoredBasicDecision(result.Outcome, *result.BasicScore, result.Rationale)
|
||||
}
|
||||
|
||||
func validateTrainingAssessmentResult(result AssessmentAttemptResultSnapshot) error {
|
||||
if result.Attempt.Mode != AssessmentAttemptModeDemoExpress || !validTrainingResultPins(result.Pins) ||
|
||||
result.Outcome != AssessmentAttemptOutcomeDemonstration || result.BasicScore != nil ||
|
||||
result.NotDeterminedReason != "" || result.Summary == "" ||
|
||||
result.Rationale != (AssessmentAttemptDecisionRationale{Rule: assessmentResultRuleTrainingOnly}) {
|
||||
return ErrInvalidAssessmentAttempt
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validTrainingResultPins(pins AssessmentAttemptResultPins) bool {
|
||||
return pins.GradingPolicyVersionID == PolicyVersionID(uuid.Nil) && pins.OpeningID == uuid.Nil &&
|
||||
pins.OpeningManifestHash == [32]byte{} && pins.TrainingBindingID != uuid.Nil && pins.TrainingManifestHash != [32]byte{}
|
||||
}
|
||||
|
||||
func validStoredBasicDecision(
|
||||
outcome AssessmentAttemptOutcome,
|
||||
score AssessmentBasicScore,
|
||||
rationale AssessmentAttemptDecisionRationale,
|
||||
) bool {
|
||||
if score.MaxPoints < 1 || score.Points < 0 || score.Points > score.MaxPoints ||
|
||||
score.PassPoints < 1 || score.PassPoints > score.MaxPoints {
|
||||
return false
|
||||
}
|
||||
passPoints := (int64(rationale.ScoredItems)*int64(rationale.PassMarkBasisPoints) + int64(basisPointsPerUnit) - 1) / int64(basisPointsPerUnit)
|
||||
if passPoints != int64(score.PassPoints) || int64(rationale.PassPoints) != passPoints {
|
||||
return false
|
||||
}
|
||||
wantOutcome := AssessmentAttemptOutcomeNotConfirmed
|
||||
if score.Points >= score.PassPoints {
|
||||
wantOutcome = AssessmentAttemptOutcomeConfirmed
|
||||
}
|
||||
return outcome == wantOutcome
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var ErrInvalidAssessmentSignal = errors.New("invalid assessment signal")
|
||||
|
||||
const (
|
||||
maxAssessmentSignalEvents = 50
|
||||
maxAssessmentSignalDurationMS = int32(259200000)
|
||||
maxAssessmentSignalSizeBytes = int32(math.MaxInt32)
|
||||
maxAssessmentSignalReceiptSize = int32(50)
|
||||
)
|
||||
|
||||
type AssessmentSignalKind string
|
||||
|
||||
const (
|
||||
AssessmentSignalFocusLoss AssessmentSignalKind = "focus_loss"
|
||||
AssessmentSignalCopy AssessmentSignalKind = "copy"
|
||||
AssessmentSignalPaste AssessmentSignalKind = "paste"
|
||||
AssessmentSignalCut AssessmentSignalKind = "cut"
|
||||
AssessmentSignalFullscreenExit AssessmentSignalKind = "fullscreen_exit"
|
||||
)
|
||||
|
||||
func (kind AssessmentSignalKind) IsKnown() bool {
|
||||
switch kind {
|
||||
case AssessmentSignalFocusLoss, AssessmentSignalCopy, AssessmentSignalPaste,
|
||||
AssessmentSignalCut, AssessmentSignalFullscreenExit:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
type AssessmentSignalEventInput struct {
|
||||
Kind AssessmentSignalKind
|
||||
ItemInstanceID uuid.UUID
|
||||
OccurredAt time.Time
|
||||
DurationMS *int32
|
||||
SizeBytes *int32
|
||||
}
|
||||
|
||||
type AssessmentSignalEvent struct {
|
||||
kind AssessmentSignalKind
|
||||
itemInstanceID uuid.UUID
|
||||
occurredAt time.Time
|
||||
durationMS int32
|
||||
hasDuration bool
|
||||
sizeBytes int32
|
||||
hasSize bool
|
||||
}
|
||||
|
||||
func NewAssessmentSignalEvent(input AssessmentSignalEventInput) (AssessmentSignalEvent, error) {
|
||||
const location = "domain.NewAssessmentSignalEvent"
|
||||
if input.ItemInstanceID == uuid.Nil || !input.Kind.IsKnown() {
|
||||
return AssessmentSignalEvent{}, fmt.Errorf("%s - event kind and item instance are required: %w", location, ErrInvalidAssessmentSignal)
|
||||
}
|
||||
occurredAt, err := canonicalAssessmentSignalTime(input.OccurredAt)
|
||||
if err != nil {
|
||||
return AssessmentSignalEvent{}, fmt.Errorf("%s - client timestamp is invalid: %w", location, err)
|
||||
}
|
||||
return newAssessmentSignalEvent(input, occurredAt)
|
||||
}
|
||||
|
||||
func newAssessmentSignalEvent(input AssessmentSignalEventInput, occurredAt time.Time) (AssessmentSignalEvent, error) {
|
||||
switch input.Kind {
|
||||
case AssessmentSignalFocusLoss:
|
||||
return assessmentFocusLossEvent(input, occurredAt)
|
||||
case AssessmentSignalCopy, AssessmentSignalPaste, AssessmentSignalCut:
|
||||
return assessmentClipboardEvent(input, occurredAt)
|
||||
case AssessmentSignalFullscreenExit:
|
||||
return assessmentFullscreenExitEvent(input, occurredAt)
|
||||
default:
|
||||
return AssessmentSignalEvent{}, fmt.Errorf("domain.NewAssessmentSignalEvent - event kind is unknown: %w", ErrInvalidAssessmentSignal)
|
||||
}
|
||||
}
|
||||
|
||||
func assessmentFocusLossEvent(input AssessmentSignalEventInput, occurredAt time.Time) (AssessmentSignalEvent, error) {
|
||||
if input.DurationMS == nil || *input.DurationMS < 1 || *input.DurationMS > maxAssessmentSignalDurationMS || input.SizeBytes != nil {
|
||||
return AssessmentSignalEvent{}, fmt.Errorf("domain.NewAssessmentSignalEvent - focus loss requires a bounded duration only: %w", ErrInvalidAssessmentSignal)
|
||||
}
|
||||
return AssessmentSignalEvent{
|
||||
kind: input.Kind, itemInstanceID: input.ItemInstanceID, occurredAt: occurredAt,
|
||||
durationMS: *input.DurationMS, hasDuration: true,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func assessmentClipboardEvent(input AssessmentSignalEventInput, occurredAt time.Time) (AssessmentSignalEvent, error) {
|
||||
if input.SizeBytes == nil || *input.SizeBytes < 0 || *input.SizeBytes > maxAssessmentSignalSizeBytes || input.DurationMS != nil {
|
||||
return AssessmentSignalEvent{}, fmt.Errorf("domain.NewAssessmentSignalEvent - clipboard signal requires a byte count only: %w", ErrInvalidAssessmentSignal)
|
||||
}
|
||||
return AssessmentSignalEvent{
|
||||
kind: input.Kind, itemInstanceID: input.ItemInstanceID, occurredAt: occurredAt,
|
||||
sizeBytes: *input.SizeBytes, hasSize: true,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func assessmentFullscreenExitEvent(input AssessmentSignalEventInput, occurredAt time.Time) (AssessmentSignalEvent, error) {
|
||||
if input.DurationMS != nil || input.SizeBytes != nil {
|
||||
return AssessmentSignalEvent{}, fmt.Errorf("domain.NewAssessmentSignalEvent - fullscreen exit has no measurements: %w", ErrInvalidAssessmentSignal)
|
||||
}
|
||||
return AssessmentSignalEvent{kind: input.Kind, itemInstanceID: input.ItemInstanceID, occurredAt: occurredAt}, nil
|
||||
}
|
||||
|
||||
func (event AssessmentSignalEvent) Kind() AssessmentSignalKind { return event.kind }
|
||||
func (event AssessmentSignalEvent) ItemInstanceID() uuid.UUID { return event.itemInstanceID }
|
||||
func (event AssessmentSignalEvent) OccurredAt() time.Time { return event.occurredAt }
|
||||
func (event AssessmentSignalEvent) DurationMS() (int32, bool) {
|
||||
return event.durationMS, event.hasDuration
|
||||
}
|
||||
func (event AssessmentSignalEvent) SizeBytes() (int32, bool) { return event.sizeBytes, event.hasSize }
|
||||
|
||||
type AssessmentSignalBatch struct {
|
||||
id uuid.UUID
|
||||
attemptID AssessmentAttemptID
|
||||
receivedAt time.Time
|
||||
events []AssessmentSignalEvent
|
||||
}
|
||||
|
||||
func NewAssessmentSignalBatch(
|
||||
id uuid.UUID,
|
||||
attemptID AssessmentAttemptID,
|
||||
receivedAt time.Time,
|
||||
events []AssessmentSignalEvent,
|
||||
) (AssessmentSignalBatch, error) {
|
||||
const location = "domain.NewAssessmentSignalBatch"
|
||||
if id == uuid.Nil || attemptID.IsZero() || len(events) == 0 || len(events) > maxAssessmentSignalEvents {
|
||||
return AssessmentSignalBatch{}, fmt.Errorf("%s - batch identifiers and 1 to %d events are required: %w", location, maxAssessmentSignalEvents, ErrInvalidAssessmentSignal)
|
||||
}
|
||||
canonical, err := canonicalAssessmentSignalTime(receivedAt)
|
||||
if err != nil {
|
||||
return AssessmentSignalBatch{}, fmt.Errorf("%s - server receipt time is invalid: %w", location, err)
|
||||
}
|
||||
if err := validateAssessmentSignalBatchEvents(events); err != nil {
|
||||
return AssessmentSignalBatch{}, fmt.Errorf("%s - an event is invalid: %w", location, err)
|
||||
}
|
||||
return AssessmentSignalBatch{id: id, attemptID: attemptID, receivedAt: canonical, events: slices.Clone(events)}, nil
|
||||
}
|
||||
|
||||
func validateAssessmentSignalBatchEvents(events []AssessmentSignalEvent) error {
|
||||
for _, event := range events {
|
||||
if err := validateAssessmentSignalBatchEvent(event); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateAssessmentSignalBatchEvent(event AssessmentSignalEvent) error {
|
||||
if event.itemInstanceID == uuid.Nil || !event.kind.IsKnown() || event.occurredAt.IsZero() {
|
||||
return ErrInvalidAssessmentSignal
|
||||
}
|
||||
switch event.kind {
|
||||
case AssessmentSignalFocusLoss:
|
||||
return validateAssessmentSignalFocusLoss(event)
|
||||
case AssessmentSignalCopy, AssessmentSignalPaste, AssessmentSignalCut:
|
||||
return validateAssessmentSignalClipboard(event)
|
||||
case AssessmentSignalFullscreenExit:
|
||||
return validateAssessmentSignalFullscreenExit(event)
|
||||
default:
|
||||
return ErrInvalidAssessmentSignal
|
||||
}
|
||||
}
|
||||
|
||||
func validateAssessmentSignalFocusLoss(event AssessmentSignalEvent) error {
|
||||
if !event.hasDuration || event.durationMS < 1 || event.durationMS > maxAssessmentSignalDurationMS || event.hasSize {
|
||||
return ErrInvalidAssessmentSignal
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateAssessmentSignalClipboard(event AssessmentSignalEvent) error {
|
||||
if !event.hasSize || event.sizeBytes < 0 || event.hasDuration {
|
||||
return ErrInvalidAssessmentSignal
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateAssessmentSignalFullscreenExit(event AssessmentSignalEvent) error {
|
||||
if event.hasDuration || event.hasSize {
|
||||
return ErrInvalidAssessmentSignal
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (batch AssessmentSignalBatch) ID() uuid.UUID { return batch.id }
|
||||
func (batch AssessmentSignalBatch) AttemptID() AssessmentAttemptID { return batch.attemptID }
|
||||
func (batch AssessmentSignalBatch) ReceivedAt() time.Time { return batch.receivedAt }
|
||||
func (batch AssessmentSignalBatch) Events() []AssessmentSignalEvent {
|
||||
return slices.Clone(batch.events)
|
||||
}
|
||||
|
||||
type AssessmentSignalReceiptStatus string
|
||||
|
||||
const (
|
||||
AssessmentSignalReceiptAccepted AssessmentSignalReceiptStatus = "accepted"
|
||||
AssessmentSignalReceiptSaturated AssessmentSignalReceiptStatus = "saturated"
|
||||
)
|
||||
|
||||
type AssessmentSignalReceipt struct {
|
||||
status AssessmentSignalReceiptStatus
|
||||
acceptedEvents int32
|
||||
receivedAt time.Time
|
||||
}
|
||||
|
||||
func NewAssessmentSignalReceipt(
|
||||
status AssessmentSignalReceiptStatus,
|
||||
acceptedEvents int32,
|
||||
receivedAt time.Time,
|
||||
) (AssessmentSignalReceipt, error) {
|
||||
const location = "domain.NewAssessmentSignalReceipt"
|
||||
canonical, err := canonicalAssessmentSignalTime(receivedAt)
|
||||
if err != nil {
|
||||
return AssessmentSignalReceipt{}, fmt.Errorf("%s - receipt time is invalid: %w", location, err)
|
||||
}
|
||||
switch status {
|
||||
case AssessmentSignalReceiptAccepted:
|
||||
if acceptedEvents < 1 || acceptedEvents > maxAssessmentSignalReceiptSize {
|
||||
return AssessmentSignalReceipt{}, fmt.Errorf("%s - accepted event count is outside the batch bound: %w", location, ErrInvalidAssessmentSignal)
|
||||
}
|
||||
case AssessmentSignalReceiptSaturated:
|
||||
if acceptedEvents != 0 {
|
||||
return AssessmentSignalReceipt{}, fmt.Errorf("%s - a saturated receipt accepts no events: %w", location, ErrInvalidAssessmentSignal)
|
||||
}
|
||||
default:
|
||||
return AssessmentSignalReceipt{}, fmt.Errorf("%s - receipt status is unknown: %w", location, ErrInvalidAssessmentSignal)
|
||||
}
|
||||
return AssessmentSignalReceipt{status: status, acceptedEvents: acceptedEvents, receivedAt: canonical}, nil
|
||||
}
|
||||
|
||||
func (receipt AssessmentSignalReceipt) Status() AssessmentSignalReceiptStatus { return receipt.status }
|
||||
func (receipt AssessmentSignalReceipt) AcceptedEvents() int32 { return receipt.acceptedEvents }
|
||||
func (receipt AssessmentSignalReceipt) ReceivedAt() time.Time { return receipt.receivedAt }
|
||||
|
||||
func canonicalAssessmentSignalTime(value time.Time) (time.Time, error) {
|
||||
canonical := value.UTC().Truncate(time.Microsecond)
|
||||
if value.IsZero() || canonical.Year() < 1 || canonical.Year() > 9999 {
|
||||
return time.Time{}, ErrInvalidAssessmentSignal
|
||||
}
|
||||
return canonical, nil
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package domain_test
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
)
|
||||
|
||||
func TestAssessmentSignalEventValidatesAllowlistedMeasurements(t *testing.T) {
|
||||
itemID := uuid.New()
|
||||
clientTime := time.Date(2026, time.October, 7, 12, 30, 0, 123456789, time.FixedZone("test", 3*60*60))
|
||||
duration := int32(2500)
|
||||
size := int32(4096)
|
||||
tests := []struct {
|
||||
name string
|
||||
input domain.AssessmentSignalEventInput
|
||||
kind domain.AssessmentSignalKind
|
||||
}{
|
||||
{name: "focus loss", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalFocusLoss, ItemInstanceID: itemID, OccurredAt: clientTime, DurationMS: &duration}, kind: domain.AssessmentSignalFocusLoss},
|
||||
{name: "copy", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalCopy, ItemInstanceID: itemID, OccurredAt: clientTime, SizeBytes: &size}, kind: domain.AssessmentSignalCopy},
|
||||
{name: "paste", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalPaste, ItemInstanceID: itemID, OccurredAt: clientTime, SizeBytes: &size}, kind: domain.AssessmentSignalPaste},
|
||||
{name: "cut", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalCut, ItemInstanceID: itemID, OccurredAt: clientTime, SizeBytes: &size}, kind: domain.AssessmentSignalCut},
|
||||
{name: "fullscreen exit", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalFullscreenExit, ItemInstanceID: itemID, OccurredAt: clientTime}, kind: domain.AssessmentSignalFullscreenExit},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
event, err := domain.NewAssessmentSignalEvent(test.input)
|
||||
if err != nil {
|
||||
t.Fatalf("NewAssessmentSignalEvent() error = %v", err)
|
||||
}
|
||||
if event.Kind() != test.kind || event.ItemInstanceID() != itemID {
|
||||
t.Fatalf("event identity = %s/%s", event.Kind(), event.ItemInstanceID())
|
||||
}
|
||||
if got := event.OccurredAt(); !got.Equal(time.Date(2026, time.October, 7, 9, 30, 0, 123456000, time.UTC)) || got.Location() != time.UTC {
|
||||
t.Fatalf("canonical event time = %s, want UTC microsecond timestamp", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAssessmentSignalEventRejectsMismatchedOrUnboundedMeasurements(t *testing.T) {
|
||||
itemID := uuid.New()
|
||||
validTime := time.Date(2026, time.October, 7, 12, 0, 0, 0, time.UTC)
|
||||
zero := int32(0)
|
||||
tooLong := int32(259200001)
|
||||
size := int32(1)
|
||||
unknown := domain.AssessmentSignalKind("answer_text")
|
||||
tests := []struct {
|
||||
name string
|
||||
input domain.AssessmentSignalEventInput
|
||||
}{
|
||||
{name: "unknown kind", input: domain.AssessmentSignalEventInput{Kind: unknown, ItemInstanceID: itemID, OccurredAt: validTime}},
|
||||
{name: "missing item", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalFullscreenExit, OccurredAt: validTime}},
|
||||
{name: "missing timestamp", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalFullscreenExit, ItemInstanceID: itemID}},
|
||||
{name: "zero focus duration", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalFocusLoss, ItemInstanceID: itemID, OccurredAt: validTime, DurationMS: &zero}},
|
||||
{name: "oversized focus duration", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalFocusLoss, ItemInstanceID: itemID, OccurredAt: validTime, DurationMS: &tooLong}},
|
||||
{name: "clipboard without size", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalPaste, ItemInstanceID: itemID, OccurredAt: validTime}},
|
||||
{name: "negative clipboard size", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalCopy, ItemInstanceID: itemID, OccurredAt: validTime, SizeBytes: func() *int32 { value := int32(-1); return &value }()}},
|
||||
{name: "focus with clipboard size", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalFocusLoss, ItemInstanceID: itemID, OccurredAt: validTime, DurationMS: &size, SizeBytes: &size}},
|
||||
{name: "fullscreen with measurement", input: domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalFullscreenExit, ItemInstanceID: itemID, OccurredAt: validTime, SizeBytes: &size}},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
if _, err := domain.NewAssessmentSignalEvent(test.input); !errors.Is(err, domain.ErrInvalidAssessmentSignal) {
|
||||
t.Fatalf("NewAssessmentSignalEvent() error = %v, want ErrInvalidAssessmentSignal", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAssessmentSignalBatchAndReceiptEnforceBounds(t *testing.T) {
|
||||
attemptID := domain.AssessmentAttemptID(uuid.New())
|
||||
itemID := uuid.New()
|
||||
at := time.Date(2026, time.October, 7, 12, 0, 0, 0, time.UTC)
|
||||
input := domain.AssessmentSignalEventInput{Kind: domain.AssessmentSignalFullscreenExit, ItemInstanceID: itemID, OccurredAt: at}
|
||||
event, err := domain.NewAssessmentSignalEvent(input)
|
||||
if err != nil {
|
||||
t.Fatalf("NewAssessmentSignalEvent() error = %v", err)
|
||||
}
|
||||
if _, err := domain.NewAssessmentSignalBatch(uuid.New(), attemptID, at, nil); !errors.Is(err, domain.ErrInvalidAssessmentSignal) {
|
||||
t.Fatalf("empty NewAssessmentSignalBatch() error = %v", err)
|
||||
}
|
||||
tooMany := make([]domain.AssessmentSignalEvent, 51)
|
||||
for index := range tooMany {
|
||||
tooMany[index] = event
|
||||
}
|
||||
if _, err := domain.NewAssessmentSignalBatch(uuid.New(), attemptID, at, tooMany); !errors.Is(err, domain.ErrInvalidAssessmentSignal) {
|
||||
t.Fatalf("oversized NewAssessmentSignalBatch() error = %v", err)
|
||||
}
|
||||
batch, err := domain.NewAssessmentSignalBatch(uuid.New(), attemptID, at, []domain.AssessmentSignalEvent{event})
|
||||
if err != nil || len(batch.Events()) != 1 {
|
||||
t.Fatalf("valid NewAssessmentSignalBatch() = %d events, error %v", len(batch.Events()), err)
|
||||
}
|
||||
for _, test := range []struct {
|
||||
status domain.AssessmentSignalReceiptStatus
|
||||
count int32
|
||||
want bool
|
||||
}{
|
||||
{status: domain.AssessmentSignalReceiptAccepted, count: 1, want: true},
|
||||
{status: domain.AssessmentSignalReceiptAccepted, count: 0},
|
||||
{status: domain.AssessmentSignalReceiptSaturated, count: 0, want: true},
|
||||
{status: domain.AssessmentSignalReceiptSaturated, count: 1},
|
||||
} {
|
||||
_, err := domain.NewAssessmentSignalReceipt(test.status, test.count, at)
|
||||
if (err == nil) != test.want {
|
||||
t.Errorf("NewAssessmentSignalReceipt(%s, %d) error = %v, want valid %v", test.status, test.count, err, test.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var ErrInvalidCandidateCardAccess = errors.New("invalid candidate card access")
|
||||
|
||||
// CandidateCardAccessKind describes an employer read protected by the current
|
||||
// publication and grant policy.
|
||||
type CandidateCardAccessKind string
|
||||
|
||||
const (
|
||||
CandidateCardAccessCardViewed CandidateCardAccessKind = "card_viewed"
|
||||
CandidateCardAccessContactRead CandidateCardAccessKind = "contact_read"
|
||||
)
|
||||
|
||||
// CandidateCardAccessInput contains identifiers and field codes only. It
|
||||
// never stores the content that was read or a search query.
|
||||
type CandidateCardAccessInput struct {
|
||||
CandidateID uuid.UUID
|
||||
OrganizationID uuid.UUID
|
||||
ActorID uuid.UUID
|
||||
Kind CandidateCardAccessKind
|
||||
ProjectionFields []CardField
|
||||
ContactFields []ContactField
|
||||
OccurredAt time.Time
|
||||
}
|
||||
|
||||
// CandidateCardAccess is one immutable audit record for a permitted read.
|
||||
type CandidateCardAccess struct {
|
||||
id uuid.UUID
|
||||
candidateID uuid.UUID
|
||||
organizationID uuid.UUID
|
||||
actorID uuid.UUID
|
||||
kind CandidateCardAccessKind
|
||||
fieldCodes []string
|
||||
occurredAt time.Time
|
||||
}
|
||||
|
||||
// NewCandidateCardAccess builds an immutable event for one permitted read.
|
||||
func NewCandidateCardAccess(input CandidateCardAccessInput) (CandidateCardAccess, error) {
|
||||
const location = "domain.NewCandidateCardAccess"
|
||||
if input.CandidateID == uuid.Nil || input.OrganizationID == uuid.Nil || input.ActorID == uuid.Nil || input.OccurredAt.IsZero() {
|
||||
return CandidateCardAccess{}, fmt.Errorf("%s - identities and time are required: %w", location, ErrInvalidCandidateCardAccess)
|
||||
}
|
||||
input.OccurredAt = input.OccurredAt.UTC().Truncate(time.Microsecond)
|
||||
if err := validateCandidateCardAccessFields(input, true); err != nil {
|
||||
return CandidateCardAccess{}, fmt.Errorf("%s - validate field codes: %w", location, err)
|
||||
}
|
||||
id, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
return CandidateCardAccess{}, fmt.Errorf("%s - generate identifier: %w", location, err)
|
||||
}
|
||||
return CandidateCardAccess{
|
||||
id: id, candidateID: input.CandidateID, organizationID: input.OrganizationID,
|
||||
actorID: input.ActorID, kind: input.Kind, fieldCodes: candidateCardAccessFieldCodes(input),
|
||||
occurredAt: input.OccurredAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// RestoreCandidateCardAccess validates an immutable audit record loaded from
|
||||
// storage.
|
||||
func RestoreCandidateCardAccess(id uuid.UUID, input CandidateCardAccessInput) (CandidateCardAccess, error) {
|
||||
const location = "domain.RestoreCandidateCardAccess"
|
||||
if id == uuid.Nil {
|
||||
return CandidateCardAccess{}, fmt.Errorf("%s - identifier is required: %w", location, ErrInvalidCandidateCardAccess)
|
||||
}
|
||||
if err := validateCandidateCardAccessFields(input, false); err != nil {
|
||||
return CandidateCardAccess{}, fmt.Errorf("%s - validate field codes: %w", location, err)
|
||||
}
|
||||
if input.CandidateID == uuid.Nil || input.OrganizationID == uuid.Nil || input.OccurredAt.IsZero() {
|
||||
return CandidateCardAccess{}, fmt.Errorf("%s - identities and time are required: %w", location, ErrInvalidCandidateCardAccess)
|
||||
}
|
||||
return CandidateCardAccess{
|
||||
id: id, candidateID: input.CandidateID, organizationID: input.OrganizationID,
|
||||
actorID: input.ActorID, kind: input.Kind, fieldCodes: candidateCardAccessFieldCodes(input),
|
||||
occurredAt: input.OccurredAt.UTC().Truncate(time.Microsecond),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func validateCandidateCardAccessFields(input CandidateCardAccessInput, requireActor bool) error {
|
||||
if requireActor && input.ActorID == uuid.Nil {
|
||||
return ErrInvalidCandidateCardAccess
|
||||
}
|
||||
switch input.Kind {
|
||||
case CandidateCardAccessCardViewed:
|
||||
if len(input.ContactFields) != 0 || len(input.ProjectionFields) > 6 {
|
||||
return ErrInvalidCandidateCardAccess
|
||||
}
|
||||
seen := make(map[CardField]struct{}, len(input.ProjectionFields))
|
||||
for _, field := range input.ProjectionFields {
|
||||
if !candidateCardProjectionField(field) {
|
||||
return ErrInvalidCandidateCardAccess
|
||||
}
|
||||
if _, exists := seen[field]; exists {
|
||||
return ErrInvalidCandidateCardAccess
|
||||
}
|
||||
seen[field] = struct{}{}
|
||||
}
|
||||
case CandidateCardAccessContactRead:
|
||||
if len(input.ProjectionFields) != 0 || len(input.ContactFields) == 0 {
|
||||
return ErrInvalidCandidateCardAccess
|
||||
}
|
||||
if _, err := NewContactFieldSet(input.ContactFields...); err != nil {
|
||||
return ErrInvalidCandidateCardAccess
|
||||
}
|
||||
default:
|
||||
return ErrInvalidCandidateCardAccess
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func candidateCardProjectionField(field CardField) bool {
|
||||
switch field {
|
||||
case CardFieldCategories, CardFieldStack, CardFieldExperience, CardFieldSelfAssessment,
|
||||
CardFieldWorkFormats, CardFieldSalaryCompatibility:
|
||||
return true
|
||||
case CardFieldSoftSkills, CardFieldLocation, CardFieldRelocation:
|
||||
return false
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func candidateCardAccessFieldCodes(input CandidateCardAccessInput) []string {
|
||||
codes := make([]string, 0, len(input.ProjectionFields)+len(input.ContactFields))
|
||||
if input.Kind == CandidateCardAccessCardViewed {
|
||||
for _, field := range input.ProjectionFields {
|
||||
codes = append(codes, string(field))
|
||||
}
|
||||
} else {
|
||||
for _, field := range input.ContactFields {
|
||||
codes = append(codes, string(field))
|
||||
}
|
||||
}
|
||||
slices.Sort(codes)
|
||||
return codes
|
||||
}
|
||||
|
||||
func (access CandidateCardAccess) ID() uuid.UUID { return access.id }
|
||||
func (access CandidateCardAccess) CandidateID() uuid.UUID { return access.candidateID }
|
||||
func (access CandidateCardAccess) OrganizationID() uuid.UUID { return access.organizationID }
|
||||
func (access CandidateCardAccess) ActorID() uuid.UUID { return access.actorID }
|
||||
func (access CandidateCardAccess) Kind() CandidateCardAccessKind { return access.kind }
|
||||
func (access CandidateCardAccess) FieldCodes() []string { return slices.Clone(access.fieldCodes) }
|
||||
func (access CandidateCardAccess) OccurredAt() time.Time { return access.occurredAt }
|
||||
|
||||
func (access CandidateCardAccess) IsZero() bool {
|
||||
return access.id == uuid.Nil || access.candidateID == uuid.Nil || access.organizationID == uuid.Nil
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"slices"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestCandidateCardAccessStoresOnlyCanonicalAllowedFieldCodes(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
now := time.Date(2026, 10, 7, 12, 0, 0, 123456789, time.FixedZone("test", 3*60*60))
|
||||
access, err := NewCandidateCardAccess(CandidateCardAccessInput{
|
||||
CandidateID: uuid.New(), OrganizationID: uuid.New(), ActorID: uuid.New(),
|
||||
Kind: CandidateCardAccessCardViewed,
|
||||
ProjectionFields: []CardField{CardFieldWorkFormats, CardFieldCategories, CardFieldStack},
|
||||
OccurredAt: now,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewCandidateCardAccess() error = %v", err)
|
||||
}
|
||||
if access.IsZero() || access.Kind() != CandidateCardAccessCardViewed ||
|
||||
!access.OccurredAt().Equal(now.UTC().Truncate(time.Microsecond)) {
|
||||
t.Fatalf("restored access = %#v", access)
|
||||
}
|
||||
if got := access.FieldCodes(); !slices.Equal(got, []string{"categories", "stack", "work_formats"}) {
|
||||
t.Fatalf("FieldCodes() = %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCandidateCardAccessRejectsPrivateOrMismatchedFields(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
base := CandidateCardAccessInput{
|
||||
CandidateID: uuid.New(), OrganizationID: uuid.New(), ActorID: uuid.New(),
|
||||
Kind: CandidateCardAccessCardViewed, ProjectionFields: []CardField{CardFieldStack},
|
||||
OccurredAt: time.Now(),
|
||||
}
|
||||
cases := map[string]func(*CandidateCardAccessInput){
|
||||
"free-text location": func(input *CandidateCardAccessInput) { input.ProjectionFields = []CardField{CardFieldLocation} },
|
||||
"duplicate field": func(input *CandidateCardAccessInput) {
|
||||
input.ProjectionFields = []CardField{CardFieldStack, CardFieldStack}
|
||||
},
|
||||
"mixed contact field": func(input *CandidateCardAccessInput) {
|
||||
input.ContactFields = []ContactField{ContactFieldEmail}
|
||||
},
|
||||
"empty contact read": func(input *CandidateCardAccessInput) {
|
||||
input.Kind = CandidateCardAccessContactRead
|
||||
input.ProjectionFields = nil
|
||||
input.ContactFields = nil
|
||||
},
|
||||
"unknown kind": func(input *CandidateCardAccessInput) { input.Kind = "workflow_accepted" },
|
||||
}
|
||||
for name, mutate := range cases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
input := base
|
||||
mutate(&input)
|
||||
if _, err := NewCandidateCardAccess(input); !errors.Is(err, ErrInvalidCandidateCardAccess) {
|
||||
t.Fatalf("NewCandidateCardAccess() error = %v, want ErrInvalidCandidateCardAccess", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCandidateCardAccessAllowsPseudonymOnlyReadAndActorlessRestore(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
input := CandidateCardAccessInput{
|
||||
CandidateID: uuid.New(), OrganizationID: uuid.New(), ActorID: uuid.New(),
|
||||
Kind: CandidateCardAccessCardViewed, OccurredAt: time.Now(),
|
||||
}
|
||||
access, err := NewCandidateCardAccess(input)
|
||||
if err != nil {
|
||||
t.Fatalf("NewCandidateCardAccess(pseudonym only) error = %v", err)
|
||||
}
|
||||
if got := access.FieldCodes(); len(got) != 0 {
|
||||
t.Fatalf("pseudonym-only field codes = %v, want empty", got)
|
||||
}
|
||||
|
||||
input.ActorID = uuid.Nil
|
||||
restored, err := RestoreCandidateCardAccess(access.ID(), input)
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreCandidateCardAccess(actor anonymized) error = %v", err)
|
||||
}
|
||||
if restored.ActorID() != uuid.Nil || restored.ID() != access.ID() {
|
||||
t.Fatalf("restored actor/id = %s/%s, want nil/%s", restored.ActorID(), restored.ID(), access.ID())
|
||||
}
|
||||
}
|
||||
|
||||
func TestCandidateCardAccessContactReadUsesClosedContactFieldSet(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
access, err := NewCandidateCardAccess(CandidateCardAccessInput{
|
||||
CandidateID: uuid.New(), OrganizationID: uuid.New(), ActorID: uuid.New(),
|
||||
Kind: CandidateCardAccessContactRead,
|
||||
ContactFields: []ContactField{ContactFieldPhone, ContactFieldEmail},
|
||||
OccurredAt: time.Now(),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewCandidateCardAccess() error = %v", err)
|
||||
}
|
||||
if got := access.FieldCodes(); !slices.Equal(got, []string{"email", "phone"}) {
|
||||
t.Fatalf("FieldCodes() = %v", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,717 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"golang.org/x/text/unicode/norm"
|
||||
)
|
||||
|
||||
var ErrInvalidAnonymousCandidateView = errors.New("invalid anonymous candidate view")
|
||||
|
||||
const (
|
||||
minimumAnonymousCandidateCohort = 5
|
||||
maximumCandidateViewGeneralization = 5
|
||||
maximumCandidateViewSpecializations = 9
|
||||
maximumCandidateViewWorkFormats = 3
|
||||
candidateViewPseudonymPrefix = "cv1_"
|
||||
minimumCandidateViewPseudonymKeyLen = 32
|
||||
)
|
||||
|
||||
const candidateViewPseudonymPurpose = "lincodex/anonymous-candidate-view/v1\x00"
|
||||
const candidatePreviewPseudonymPurpose = "lincodex/anonymous-candidate-preview/v1\x00"
|
||||
|
||||
// CandidateViewPseudonymKey is a dedicated secret for organization-scoped
|
||||
// candidate aliases. It must not be reused for another HMAC purpose.
|
||||
type CandidateViewPseudonymKey struct {
|
||||
secret []byte
|
||||
}
|
||||
|
||||
func NewCandidateViewPseudonymKey(secret []byte) (CandidateViewPseudonymKey, error) {
|
||||
if len(secret) < minimumCandidateViewPseudonymKeyLen {
|
||||
return CandidateViewPseudonymKey{}, ErrInvalidAnonymousCandidateView
|
||||
}
|
||||
return CandidateViewPseudonymKey{secret: slices.Clone(secret)}, nil
|
||||
}
|
||||
|
||||
func (CandidateViewPseudonymKey) String() string { return "[candidate view pseudonym key]" }
|
||||
func (CandidateViewPseudonymKey) GoString() string { return "[candidate view pseudonym key]" }
|
||||
func (CandidateViewPseudonymKey) LogValue() slog.Value {
|
||||
return slog.StringValue("[candidate view pseudonym key]")
|
||||
}
|
||||
|
||||
// ForOrganization derives a stable pseudonym for one candidate in one
|
||||
// organization. Fixed-width UUID bytes and a purpose label make the HMAC
|
||||
// input unambiguous and separate it from other keyed identifiers.
|
||||
func (key CandidateViewPseudonymKey) ForOrganization(organizationID, candidateID uuid.UUID) (string, error) {
|
||||
if len(key.secret) < minimumCandidateViewPseudonymKeyLen || organizationID == uuid.Nil || candidateID == uuid.Nil {
|
||||
return "", ErrInvalidAnonymousCandidateView
|
||||
}
|
||||
mac := hmac.New(sha256.New, key.secret)
|
||||
_, _ = mac.Write([]byte(candidateViewPseudonymPurpose))
|
||||
_, _ = mac.Write(organizationID[:])
|
||||
_, _ = mac.Write(candidateID[:])
|
||||
return candidateViewPseudonymPrefix + base64.RawURLEncoding.EncodeToString(mac.Sum(nil)), nil
|
||||
}
|
||||
|
||||
// ForCandidatePreview derives a private preview alias. Its HMAC purpose is
|
||||
// separate from organization aliases so a preview never reveals a linkable
|
||||
// organization identity.
|
||||
func (key CandidateViewPseudonymKey) ForCandidatePreview(candidateID uuid.UUID) (string, error) {
|
||||
if len(key.secret) < minimumCandidateViewPseudonymKeyLen || candidateID == uuid.Nil {
|
||||
return "", ErrInvalidAnonymousCandidateView
|
||||
}
|
||||
mac := hmac.New(sha256.New, key.secret)
|
||||
_, _ = mac.Write([]byte(candidatePreviewPseudonymPurpose))
|
||||
_, _ = mac.Write(candidateID[:])
|
||||
return candidateViewPseudonymPrefix + base64.RawURLEncoding.EncodeToString(mac.Sum(nil)), nil
|
||||
}
|
||||
|
||||
// CandidateViewSkillCode is a closed technology taxonomy. Raw profile tags
|
||||
// are never copied to an organization-facing view.
|
||||
type CandidateViewSkillCode string
|
||||
|
||||
const (
|
||||
CandidateViewSkillGo CandidateViewSkillCode = "go"
|
||||
CandidateViewSkillPostgreSQL CandidateViewSkillCode = "postgresql"
|
||||
CandidateViewSkillKafka CandidateViewSkillCode = "kafka"
|
||||
CandidateViewSkillDocker CandidateViewSkillCode = "docker"
|
||||
)
|
||||
|
||||
var candidateViewSkillCodes = []CandidateViewSkillCode{
|
||||
CandidateViewSkillDocker,
|
||||
CandidateViewSkillGo,
|
||||
CandidateViewSkillKafka,
|
||||
CandidateViewSkillPostgreSQL,
|
||||
}
|
||||
|
||||
func (code CandidateViewSkillCode) IsKnown() bool {
|
||||
return slices.Contains(candidateViewSkillCodes, code)
|
||||
}
|
||||
|
||||
// CandidateViewSkillCodes returns the closed skill taxonomy in canonical
|
||||
// order.
|
||||
func CandidateViewSkillCodes() []CandidateViewSkillCode {
|
||||
return slices.Clone(candidateViewSkillCodes)
|
||||
}
|
||||
|
||||
// CanonicalCandidateViewSkill maps a confirmed profile tag only when its
|
||||
// normalized value exactly matches a supported taxonomy entry.
|
||||
func CanonicalCandidateViewSkill(raw string) (CandidateViewSkillCode, bool) {
|
||||
normalized := strings.ToLower(strings.TrimSpace(norm.NFKC.String(raw)))
|
||||
switch normalized {
|
||||
case string(CandidateViewSkillGo):
|
||||
return CandidateViewSkillGo, true
|
||||
case string(CandidateViewSkillPostgreSQL):
|
||||
return CandidateViewSkillPostgreSQL, true
|
||||
case string(CandidateViewSkillKafka):
|
||||
return CandidateViewSkillKafka, true
|
||||
case string(CandidateViewSkillDocker):
|
||||
return CandidateViewSkillDocker, true
|
||||
default:
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
|
||||
// CandidateExperienceBand is the only work-tenure precision available in an
|
||||
// anonymous candidate view. The first four values are the normal buckets;
|
||||
// the last two are emitted only when a rare combination must be generalized.
|
||||
type CandidateExperienceBand string
|
||||
|
||||
const (
|
||||
CandidateExperienceBandZeroToOne CandidateExperienceBand = "0_1"
|
||||
CandidateExperienceBandOneToThree CandidateExperienceBand = "1_3"
|
||||
CandidateExperienceBandThreeToSix CandidateExperienceBand = "3_6"
|
||||
CandidateExperienceBandSixPlus CandidateExperienceBand = "6_plus"
|
||||
CandidateExperienceBandZeroToThree CandidateExperienceBand = "0_3"
|
||||
CandidateExperienceBandThreePlus CandidateExperienceBand = "3_plus"
|
||||
)
|
||||
|
||||
func (band CandidateExperienceBand) IsKnown() bool {
|
||||
switch band {
|
||||
case CandidateExperienceBandZeroToOne, CandidateExperienceBandOneToThree,
|
||||
CandidateExperienceBandThreeToSix, CandidateExperienceBandSixPlus,
|
||||
CandidateExperienceBandZeroToThree, CandidateExperienceBandThreePlus:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// CandidateViewConfirmationStatus says whether the current authoritative
|
||||
// result source confirms a specialization. It carries no attempt history.
|
||||
type CandidateViewConfirmationStatus string
|
||||
|
||||
const (
|
||||
CandidateViewConfirmationConfirmed CandidateViewConfirmationStatus = "confirmed"
|
||||
CandidateViewConfirmationUnconfirmed CandidateViewConfirmationStatus = "unconfirmed"
|
||||
)
|
||||
|
||||
// CandidateViewConfirmationStrength is a coarse, non-numeric description of
|
||||
// an authoritative confirmation. It is absent when no category is confirmed.
|
||||
type CandidateViewConfirmationStrength string
|
||||
|
||||
const (
|
||||
CandidateViewStrengthStandard CandidateViewConfirmationStrength = "standard"
|
||||
CandidateViewStrengthStrong CandidateViewConfirmationStrength = "strong"
|
||||
)
|
||||
|
||||
func (strength CandidateViewConfirmationStrength) IsKnown() bool {
|
||||
return strength == CandidateViewStrengthStandard || strength == CandidateViewStrengthStrong
|
||||
}
|
||||
|
||||
// CandidateViewConfirmedCategoryInput is accepted only from an authoritative
|
||||
// assessment-result source. It intentionally has no field for attempts,
|
||||
// failures, scores, or the candidate's self-assessment.
|
||||
type CandidateViewConfirmedCategoryInput struct {
|
||||
Specialization SpecializationCode
|
||||
Grade GradeCode
|
||||
Strength CandidateViewConfirmationStrength
|
||||
}
|
||||
|
||||
type candidateViewStackClaim struct {
|
||||
value string
|
||||
status ProfileClaimStatus
|
||||
}
|
||||
|
||||
type candidateViewRoleClaim struct {
|
||||
value ProfileRole
|
||||
status ProfileClaimStatus
|
||||
}
|
||||
|
||||
type candidateViewExperienceClaim struct {
|
||||
startedOn string
|
||||
endedOn string
|
||||
status ProfileClaimStatus
|
||||
}
|
||||
|
||||
// CandidateViewProfile is the private, minimal input needed for projection.
|
||||
// It carries no name, contact, employer, resume quote, summary, salary, or
|
||||
// free-text location or soft skill.
|
||||
type CandidateViewProfile struct {
|
||||
stack []candidateViewStackClaim
|
||||
roles []candidateViewRoleClaim
|
||||
experience []candidateViewExperienceClaim
|
||||
}
|
||||
|
||||
func (CandidateViewProfile) String() string { return "[candidate view profile]" }
|
||||
func (CandidateViewProfile) GoString() string { return "[candidate view profile]" }
|
||||
func (CandidateViewProfile) LogValue() slog.Value {
|
||||
return slog.StringValue("[candidate view profile]")
|
||||
}
|
||||
|
||||
// CandidateViewProfileFromContent removes private profile values that are
|
||||
// not needed to build the anonymous organization-facing view.
|
||||
func CandidateViewProfileFromContent(content CandidateProfileContent) CandidateViewProfile {
|
||||
profile := CandidateViewProfile{}
|
||||
for _, claim := range content.Stack() {
|
||||
profile.stack = append(profile.stack, candidateViewStackClaim{value: claim.Value(), status: claim.Status()})
|
||||
}
|
||||
for _, claim := range content.Roles() {
|
||||
profile.roles = append(profile.roles, candidateViewRoleClaim{value: claim.Value(), status: claim.Status()})
|
||||
}
|
||||
for _, claim := range content.Experience() {
|
||||
value := claim.Value()
|
||||
profile.experience = append(profile.experience, candidateViewExperienceClaim{
|
||||
startedOn: value.StartedOn, endedOn: value.EndedOn, status: claim.Status(),
|
||||
})
|
||||
}
|
||||
return profile
|
||||
}
|
||||
|
||||
// CandidateViewCategory is the category and coarse strength shown only when
|
||||
// categories were explicitly included in the publication.
|
||||
type CandidateViewCategory struct {
|
||||
Specialization SpecializationCode `json:"specialization"`
|
||||
Grade GradeCode `json:"grade"`
|
||||
Strength CandidateViewConfirmationStrength `json:"strength"`
|
||||
}
|
||||
|
||||
// CandidateViewSelfAssessment is a candidate-declared specialization and
|
||||
// grade, separate from the confirmed categories collection.
|
||||
type CandidateViewSelfAssessment struct {
|
||||
Specialization SpecializationCode `json:"specialization"`
|
||||
ConfirmationStatus CandidateViewConfirmationStatus `json:"confirmation_status"`
|
||||
DeclaredGrade *GradeCode `json:"declared_grade,omitempty"`
|
||||
}
|
||||
|
||||
// CandidateViewSalaryCompatibility is a typed comparison result. The numeric
|
||||
// salary bounds and the candidate's minimum are never part of a view.
|
||||
type CandidateViewSalaryCompatibility string
|
||||
|
||||
const (
|
||||
CandidateViewSalaryCompatible CandidateViewSalaryCompatibility = "compatible"
|
||||
CandidateViewSalaryNotCompatible CandidateViewSalaryCompatibility = "not_compatible"
|
||||
)
|
||||
|
||||
func (compatibility CandidateViewSalaryCompatibility) IsKnown() bool {
|
||||
return compatibility == CandidateViewSalaryCompatible || compatibility == CandidateViewSalaryNotCompatible
|
||||
}
|
||||
|
||||
// AnonymousCandidateViewDTO is the complete closed organization-facing data
|
||||
// transfer object. It contains no account ID, raw profile fields, or history.
|
||||
type AnonymousCandidateViewDTO struct {
|
||||
Pseudonym string `json:"pseudonym"`
|
||||
Skills []CandidateViewSkillCode `json:"skills"`
|
||||
Categories []CandidateViewCategory `json:"categories"`
|
||||
SelfAssessment []CandidateViewSelfAssessment `json:"self_assessment"`
|
||||
ExperienceBand *CandidateExperienceBand `json:"experience_band"`
|
||||
WorkFormats []QuestionnaireWorkFormat `json:"work_formats"`
|
||||
SalaryCompatibility *CandidateViewSalaryCompatibility `json:"salary_compatibility"`
|
||||
}
|
||||
|
||||
func (AnonymousCandidateViewDTO) String() string { return "[anonymous candidate view]" }
|
||||
func (AnonymousCandidateViewDTO) GoString() string { return "[anonymous candidate view]" }
|
||||
func (AnonymousCandidateViewDTO) LogValue() slog.Value {
|
||||
return slog.StringValue("[anonymous candidate view]")
|
||||
}
|
||||
|
||||
// CandidateViewInput combines explicitly published profile data with typed
|
||||
// results from authoritative sources. Profile content stays private and is
|
||||
// projected through a closed allowlist.
|
||||
type CandidateViewInput struct {
|
||||
Pseudonym string
|
||||
PublishedFields CardFieldSet
|
||||
Profile CandidateViewProfile
|
||||
AsOf time.Time
|
||||
ConfirmedCategories []CandidateViewConfirmedCategoryInput
|
||||
WorkFormats []QuestionnaireWorkFormat
|
||||
SalaryCompatibility *CandidateViewSalaryCompatibility
|
||||
}
|
||||
|
||||
func (CandidateViewInput) String() string { return "[candidate view input]" }
|
||||
func (CandidateViewInput) GoString() string { return "[candidate view input]" }
|
||||
func (CandidateViewInput) LogValue() slog.Value {
|
||||
return slog.StringValue("[candidate view input]")
|
||||
}
|
||||
|
||||
// AnonymousCandidateView is a validated, organization-scoped anonymous
|
||||
// projection. The internal generalization level is never exposed.
|
||||
type AnonymousCandidateView struct {
|
||||
dto AnonymousCandidateViewDTO
|
||||
generalizationLevel int
|
||||
}
|
||||
|
||||
// NewAnonymousCandidateView builds a strictly allowlisted projection from
|
||||
// currently published fields and typed, authoritative inputs.
|
||||
func NewAnonymousCandidateView(input CandidateViewInput) (AnonymousCandidateView, error) {
|
||||
const location = "domain.NewAnonymousCandidateView"
|
||||
if !validCandidateViewPseudonym(input.Pseudonym) {
|
||||
return AnonymousCandidateView{}, fmt.Errorf("%s - pseudonym is invalid: %w", location, ErrInvalidAnonymousCandidateView)
|
||||
}
|
||||
if err := validateCandidateViewConfirmations(input.ConfirmedCategories); err != nil {
|
||||
return AnonymousCandidateView{}, fmt.Errorf("%s - confirmations are invalid: %w", location, err)
|
||||
}
|
||||
view := AnonymousCandidateView{dto: AnonymousCandidateViewDTO{Pseudonym: input.Pseudonym}}
|
||||
if input.PublishedFields.Contains(CardFieldStack) {
|
||||
view.dto.Skills = candidateViewSkills(input.Profile)
|
||||
}
|
||||
if input.PublishedFields.Contains(CardFieldExperience) {
|
||||
band, err := candidateViewExperienceBand(input.Profile.experience, input.AsOf)
|
||||
if err != nil {
|
||||
return AnonymousCandidateView{}, fmt.Errorf("%s - project experience: %w", location, err)
|
||||
}
|
||||
view.dto.ExperienceBand = band
|
||||
}
|
||||
if input.PublishedFields.Contains(CardFieldCategories) {
|
||||
view.dto.Categories = candidateViewCategories(input.ConfirmedCategories)
|
||||
}
|
||||
if input.PublishedFields.Contains(CardFieldSelfAssessment) {
|
||||
view.dto.SelfAssessment = candidateViewSelfAssessments(input.Profile.roles, input.ConfirmedCategories)
|
||||
}
|
||||
if input.PublishedFields.Contains(CardFieldWorkFormats) {
|
||||
formats, err := canonicalCandidateViewWorkFormats(input.WorkFormats)
|
||||
if err != nil {
|
||||
return AnonymousCandidateView{}, fmt.Errorf("%s - work formats are invalid: %w", location, err)
|
||||
}
|
||||
view.dto.WorkFormats = formats
|
||||
}
|
||||
if input.PublishedFields.Contains(CardFieldSalaryCompatibility) && input.SalaryCompatibility != nil {
|
||||
if !input.SalaryCompatibility.IsKnown() {
|
||||
return AnonymousCandidateView{}, fmt.Errorf("%s - salary compatibility is invalid: %w", location, ErrInvalidAnonymousCandidateView)
|
||||
}
|
||||
value := *input.SalaryCompatibility
|
||||
view.dto.SalaryCompatibility = &value
|
||||
}
|
||||
return view, nil
|
||||
}
|
||||
|
||||
// DTO returns a detached copy of the allowlisted organization-facing value.
|
||||
func (view AnonymousCandidateView) DTO() AnonymousCandidateViewDTO {
|
||||
return cloneAnonymousCandidateViewDTO(view.dto)
|
||||
}
|
||||
|
||||
func cloneAnonymousCandidateViewDTO(dto AnonymousCandidateViewDTO) AnonymousCandidateViewDTO {
|
||||
dto.Skills = slices.Clone(dto.Skills)
|
||||
dto.Categories = slices.Clone(dto.Categories)
|
||||
dto.SelfAssessment = slices.Clone(dto.SelfAssessment)
|
||||
for index := range dto.SelfAssessment {
|
||||
dto.SelfAssessment[index].DeclaredGrade = clonePointer(dto.SelfAssessment[index].DeclaredGrade)
|
||||
}
|
||||
dto.ExperienceBand = clonePointer(dto.ExperienceBand)
|
||||
dto.WorkFormats = slices.Clone(dto.WorkFormats)
|
||||
dto.SalaryCompatibility = clonePointer(dto.SalaryCompatibility)
|
||||
return dto
|
||||
}
|
||||
|
||||
func validCandidateViewPseudonym(pseudonym string) bool {
|
||||
if !strings.HasPrefix(pseudonym, candidateViewPseudonymPrefix) {
|
||||
return false
|
||||
}
|
||||
encoded := strings.TrimPrefix(pseudonym, candidateViewPseudonymPrefix)
|
||||
decoded, err := base64.RawURLEncoding.DecodeString(encoded)
|
||||
return err == nil && len(decoded) == sha256.Size && base64.RawURLEncoding.EncodeToString(decoded) == encoded
|
||||
}
|
||||
|
||||
// IsCandidateViewPseudonym reports whether value is a canonical opaque view
|
||||
// alias. It does not establish that the alias is visible to any organization.
|
||||
func IsCandidateViewPseudonym(value string) bool {
|
||||
return validCandidateViewPseudonym(value)
|
||||
}
|
||||
|
||||
func validateCandidateViewConfirmations(confirmations []CandidateViewConfirmedCategoryInput) error {
|
||||
seen := make(map[SpecializationCode]struct{}, len(confirmations))
|
||||
for _, confirmation := range confirmations {
|
||||
if !confirmation.Specialization.IsKnown() || !confirmation.Grade.IsKnown() || !confirmation.Strength.IsKnown() {
|
||||
return ErrInvalidAnonymousCandidateView
|
||||
}
|
||||
if _, duplicate := seen[confirmation.Specialization]; duplicate {
|
||||
return ErrInvalidAnonymousCandidateView
|
||||
}
|
||||
seen[confirmation.Specialization] = struct{}{}
|
||||
}
|
||||
if len(confirmations) > maximumCandidateViewSpecializations {
|
||||
return ErrInvalidAnonymousCandidateView
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func candidateViewSkills(profile CandidateViewProfile) []CandidateViewSkillCode {
|
||||
seen := make(map[CandidateViewSkillCode]struct{})
|
||||
for _, claim := range profile.stack {
|
||||
if claim.status != ProfileClaimConfirmed {
|
||||
continue
|
||||
}
|
||||
code, ok := CanonicalCandidateViewSkill(claim.value)
|
||||
if ok {
|
||||
seen[code] = struct{}{}
|
||||
}
|
||||
}
|
||||
if len(seen) == 0 {
|
||||
return nil
|
||||
}
|
||||
result := make([]CandidateViewSkillCode, 0, len(seen))
|
||||
for code := range seen {
|
||||
result = append(result, code)
|
||||
}
|
||||
slices.Sort(result)
|
||||
return result
|
||||
}
|
||||
|
||||
func candidateViewExperienceBand(claims []candidateViewExperienceClaim, asOf time.Time) (*CandidateExperienceBand, error) {
|
||||
periods := make([]candidateViewMonthRange, 0, len(claims))
|
||||
for _, claim := range claims {
|
||||
if claim.status != ProfileClaimConfirmed {
|
||||
continue
|
||||
}
|
||||
period, err := candidateViewExperiencePeriod(claim, asOf)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
periods = append(periods, period)
|
||||
}
|
||||
if len(periods) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
slices.SortFunc(periods, func(left, right candidateViewMonthRange) int {
|
||||
if left.start < right.start {
|
||||
return -1
|
||||
}
|
||||
if left.start > right.start {
|
||||
return 1
|
||||
}
|
||||
if left.end < right.end {
|
||||
return -1
|
||||
}
|
||||
if left.end > right.end {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
})
|
||||
months := candidateViewUnionMonthCount(periods)
|
||||
if months < 0 {
|
||||
return nil, ErrInvalidAnonymousCandidateView
|
||||
}
|
||||
band := candidateViewBandForMonths(months)
|
||||
return &band, nil
|
||||
}
|
||||
|
||||
func candidateViewExperiencePeriod(experience candidateViewExperienceClaim, asOf time.Time) (candidateViewMonthRange, error) {
|
||||
start, valid := candidateViewMonthIndex(experience.startedOn)
|
||||
if !valid {
|
||||
return candidateViewMonthRange{}, ErrInvalidAnonymousCandidateView
|
||||
}
|
||||
var end int64
|
||||
switch {
|
||||
case experience.endedOn != "":
|
||||
end, valid = candidateViewMonthIndex(experience.endedOn)
|
||||
case !asOf.IsZero():
|
||||
end, valid = candidateViewMonthIndex(asOf.UTC().Format("2006-01"))
|
||||
default:
|
||||
return candidateViewMonthRange{}, ErrInvalidAnonymousCandidateView
|
||||
}
|
||||
if !valid || end < start {
|
||||
return candidateViewMonthRange{}, ErrInvalidAnonymousCandidateView
|
||||
}
|
||||
return candidateViewMonthRange{start: start, end: end}, nil
|
||||
}
|
||||
|
||||
type candidateViewMonthRange struct {
|
||||
start int64
|
||||
end int64
|
||||
}
|
||||
|
||||
func candidateViewMonthIndex(value string) (int64, bool) {
|
||||
if len(value) != 7 || value[4] != '-' {
|
||||
return 0, false
|
||||
}
|
||||
var year, month int64
|
||||
if _, err := fmt.Sscanf(value, "%4d-%2d", &year, &month); err != nil || year < 1 || month < 1 || month > 12 {
|
||||
return 0, false
|
||||
}
|
||||
return year*12 + month - 1, true
|
||||
}
|
||||
|
||||
func candidateViewUnionMonthCount(periods []candidateViewMonthRange) int64 {
|
||||
start, end := periods[0].start, periods[0].end
|
||||
var months int64
|
||||
for _, period := range periods[1:] {
|
||||
if period.start <= end+1 {
|
||||
if period.end > end {
|
||||
end = period.end
|
||||
}
|
||||
continue
|
||||
}
|
||||
months += end - start + 1
|
||||
start, end = period.start, period.end
|
||||
}
|
||||
return months + end - start + 1
|
||||
}
|
||||
|
||||
func candidateViewBandForMonths(months int64) CandidateExperienceBand {
|
||||
switch {
|
||||
case months < 12:
|
||||
return CandidateExperienceBandZeroToOne
|
||||
case months < 36:
|
||||
return CandidateExperienceBandOneToThree
|
||||
case months < 72:
|
||||
return CandidateExperienceBandThreeToSix
|
||||
default:
|
||||
return CandidateExperienceBandSixPlus
|
||||
}
|
||||
}
|
||||
|
||||
func candidateViewCategories(confirmations []CandidateViewConfirmedCategoryInput) []CandidateViewCategory {
|
||||
if len(confirmations) == 0 {
|
||||
return nil
|
||||
}
|
||||
result := make([]CandidateViewCategory, 0, len(confirmations))
|
||||
for _, confirmation := range confirmations {
|
||||
result = append(result, CandidateViewCategory(confirmation))
|
||||
}
|
||||
slices.SortFunc(result, func(left, right CandidateViewCategory) int {
|
||||
return strings.Compare(string(left.Specialization), string(right.Specialization))
|
||||
})
|
||||
return result
|
||||
}
|
||||
|
||||
func candidateViewSelfAssessments(
|
||||
roles []candidateViewRoleClaim,
|
||||
confirmations []CandidateViewConfirmedCategoryInput,
|
||||
) []CandidateViewSelfAssessment {
|
||||
confirmationBySpecialization := make(map[SpecializationCode]struct{}, len(confirmations))
|
||||
for _, confirmation := range confirmations {
|
||||
confirmationBySpecialization[confirmation.Specialization] = struct{}{}
|
||||
}
|
||||
result := make([]CandidateViewSelfAssessment, 0, len(roles))
|
||||
seen := make(map[SpecializationCode]struct{}, len(roles))
|
||||
for _, claim := range roles {
|
||||
if claim.status != ProfileClaimConfirmed {
|
||||
continue
|
||||
}
|
||||
role := claim.value
|
||||
if _, duplicate := seen[role.Specialization]; duplicate {
|
||||
return nil
|
||||
}
|
||||
seen[role.Specialization] = struct{}{}
|
||||
status := CandidateViewConfirmationUnconfirmed
|
||||
if _, confirmed := confirmationBySpecialization[role.Specialization]; confirmed {
|
||||
status = CandidateViewConfirmationConfirmed
|
||||
}
|
||||
item := CandidateViewSelfAssessment{Specialization: role.Specialization, ConfirmationStatus: status}
|
||||
if role.SelfAssessedGrade != "" {
|
||||
grade := role.SelfAssessedGrade
|
||||
item.DeclaredGrade = &grade
|
||||
}
|
||||
result = append(result, item)
|
||||
}
|
||||
if len(result) == 0 {
|
||||
return nil
|
||||
}
|
||||
slices.SortFunc(result, func(left, right CandidateViewSelfAssessment) int {
|
||||
return strings.Compare(string(left.Specialization), string(right.Specialization))
|
||||
})
|
||||
return result
|
||||
}
|
||||
|
||||
func canonicalCandidateViewWorkFormats(formats []QuestionnaireWorkFormat) ([]QuestionnaireWorkFormat, error) {
|
||||
if len(formats) > maximumCandidateViewWorkFormats {
|
||||
return nil, ErrInvalidAnonymousCandidateView
|
||||
}
|
||||
if len(formats) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
result := slices.Clone(formats)
|
||||
for _, format := range result {
|
||||
if !format.IsKnown() {
|
||||
return nil, ErrInvalidAnonymousCandidateView
|
||||
}
|
||||
}
|
||||
slices.Sort(result)
|
||||
if len(slices.Compact(slices.Clone(result))) != len(result) {
|
||||
return nil, ErrInvalidAnonymousCandidateView
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// GeneralizeAnonymousCandidateCohort suppresses or generalizes the complete
|
||||
// visible quasi-identifier combination until every displayed combination has
|
||||
// at least five distinct pseudonyms. The caller must pass only candidates
|
||||
// whose C2, publication, and organization visibility checks succeeded.
|
||||
func GeneralizeAnonymousCandidateCohort(views []AnonymousCandidateView) ([]AnonymousCandidateView, error) {
|
||||
result := make([]AnonymousCandidateView, len(views))
|
||||
seenPseudonyms := make(map[string]struct{}, len(views))
|
||||
for index, view := range views {
|
||||
if !validCandidateViewPseudonym(view.dto.Pseudonym) {
|
||||
return nil, ErrInvalidAnonymousCandidateView
|
||||
}
|
||||
if _, duplicate := seenPseudonyms[view.dto.Pseudonym]; duplicate {
|
||||
return nil, ErrInvalidAnonymousCandidateView
|
||||
}
|
||||
seenPseudonyms[view.dto.Pseudonym] = struct{}{}
|
||||
result[index] = AnonymousCandidateView{
|
||||
dto: cloneAnonymousCandidateViewDTO(view.dto), generalizationLevel: view.generalizationLevel,
|
||||
}
|
||||
}
|
||||
for pass := 0; pass <= maximumCandidateViewGeneralization; pass++ {
|
||||
groups := candidateViewCohortGroups(result)
|
||||
changed := false
|
||||
for _, indexes := range groups {
|
||||
if len(indexes) >= minimumAnonymousCandidateCohort {
|
||||
continue
|
||||
}
|
||||
for _, index := range indexes {
|
||||
if result[index].generalizationLevel >= maximumCandidateViewGeneralization {
|
||||
continue
|
||||
}
|
||||
result[index].generalizationLevel++
|
||||
applyCandidateViewGeneralization(&result[index])
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
break
|
||||
}
|
||||
}
|
||||
return suppressSmallCandidateViewGroups(result), nil
|
||||
}
|
||||
|
||||
func suppressSmallCandidateViewGroups(views []AnonymousCandidateView) []AnonymousCandidateView {
|
||||
groups := candidateViewCohortGroups(views)
|
||||
keep := make([]bool, len(views))
|
||||
for _, indexes := range groups {
|
||||
if len(indexes) < minimumAnonymousCandidateCohort {
|
||||
continue
|
||||
}
|
||||
for _, index := range indexes {
|
||||
keep[index] = true
|
||||
}
|
||||
}
|
||||
result := make([]AnonymousCandidateView, 0, len(views))
|
||||
for index, view := range views {
|
||||
if keep[index] {
|
||||
result = append(result, view)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func candidateViewCohortGroups(views []AnonymousCandidateView) map[string][]int {
|
||||
groups := make(map[string][]int)
|
||||
for index, view := range views {
|
||||
encoded, _ := json.Marshal(candidateViewCohortFeatures(view.dto))
|
||||
groups[string(encoded)] = append(groups[string(encoded)], index)
|
||||
}
|
||||
return groups
|
||||
}
|
||||
|
||||
type anonymousCandidateViewFeatures struct {
|
||||
Skills []CandidateViewSkillCode `json:"skills"`
|
||||
Categories []CandidateViewCategory `json:"categories"`
|
||||
SelfAssessment []CandidateViewSelfAssessment `json:"self_assessment"`
|
||||
ExperienceBand *CandidateExperienceBand `json:"experience_band"`
|
||||
WorkFormats []QuestionnaireWorkFormat `json:"work_formats"`
|
||||
SalaryCompatibility *CandidateViewSalaryCompatibility `json:"salary_compatibility"`
|
||||
}
|
||||
|
||||
func candidateViewCohortFeatures(dto AnonymousCandidateViewDTO) anonymousCandidateViewFeatures {
|
||||
return anonymousCandidateViewFeatures{
|
||||
Skills: dto.Skills, Categories: dto.Categories, SelfAssessment: dto.SelfAssessment,
|
||||
ExperienceBand: dto.ExperienceBand, WorkFormats: dto.WorkFormats,
|
||||
SalaryCompatibility: dto.SalaryCompatibility,
|
||||
}
|
||||
}
|
||||
|
||||
func applyCandidateViewGeneralization(view *AnonymousCandidateView) {
|
||||
switch view.generalizationLevel {
|
||||
case 1:
|
||||
view.dto.Skills = nil
|
||||
case 2:
|
||||
view.dto.WorkFormats = nil
|
||||
case 3:
|
||||
view.dto.SalaryCompatibility = nil
|
||||
view.dto.ExperienceBand = generalizedCandidateExperienceBand(view.dto.ExperienceBand)
|
||||
case 4:
|
||||
view.dto.Categories = nil
|
||||
view.dto.SelfAssessment = nil
|
||||
case 5:
|
||||
view.dto.ExperienceBand = nil
|
||||
}
|
||||
}
|
||||
|
||||
func generalizedCandidateExperienceBand(band *CandidateExperienceBand) *CandidateExperienceBand {
|
||||
if band == nil {
|
||||
return nil
|
||||
}
|
||||
var generalized CandidateExperienceBand
|
||||
switch *band {
|
||||
case CandidateExperienceBandZeroToOne, CandidateExperienceBandOneToThree:
|
||||
generalized = CandidateExperienceBandZeroToThree
|
||||
case CandidateExperienceBandThreeToSix, CandidateExperienceBandSixPlus:
|
||||
generalized = CandidateExperienceBandThreePlus
|
||||
case CandidateExperienceBandZeroToThree, CandidateExperienceBandThreePlus:
|
||||
generalized = *band
|
||||
default:
|
||||
return clonePointer(band)
|
||||
}
|
||||
return &generalized
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var ErrInvalidCandidateViewSource = errors.New("invalid candidate view source")
|
||||
|
||||
// CandidateViewSource is a private read-model source for one currently
|
||||
// published candidate. Its identifier and source values must never be logged
|
||||
// or serialized as an organization-facing response.
|
||||
type CandidateViewSource struct {
|
||||
candidateID uuid.UUID
|
||||
publishedFields CardFieldSet
|
||||
profile CandidateViewProfile
|
||||
confirmedCategories []CandidateViewConfirmedCategoryInput
|
||||
workFormats []QuestionnaireWorkFormat
|
||||
salaryCompatibility *CandidateViewSalaryCompatibility
|
||||
}
|
||||
|
||||
func NewCandidateViewSource(
|
||||
candidateID uuid.UUID,
|
||||
publishedFields CardFieldSet,
|
||||
profile CandidateViewProfile,
|
||||
confirmedCategories []CandidateViewConfirmedCategoryInput,
|
||||
workFormats []QuestionnaireWorkFormat,
|
||||
salaryCompatibility *CandidateViewSalaryCompatibility,
|
||||
) (CandidateViewSource, error) {
|
||||
if candidateID == uuid.Nil || publishedFields.IsEmpty() {
|
||||
return CandidateViewSource{}, ErrInvalidCandidateViewSource
|
||||
}
|
||||
if len(workFormats) > maximumCandidateViewWorkFormats || len(confirmedCategories) > maximumCandidateViewSpecializations {
|
||||
return CandidateViewSource{}, ErrInvalidCandidateViewSource
|
||||
}
|
||||
return CandidateViewSource{
|
||||
candidateID: candidateID, publishedFields: publishedFields,
|
||||
profile: cloneCandidateViewProfile(profile),
|
||||
confirmedCategories: slices.Clone(confirmedCategories), workFormats: slices.Clone(workFormats),
|
||||
salaryCompatibility: clonePointer(salaryCompatibility),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (CandidateViewSource) String() string { return "[private candidate view source]" }
|
||||
func (CandidateViewSource) GoString() string { return "[private candidate view source]" }
|
||||
func (CandidateViewSource) LogValue() slog.Value {
|
||||
return slog.StringValue("[private candidate view source]")
|
||||
}
|
||||
|
||||
// CandidateID is an internal join key for deriving the organization-scoped
|
||||
// pseudonym. It is not part of the anonymous DTO.
|
||||
func (source CandidateViewSource) CandidateID() uuid.UUID { return source.candidateID }
|
||||
|
||||
// PublishedFields returns the selected allowlist for the private projection.
|
||||
func (source CandidateViewSource) PublishedFields() CardFieldSet { return source.publishedFields }
|
||||
|
||||
// Input returns detached, typed projection data without the candidate ID.
|
||||
func (source CandidateViewSource) Input(pseudonym string, asOf time.Time) CandidateViewInput {
|
||||
return CandidateViewInput{
|
||||
Pseudonym: pseudonym, PublishedFields: source.publishedFields,
|
||||
Profile: cloneCandidateViewProfile(source.profile), AsOf: asOf,
|
||||
ConfirmedCategories: slices.Clone(source.confirmedCategories),
|
||||
WorkFormats: slices.Clone(source.workFormats),
|
||||
SalaryCompatibility: clonePointer(source.salaryCompatibility),
|
||||
}
|
||||
}
|
||||
|
||||
func cloneCandidateViewProfile(profile CandidateViewProfile) CandidateViewProfile {
|
||||
return CandidateViewProfile{
|
||||
stack: slices.Clone(profile.stack), roles: slices.Clone(profile.roles),
|
||||
experience: slices.Clone(profile.experience),
|
||||
}
|
||||
}
|
||||
|
||||
func ValidateCandidateViewSource(source CandidateViewSource) error {
|
||||
if source.candidateID == uuid.Nil || source.publishedFields.IsEmpty() {
|
||||
return fmt.Errorf("candidate view source identity or publication is invalid: %w", ErrInvalidCandidateViewSource)
|
||||
}
|
||||
if source.salaryCompatibility != nil && !source.salaryCompatibility.IsKnown() {
|
||||
return fmt.Errorf("candidate view source compatibility is invalid: %w", ErrInvalidCandidateViewSource)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,419 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestCandidateViewPseudonymIsStableAndOrganizationScoped(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
key, err := NewCandidateViewPseudonymKey(bytes.Repeat([]byte("k"), minimumCandidateViewPseudonymKeyLen))
|
||||
if err != nil {
|
||||
t.Fatalf("NewCandidateViewPseudonymKey() error = %v", err)
|
||||
}
|
||||
organizationA := uuid.New()
|
||||
organizationB := uuid.New()
|
||||
candidate := uuid.New()
|
||||
|
||||
first, err := key.ForOrganization(organizationA, candidate)
|
||||
if err != nil {
|
||||
t.Fatalf("ForOrganization() error = %v", err)
|
||||
}
|
||||
repeated, err := key.ForOrganization(organizationA, candidate)
|
||||
if err != nil {
|
||||
t.Fatalf("ForOrganization() repeat error = %v", err)
|
||||
}
|
||||
otherOrganization, err := key.ForOrganization(organizationB, candidate)
|
||||
if err != nil {
|
||||
t.Fatalf("ForOrganization() other organization error = %v", err)
|
||||
}
|
||||
otherCandidate, err := key.ForOrganization(organizationA, uuid.New())
|
||||
if err != nil {
|
||||
t.Fatalf("ForOrganization() other candidate error = %v", err)
|
||||
}
|
||||
|
||||
if first != repeated {
|
||||
t.Fatal("pseudonym changed for the same organization and candidate")
|
||||
}
|
||||
if first == otherOrganization || first == otherCandidate {
|
||||
t.Fatal("pseudonym did not vary by organization and candidate")
|
||||
}
|
||||
if !validCandidateViewPseudonym(first) || strings.Contains(first, candidate.String()) {
|
||||
t.Fatalf("pseudonym is not an opaque full-length alias: %q", first)
|
||||
}
|
||||
if strings.Contains(key.String(), string(bytes.Repeat([]byte("k"), minimumCandidateViewPseudonymKeyLen))) {
|
||||
t.Fatal("key formatting exposed its secret")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCandidateViewPseudonymRejectsWeakKeyAndEmptyIdentity(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
if _, err := NewCandidateViewPseudonymKey(make([]byte, minimumCandidateViewPseudonymKeyLen-1)); !errors.Is(err, ErrInvalidAnonymousCandidateView) {
|
||||
t.Fatalf("short key error = %v, want ErrInvalidAnonymousCandidateView", err)
|
||||
}
|
||||
key, err := NewCandidateViewPseudonymKey(bytes.Repeat([]byte("k"), minimumCandidateViewPseudonymKeyLen))
|
||||
if err != nil {
|
||||
t.Fatalf("NewCandidateViewPseudonymKey() error = %v", err)
|
||||
}
|
||||
if _, err := key.ForOrganization(uuid.Nil, uuid.New()); !errors.Is(err, ErrInvalidAnonymousCandidateView) {
|
||||
t.Fatalf("empty organization error = %v, want ErrInvalidAnonymousCandidateView", err)
|
||||
}
|
||||
if _, err := key.ForOrganization(uuid.New(), uuid.Nil); !errors.Is(err, ErrInvalidAnonymousCandidateView) {
|
||||
t.Fatalf("empty candidate error = %v, want ErrInvalidAnonymousCandidateView", err)
|
||||
}
|
||||
if _, err := key.ForCandidatePreview(uuid.Nil); !errors.Is(err, ErrInvalidAnonymousCandidateView) {
|
||||
t.Fatalf("empty preview candidate error = %v, want ErrInvalidAnonymousCandidateView", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCandidatePreviewPseudonymUsesSeparateContext(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
key, err := NewCandidateViewPseudonymKey(bytes.Repeat([]byte("k"), minimumCandidateViewPseudonymKeyLen))
|
||||
if err != nil {
|
||||
t.Fatalf("NewCandidateViewPseudonymKey() error = %v", err)
|
||||
}
|
||||
candidateID := uuid.New()
|
||||
preview, err := key.ForCandidatePreview(candidateID)
|
||||
if err != nil {
|
||||
t.Fatalf("ForCandidatePreview() error = %v", err)
|
||||
}
|
||||
organization, err := key.ForOrganization(uuid.New(), candidateID)
|
||||
if err != nil {
|
||||
t.Fatalf("ForOrganization() error = %v", err)
|
||||
}
|
||||
previewAgain, err := key.ForCandidatePreview(candidateID)
|
||||
if err != nil {
|
||||
t.Fatalf("ForCandidatePreview() repeat error = %v", err)
|
||||
}
|
||||
if preview == organization || previewAgain != preview || !validCandidateViewPseudonym(preview) {
|
||||
t.Fatal("preview pseudonym must be stable, valid, and separate from employer aliases")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnonymousCandidateViewUsesPublishedAllowlist(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
profileID := uuid.New()
|
||||
profile, err := EmptyCandidateProfile(profileID)
|
||||
if err != nil {
|
||||
t.Fatalf("EmptyCandidateProfile() error = %v", err)
|
||||
}
|
||||
input := CandidateProfileInput{
|
||||
FullName: confirmed("NameMarker"), Email: confirmed("person-marker@example.test"),
|
||||
Phone: confirmed("+79000000000"), Telegram: confirmed("@external_marker"),
|
||||
Stack: confirmedItems("Go", "postgresql", "UniqueStackMarker"),
|
||||
Roles: confirmedItems(
|
||||
ProfileRole{Specialization: SpecializationBackend, SelfAssessedGrade: GradeJunior},
|
||||
ProfileRole{Specialization: SpecializationNetworkEngineer, SelfAssessedGrade: GradeSenior},
|
||||
),
|
||||
Experience: confirmedItems(
|
||||
ProfileExperience{EmployerName: "EmployerMarker", Specialization: SpecializationBackend, StartedOn: "2022-01", EndedOn: "2023-12", Summary: "SummaryMarker"},
|
||||
ProfileExperience{EmployerName: "OtherEmployerMarker", Specialization: SpecializationBackend, StartedOn: "2023-01", EndedOn: "2024-12", Summary: "OtherSummaryMarker"},
|
||||
),
|
||||
ParallelPeriodAcknowledgements: []ProfileParallelPeriodAcknowledgement{{
|
||||
FirstIndex: 0, SecondIndex: 1,
|
||||
FirstPeriod: ProfileExperiencePeriod{StartedOn: "2022-01", EndedOn: "2023-12"},
|
||||
SecondPeriod: ProfileExperiencePeriod{StartedOn: "2023-01", EndedOn: "2024-12"},
|
||||
}},
|
||||
SoftSkills: confirmedItems("SoftSkillMarker"), Location: confirmed("LocationMarker"),
|
||||
Relocation: confirmed(true), SalaryMinimum: confirmed(ProfileSalaryMinimum{Amount: 180_000, TaxBasis: ProfileTaxNet}),
|
||||
}
|
||||
content, err := ResolveCandidateProfileContent(profile.Content(), input, time.Date(2026, 10, 6, 0, 0, 0, 0, time.UTC))
|
||||
if err != nil {
|
||||
t.Fatalf("ResolveCandidateProfileContent() error = %v", err)
|
||||
}
|
||||
fields, err := NewCardFieldSet([]CardField{
|
||||
CardFieldStack, CardFieldExperience, CardFieldCategories, CardFieldSelfAssessment,
|
||||
CardFieldWorkFormats, CardFieldSalaryCompatibility,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewCardFieldSet() error = %v", err)
|
||||
}
|
||||
pseudonym := candidateViewTestPseudonym(t, uuid.New(), profileID)
|
||||
view, err := NewAnonymousCandidateView(CandidateViewInput{
|
||||
Pseudonym: pseudonym, PublishedFields: fields, Profile: CandidateViewProfileFromContent(content),
|
||||
AsOf: time.Date(2026, 10, 6, 0, 0, 0, 0, time.UTC),
|
||||
ConfirmedCategories: []CandidateViewConfirmedCategoryInput{{
|
||||
Specialization: SpecializationBackend, Grade: GradeMiddle, Strength: CandidateViewStrengthStrong,
|
||||
}},
|
||||
WorkFormats: []QuestionnaireWorkFormat{QuestionnaireWorkFormatRemote, QuestionnaireWorkFormatHybrid},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewAnonymousCandidateView() error = %v", err)
|
||||
}
|
||||
dto := view.DTO()
|
||||
if len(dto.Skills) != 2 || !containsCandidateViewSkill(dto.Skills, CandidateViewSkillGo) || !containsCandidateViewSkill(dto.Skills, CandidateViewSkillPostgreSQL) {
|
||||
t.Fatalf("skills = %#v, want only canonical Go and PostgreSQL", dto.Skills)
|
||||
}
|
||||
if dto.ExperienceBand == nil || *dto.ExperienceBand != CandidateExperienceBandThreeToSix {
|
||||
t.Fatalf("experience band = %v, want 3_6", dto.ExperienceBand)
|
||||
}
|
||||
if len(dto.Categories) != 1 || dto.Categories[0].Specialization != SpecializationBackend || dto.Categories[0].Grade != GradeMiddle || dto.Categories[0].Strength != CandidateViewStrengthStrong {
|
||||
t.Fatalf("categories = %#v, want only the authoritative backend result", dto.Categories)
|
||||
}
|
||||
if len(dto.SelfAssessment) != 2 {
|
||||
t.Fatalf("self assessment = %#v, want two separately published declared specializations", dto.SelfAssessment)
|
||||
}
|
||||
if dto.SelfAssessment[0].Specialization != SpecializationBackend || dto.SelfAssessment[0].ConfirmationStatus != CandidateViewConfirmationConfirmed ||
|
||||
dto.SelfAssessment[0].DeclaredGrade == nil || *dto.SelfAssessment[0].DeclaredGrade != GradeJunior {
|
||||
t.Fatalf("backend self assessment = %#v, want separately declared grade", dto.SelfAssessment[0])
|
||||
}
|
||||
if dto.SelfAssessment[1].Specialization != SpecializationNetworkEngineer || dto.SelfAssessment[1].ConfirmationStatus != CandidateViewConfirmationUnconfirmed ||
|
||||
dto.SelfAssessment[1].DeclaredGrade == nil || *dto.SelfAssessment[1].DeclaredGrade != GradeSenior {
|
||||
t.Fatalf("network self assessment = %#v, want declared-only grade", dto.SelfAssessment[1])
|
||||
}
|
||||
if len(dto.WorkFormats) != 2 || dto.SalaryCompatibility != nil {
|
||||
t.Fatalf("work formats and compatibility = %#v, %#v", dto.WorkFormats, dto.SalaryCompatibility)
|
||||
}
|
||||
|
||||
encoded, err := json.Marshal(dto)
|
||||
if err != nil {
|
||||
t.Fatalf("Marshal() error = %v", err)
|
||||
}
|
||||
for _, marker := range []string{
|
||||
"NameMarker", "person-marker@example.test", "+79000000000", "external_marker",
|
||||
"EmployerMarker", "OtherEmployerMarker", "SummaryMarker", "OtherSummaryMarker",
|
||||
"SoftSkillMarker", "LocationMarker", "UniqueStackMarker", "180000",
|
||||
} {
|
||||
if strings.Contains(string(encoded), marker) {
|
||||
t.Errorf("anonymous DTO contains forbidden marker %q: %s", marker, encoded)
|
||||
}
|
||||
}
|
||||
if strings.Contains(string(encoded), `"declared_grade":null`) || strings.Contains(string(encoded), `"strength":null`) {
|
||||
t.Fatalf("missing values must be omitted rather than encoded as zero values: %s", encoded)
|
||||
}
|
||||
if strings.Contains(string(encoded), `"specialization":"network_engineer","grade":"senior"`) {
|
||||
t.Fatalf("declared grade was mixed into confirmed categories: %s", encoded)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnonymousCandidateViewSalaryCompatibilityRequiresExplicitField(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
profile, err := EmptyCandidateProfile(uuid.New())
|
||||
if err != nil {
|
||||
t.Fatalf("EmptyCandidateProfile() error = %v", err)
|
||||
}
|
||||
compatibility := CandidateViewSalaryNotCompatible
|
||||
fields, err := NewCardFieldSet([]CardField{CardFieldSalaryCompatibility})
|
||||
if err != nil {
|
||||
t.Fatalf("NewCardFieldSet() error = %v", err)
|
||||
}
|
||||
view, err := NewAnonymousCandidateView(CandidateViewInput{
|
||||
Pseudonym: candidateViewTestPseudonym(t, uuid.New(), profile.UserID()),
|
||||
PublishedFields: fields, Profile: CandidateViewProfileFromContent(profile.Content()), SalaryCompatibility: &compatibility,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewAnonymousCandidateView() error = %v", err)
|
||||
}
|
||||
if view.DTO().SalaryCompatibility == nil || *view.DTO().SalaryCompatibility != CandidateViewSalaryNotCompatible {
|
||||
t.Fatalf("compatibility = %v, want explicitly supplied non-compatible result", view.DTO().SalaryCompatibility)
|
||||
}
|
||||
|
||||
fields, err = NewCardFieldSet(nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewCardFieldSet(empty) error = %v", err)
|
||||
}
|
||||
view, err = NewAnonymousCandidateView(CandidateViewInput{
|
||||
Pseudonym: candidateViewTestPseudonym(t, uuid.New(), profile.UserID()),
|
||||
PublishedFields: fields, Profile: CandidateViewProfileFromContent(profile.Content()), SalaryCompatibility: &compatibility,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewAnonymousCandidateView() without opt-in error = %v", err)
|
||||
}
|
||||
if view.DTO().SalaryCompatibility != nil {
|
||||
t.Fatalf("compatibility = %v without the publication opt-in, want nil", view.DTO().SalaryCompatibility)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnonymousCandidateViewKeepsCategoriesSeparateFromSelfAssessment(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
profile, err := EmptyCandidateProfile(uuid.New())
|
||||
if err != nil {
|
||||
t.Fatalf("EmptyCandidateProfile() error = %v", err)
|
||||
}
|
||||
content, err := ResolveCandidateProfileContent(profile.Content(), CandidateProfileInput{
|
||||
Roles: confirmedItems(ProfileRole{Specialization: SpecializationBackend, SelfAssessedGrade: GradeJunior}),
|
||||
}, candidateTestTime)
|
||||
if err != nil {
|
||||
t.Fatalf("ResolveCandidateProfileContent() error = %v", err)
|
||||
}
|
||||
category := CandidateViewConfirmedCategoryInput{
|
||||
Specialization: SpecializationBackend, Grade: GradeMiddle, Strength: CandidateViewStrengthStandard,
|
||||
}
|
||||
newView := func(field CardField) AnonymousCandidateViewDTO {
|
||||
t.Helper()
|
||||
fields, err := NewCardFieldSet([]CardField{field})
|
||||
if err != nil {
|
||||
t.Fatalf("NewCardFieldSet() error = %v", err)
|
||||
}
|
||||
view, err := NewAnonymousCandidateView(CandidateViewInput{
|
||||
Pseudonym: candidateViewTestPseudonym(t, uuid.New(), profile.UserID()),
|
||||
PublishedFields: fields, Profile: CandidateViewProfileFromContent(content),
|
||||
ConfirmedCategories: []CandidateViewConfirmedCategoryInput{category},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewAnonymousCandidateView() error = %v", err)
|
||||
}
|
||||
return view.DTO()
|
||||
}
|
||||
|
||||
categoryOnly := newView(CardFieldCategories)
|
||||
if len(categoryOnly.Categories) != 1 || categoryOnly.SelfAssessment != nil {
|
||||
t.Fatalf("categories-only opt-in returned categories=%#v self_assessment=%#v", categoryOnly.Categories, categoryOnly.SelfAssessment)
|
||||
}
|
||||
selfAssessmentOnly := newView(CardFieldSelfAssessment)
|
||||
if selfAssessmentOnly.Categories != nil || len(selfAssessmentOnly.SelfAssessment) != 1 {
|
||||
t.Fatalf("self-assessment-only opt-in returned categories=%#v self_assessment=%#v", selfAssessmentOnly.Categories, selfAssessmentOnly.SelfAssessment)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCandidateViewExperienceBandsHaveExactBoundaries(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
from string
|
||||
to string
|
||||
want CandidateExperienceBand
|
||||
}{
|
||||
{name: "eleven months", from: "2024-01", to: "2024-11", want: CandidateExperienceBandZeroToOne},
|
||||
{name: "one year", from: "2024-01", to: "2024-12", want: CandidateExperienceBandOneToThree},
|
||||
{name: "three years", from: "2022-01", to: "2024-12", want: CandidateExperienceBandThreeToSix},
|
||||
{name: "six years", from: "2020-01", to: "2025-12", want: CandidateExperienceBandSixPlus},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
profile, err := EmptyCandidateProfile(uuid.New())
|
||||
if err != nil {
|
||||
t.Fatalf("EmptyCandidateProfile() error = %v", err)
|
||||
}
|
||||
content, err := ResolveCandidateProfileContent(profile.Content(), CandidateProfileInput{Experience: confirmedItems(ProfileExperience{
|
||||
Specialization: SpecializationBackend, StartedOn: test.from, EndedOn: test.to,
|
||||
})}, candidateTestTime)
|
||||
if err != nil {
|
||||
t.Fatalf("ResolveCandidateProfileContent() error = %v", err)
|
||||
}
|
||||
band, err := candidateViewExperienceBand(CandidateViewProfileFromContent(content).experience, time.Time{})
|
||||
if err != nil {
|
||||
t.Fatalf("candidateViewExperienceBand() error = %v", err)
|
||||
}
|
||||
if band == nil || *band != test.want {
|
||||
t.Fatalf("band = %v, want %s", band, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGeneralizeAnonymousCandidateCohortSuppressesRareCombinations(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
organizationID := uuid.New()
|
||||
key, err := NewCandidateViewPseudonymKey(bytes.Repeat([]byte("p"), minimumCandidateViewPseudonymKeyLen))
|
||||
if err != nil {
|
||||
t.Fatalf("NewCandidateViewPseudonymKey() error = %v", err)
|
||||
}
|
||||
newView := func(skill CandidateViewSkillCode, candidateID uuid.UUID) AnonymousCandidateView {
|
||||
t.Helper()
|
||||
profile, err := EmptyCandidateProfile(candidateID)
|
||||
if err != nil {
|
||||
t.Fatalf("EmptyCandidateProfile() error = %v", err)
|
||||
}
|
||||
fields, err := NewCardFieldSet([]CardField{CardFieldStack})
|
||||
if err != nil {
|
||||
t.Fatalf("NewCardFieldSet() error = %v", err)
|
||||
}
|
||||
input := CandidateProfileInput{Stack: confirmedItems(string(skill))}
|
||||
content, err := ResolveCandidateProfileContent(profile.Content(), input, candidateTestTime)
|
||||
if err != nil {
|
||||
t.Fatalf("ResolveCandidateProfileContent() error = %v", err)
|
||||
}
|
||||
pseudonym, err := key.ForOrganization(organizationID, candidateID)
|
||||
if err != nil {
|
||||
t.Fatalf("ForOrganization() error = %v", err)
|
||||
}
|
||||
view, err := NewAnonymousCandidateView(CandidateViewInput{
|
||||
Pseudonym: pseudonym, PublishedFields: fields, Profile: CandidateViewProfileFromContent(content),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewAnonymousCandidateView() error = %v", err)
|
||||
}
|
||||
return view
|
||||
}
|
||||
|
||||
views := make([]AnonymousCandidateView, 0, 10)
|
||||
for range 4 {
|
||||
views = append(views, newView(CandidateViewSkillGo, uuid.New()))
|
||||
}
|
||||
views = append(views, newView(CandidateViewSkillKafka, uuid.New()))
|
||||
for range 5 {
|
||||
views = append(views, newView(CandidateViewSkillDocker, uuid.New()))
|
||||
}
|
||||
generalized, err := GeneralizeAnonymousCandidateCohort(views)
|
||||
if err != nil {
|
||||
t.Fatalf("GeneralizeAnonymousCandidateCohort() error = %v", err)
|
||||
}
|
||||
if len(generalized) != 10 {
|
||||
t.Fatalf("generalized views = %d, want all ten after the rare combinations merge safely", len(generalized))
|
||||
}
|
||||
var generalizedRare, retainedCommon int
|
||||
for _, view := range generalized {
|
||||
switch {
|
||||
case len(view.DTO().Skills) == 0:
|
||||
generalizedRare++
|
||||
case len(view.DTO().Skills) == 1 && view.DTO().Skills[0] == CandidateViewSkillDocker:
|
||||
retainedCommon++
|
||||
default:
|
||||
t.Fatalf("view retained an unexpected skill combination: %#v", view.DTO().Skills)
|
||||
}
|
||||
}
|
||||
if generalizedRare != 5 || retainedCommon != 5 {
|
||||
t.Fatalf("generalized rare/common counts = %d/%d, want 5/5", generalizedRare, retainedCommon)
|
||||
}
|
||||
|
||||
for _, cohortSize := range []int{1, 4} {
|
||||
small := make([]AnonymousCandidateView, 0, cohortSize)
|
||||
for range cohortSize {
|
||||
small = append(small, newView(CandidateViewSkillGo, uuid.New()))
|
||||
}
|
||||
result, err := GeneralizeAnonymousCandidateCohort(small)
|
||||
if err != nil {
|
||||
t.Fatalf("GeneralizeAnonymousCandidateCohort(size=%d) error = %v", cohortSize, err)
|
||||
}
|
||||
if len(result) != 0 {
|
||||
t.Fatalf("cohort size %d returned %d profiles after maximum generalization, want suppression", cohortSize, len(result))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func candidateViewTestPseudonym(t *testing.T, organizationID, candidateID uuid.UUID) string {
|
||||
t.Helper()
|
||||
key, err := NewCandidateViewPseudonymKey(bytes.Repeat([]byte("v"), minimumCandidateViewPseudonymKeyLen))
|
||||
if err != nil {
|
||||
t.Fatalf("NewCandidateViewPseudonymKey() error = %v", err)
|
||||
}
|
||||
pseudonym, err := key.ForOrganization(organizationID, candidateID)
|
||||
if err != nil {
|
||||
t.Fatalf("ForOrganization() error = %v", err)
|
||||
}
|
||||
return pseudonym
|
||||
}
|
||||
|
||||
func containsCandidateViewSkill(skills []CandidateViewSkillCode, wanted CandidateViewSkillCode) bool {
|
||||
for _, skill := range skills {
|
||||
if skill == wanted {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
+118
-24
@@ -1,6 +1,7 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
@@ -25,16 +26,19 @@ var (
|
||||
)
|
||||
|
||||
const (
|
||||
maxNeedTitleRunes = 200
|
||||
maxNeedSourceTextRunes = 10000
|
||||
maxNeedNameRunes = 100
|
||||
maxNeedTaskRunes = 300
|
||||
maxNeedQuoteRunes = 300
|
||||
maxNeedSkillItems = 30
|
||||
maxNeedTaskItems = 20
|
||||
maxNeedWorkFormats = 3
|
||||
MaxNeedSnapshotBytes = 262144
|
||||
redactedNeed = "[redacted need]"
|
||||
maxNeedTitleRunes = 200
|
||||
maxNeedSourceTextRunes = 10000
|
||||
maxNeedNameRunes = 100
|
||||
maxNeedTaskRunes = 300
|
||||
maxNeedQuoteRunes = 300
|
||||
maxNeedSkillItems = 30
|
||||
maxNeedTaskItems = 20
|
||||
maxNeedWorkFormats = 3
|
||||
MaxNeedRejectedSuggestions = 64
|
||||
MaxNeedSnapshotBytes = 262144
|
||||
MaxNeedJSONBTextHeadroom = 8192
|
||||
MaxNeedSnapshotStorageBytes = MaxNeedSnapshotBytes + MaxNeedJSONBTextHeadroom
|
||||
redactedNeed = "[redacted need]"
|
||||
)
|
||||
|
||||
// NeedValueStatus is the confirmation state of one need field.
|
||||
@@ -157,16 +161,39 @@ func EmptyNeedRequirements() NeedRequirements {
|
||||
// NeedSnapshot is the complete immutable business state of one need version.
|
||||
// Derived readiness and recommendations are computed separately.
|
||||
type NeedSnapshot struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
OrganizationID uuid.UUID `json:"organization_id"`
|
||||
VacancyID *uuid.UUID `json:"vacancy_id"`
|
||||
Title string `json:"title"`
|
||||
SourceText *string `json:"source_text"`
|
||||
Version int64 `json:"version"`
|
||||
RequirementsVersion int64 `json:"requirements_version"`
|
||||
Requirements NeedRequirements `json:"requirements"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
ID uuid.UUID `json:"id"`
|
||||
OrganizationID uuid.UUID `json:"organization_id"`
|
||||
VacancyID *uuid.UUID `json:"vacancy_id"`
|
||||
Title string `json:"title"`
|
||||
SourceText *string `json:"source_text"`
|
||||
Version int64 `json:"version"`
|
||||
RequirementsVersion int64 `json:"requirements_version"`
|
||||
Requirements NeedRequirements `json:"requirements"`
|
||||
RejectedSuggestions []NeedRejectedSuggestion `json:"rejected_suggestions"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// NeedRejectedSuggestionField groups extracted values for suppression after
|
||||
// an owner explicitly deletes them.
|
||||
type NeedRejectedSuggestionField string
|
||||
|
||||
const (
|
||||
NeedRejectedSpecialization NeedRejectedSuggestionField = "specialization"
|
||||
NeedRejectedGrade NeedRejectedSuggestionField = "grade"
|
||||
NeedRejectedSkills NeedRejectedSuggestionField = "skills"
|
||||
NeedRejectedTasks NeedRejectedSuggestionField = "tasks"
|
||||
NeedRejectedDomain NeedRejectedSuggestionField = "domain"
|
||||
NeedRejectedWorkFormats NeedRejectedSuggestionField = "work_formats"
|
||||
NeedRejectedLocation NeedRejectedSuggestionField = "location"
|
||||
NeedRejectedSalary NeedRejectedSuggestionField = "salary"
|
||||
)
|
||||
|
||||
// NeedRejectedSuggestion records an extracted proposal that an owner removed.
|
||||
// It is private need state and is never included in the public Need response.
|
||||
type NeedRejectedSuggestion struct {
|
||||
Field NeedRejectedSuggestionField `json:"field"`
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
// Need is one immutable version of an organization's hiring need. Snapshot
|
||||
@@ -190,6 +217,9 @@ func RestoreNeed(snapshot NeedSnapshot) (Need, error) {
|
||||
const location = "domain.RestoreNeed"
|
||||
snapshot.CreatedAt = canonicalNeedTime(snapshot.CreatedAt)
|
||||
snapshot.UpdatedAt = canonicalNeedTime(snapshot.UpdatedAt)
|
||||
if snapshot.RejectedSuggestions == nil {
|
||||
snapshot.RejectedSuggestions = []NeedRejectedSuggestion{}
|
||||
}
|
||||
if err := validateNeedSnapshot(location, snapshot); err != nil {
|
||||
return Need{}, err
|
||||
}
|
||||
@@ -453,6 +483,19 @@ func confirmedNeedTasks(tasks []NeedTask) []string {
|
||||
}
|
||||
|
||||
func validateNeedSnapshot(location string, snapshot NeedSnapshot) error {
|
||||
if err := validateNeedSnapshotMetadata(location, snapshot); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateNeedRejectedSuggestions(location, snapshot.RejectedSuggestions); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateNeedRequirements(location, snapshot.Version, snapshot.Requirements); err != nil {
|
||||
return err
|
||||
}
|
||||
return validateNeedSnapshotSize(location, snapshot)
|
||||
}
|
||||
|
||||
func validateNeedSnapshotMetadata(location string, snapshot NeedSnapshot) error {
|
||||
switch {
|
||||
case snapshot.ID == uuid.Nil || snapshot.OrganizationID == uuid.Nil:
|
||||
return invalidNeed(location, "need and organization IDs must be set")
|
||||
@@ -462,10 +505,60 @@ func validateNeedSnapshot(location string, snapshot NeedSnapshot) error {
|
||||
return invalidNeedField(location, "/title", "must be 1 to 200 characters without surrounding whitespace or line breaks")
|
||||
case snapshot.SourceText != nil && !validNeedLength(*snapshot.SourceText, maxNeedSourceTextRunes):
|
||||
return invalidNeedField(location, "/source_text", "must be 1 to 10000 characters")
|
||||
case snapshot.CreatedAt.IsZero() || snapshot.UpdatedAt.IsZero() || snapshot.UpdatedAt.Before(snapshot.CreatedAt):
|
||||
return invalidNeed(location, "timestamps must be set and ordered")
|
||||
case !validNeedTimestamp(snapshot.CreatedAt) || !validNeedTimestamp(snapshot.UpdatedAt) || snapshot.UpdatedAt.Before(snapshot.CreatedAt):
|
||||
return invalidNeed(location, "timestamps must be set, representable, and ordered")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateNeedSnapshotSize(location string, snapshot NeedSnapshot) error {
|
||||
encoded, err := json.Marshal(snapshot)
|
||||
if err != nil {
|
||||
return invalidNeed(location, "snapshot cannot be encoded")
|
||||
}
|
||||
if len(encoded) > MaxNeedSnapshotBytes {
|
||||
return invalidNeedField(location, "/rejected_suggestions", "combined need snapshot exceeds its storage bound")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validNeedTimestamp(value time.Time) bool {
|
||||
return !value.IsZero() && value.Year() >= 1 && value.Year() <= 9999
|
||||
}
|
||||
|
||||
func validateNeedRejectedSuggestions(location string, suggestions []NeedRejectedSuggestion) error {
|
||||
if suggestions == nil || len(suggestions) > MaxNeedRejectedSuggestions {
|
||||
return invalidNeedField(location, "/rejected_suggestions", "must be present and within its storage bound")
|
||||
}
|
||||
seen := make(map[string]struct{}, len(suggestions))
|
||||
for index, suggestion := range suggestions {
|
||||
pointer := "/rejected_suggestions/" + strconv.Itoa(index)
|
||||
if !knownNeedRejectedSuggestionField(suggestion.Field) || !validNeedLength(suggestion.Value, maxNeedTaskRunes) ||
|
||||
strings.TrimSpace(suggestion.Value) != suggestion.Value || strings.ToLower(suggestion.Value) != suggestion.Value {
|
||||
return invalidNeedField(location, pointer, "must have a normalized field and value")
|
||||
}
|
||||
for _, char := range suggestion.Value {
|
||||
if isNeedLineBreak(char) {
|
||||
return invalidNeedField(location, pointer+"/value", "must not contain line breaks")
|
||||
}
|
||||
}
|
||||
key := string(suggestion.Field) + "\x00" + suggestion.Value
|
||||
if _, exists := seen[key]; exists {
|
||||
return invalidNeedField(location, pointer, "duplicates a rejected suggestion")
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func knownNeedRejectedSuggestionField(field NeedRejectedSuggestionField) bool {
|
||||
switch field {
|
||||
case NeedRejectedSpecialization, NeedRejectedGrade, NeedRejectedSkills, NeedRejectedTasks,
|
||||
NeedRejectedDomain, NeedRejectedWorkFormats, NeedRejectedLocation, NeedRejectedSalary:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
return validateNeedRequirements(location, snapshot.Version, snapshot.Requirements)
|
||||
}
|
||||
|
||||
func validateNeedRequirements(location string, version int64, requirements NeedRequirements) error {
|
||||
@@ -718,7 +811,7 @@ func validNeedText(value string, maxRunes int) bool {
|
||||
}
|
||||
|
||||
func validNeedLength(value string, maxRunes int) bool {
|
||||
if !utf8.ValidString(value) {
|
||||
if !utf8.ValidString(value) || strings.ContainsRune(value, '\x00') {
|
||||
return false
|
||||
}
|
||||
length := utf8.RuneCountInString(value)
|
||||
@@ -743,6 +836,7 @@ func cloneNeedSnapshot(snapshot NeedSnapshot) NeedSnapshot {
|
||||
cloned.VacancyID = cloneNeedPointer(snapshot.VacancyID)
|
||||
cloned.SourceText = cloneNeedPointer(snapshot.SourceText)
|
||||
cloned.Requirements = cloneNeedRequirements(snapshot.Requirements)
|
||||
cloned.RejectedSuggestions = slices.Clone(snapshot.RejectedSuggestions)
|
||||
return cloned
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"slices"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
MaxNeedCreationResultBytes = 524288
|
||||
MaxNeedCreationResultStorageBytes = MaxNeedCreationResultBytes + MaxNeedJSONBTextHeadroom
|
||||
)
|
||||
|
||||
// NeedRecommendationStatus is the public state of category calculation.
|
||||
type NeedRecommendationStatus string
|
||||
|
||||
const (
|
||||
NeedRecommendationsComputed NeedRecommendationStatus = "computed"
|
||||
NeedRecommendationsPending NeedRecommendationStatus = "pending"
|
||||
NeedRecommendationsNotAvailable NeedRecommendationStatus = "not_available"
|
||||
)
|
||||
|
||||
type NeedMoneyStatus string
|
||||
|
||||
const (
|
||||
NeedMoneyComputed NeedMoneyStatus = "computed"
|
||||
NeedMoneyInsufficientData NeedMoneyStatus = "insufficient_data"
|
||||
NeedMoneyNoSalary NeedMoneyStatus = "no_salary"
|
||||
NeedMoneyWithheld NeedMoneyStatus = "withheld"
|
||||
)
|
||||
|
||||
type NeedSupplyBand string
|
||||
|
||||
const (
|
||||
NeedSupplyFewerThanFive NeedSupplyBand = "fewer_than_5"
|
||||
NeedSupplyFromFiveTo29 NeedSupplyBand = "from_5_to_29"
|
||||
NeedSupply30OrMore NeedSupplyBand = "30_or_more"
|
||||
)
|
||||
|
||||
// NeedSkillOverlap is the public category skill coverage component.
|
||||
type NeedSkillOverlap struct {
|
||||
Share float64 `json:"share"`
|
||||
CoveredSkills []string `json:"covered_skills"`
|
||||
UncoveredSkills []string `json:"uncovered_skills"`
|
||||
}
|
||||
|
||||
// NeedMoneyFit is the privacy-preserving public salary component.
|
||||
type NeedMoneyFit struct {
|
||||
Status NeedMoneyStatus `json:"status"`
|
||||
Share *float64 `json:"share"`
|
||||
}
|
||||
|
||||
// NeedCategoryRecommendation is one category and the public components used
|
||||
// to rank it. It contains no candidate-level salary information.
|
||||
type NeedCategoryRecommendation struct {
|
||||
Specialization SpecializationCode `json:"specialization"`
|
||||
Grade GradeCode `json:"grade"`
|
||||
Score *float64 `json:"score"`
|
||||
SkillOverlap NeedSkillOverlap `json:"skill_overlap"`
|
||||
Money NeedMoneyFit `json:"money"`
|
||||
Supply NeedSupplyBand `json:"supply"`
|
||||
}
|
||||
|
||||
// NeedCategoryRecommendations is the server's versioned public calculation
|
||||
// state for the confirmed requirements.
|
||||
type NeedCategoryRecommendations struct {
|
||||
Status NeedRecommendationStatus `json:"status"`
|
||||
RequirementsVersion int64 `json:"requirements_version"`
|
||||
PolicyVersion *int32 `json:"policy_version"`
|
||||
AlgorithmVersion *string `json:"algorithm_version"`
|
||||
ComputedAt *time.Time `json:"computed_at"`
|
||||
Categories []NeedCategoryRecommendation `json:"categories"`
|
||||
}
|
||||
|
||||
// NeedResponseSnapshot is an immutable public result captured when an
|
||||
// idempotent create succeeds. Replay uses this snapshot instead of reading a
|
||||
// later need version or recomputing readiness or recommendations.
|
||||
type NeedResponseSnapshot struct {
|
||||
Need NeedSnapshot `json:"need"`
|
||||
Readiness NeedReadinessReport `json:"readiness"`
|
||||
Recommendations NeedCategoryRecommendations `json:"recommendations"`
|
||||
}
|
||||
|
||||
// NeedResponseSnapshot returns the current public result without exposing
|
||||
// private rejected suggestion state to the response mapper.
|
||||
func (need Need) ResponseSnapshot() NeedResponseSnapshot {
|
||||
return NeedResponseSnapshot{
|
||||
Need: need.Snapshot(), Readiness: need.Readiness(), Recommendations: need.Recommendations(),
|
||||
}
|
||||
}
|
||||
|
||||
// Recommendations returns the honest current MVP state. It never fabricates
|
||||
// a computed category result while the calculator is unavailable.
|
||||
func (need Need) Recommendations() NeedCategoryRecommendations {
|
||||
status := NeedRecommendationsNotAvailable
|
||||
if hasConfirmedNeedSkill(need.snapshot.Requirements.RequiredSkills) || hasConfirmedNeedSkill(need.snapshot.Requirements.DesiredSkills) {
|
||||
status = NeedRecommendationsPending
|
||||
}
|
||||
return NeedCategoryRecommendations{
|
||||
Status: status, RequirementsVersion: need.RequirementsVersion(),
|
||||
Categories: []NeedCategoryRecommendation{},
|
||||
}
|
||||
}
|
||||
|
||||
// RestoreNeedResponseSnapshot validates and defensively copies an immutable
|
||||
// create result read from storage.
|
||||
func RestoreNeedResponseSnapshot(snapshot NeedResponseSnapshot) (NeedResponseSnapshot, error) {
|
||||
const location = "domain.RestoreNeedResponseSnapshot"
|
||||
need, err := RestoreNeed(snapshot.Need)
|
||||
if err != nil {
|
||||
return NeedResponseSnapshot{}, fmt.Errorf("%s - restore need: %w", location, err)
|
||||
}
|
||||
if err := validateNeedReadiness(location, snapshot.Readiness); err != nil {
|
||||
return NeedResponseSnapshot{}, err
|
||||
}
|
||||
if err := validateNeedRecommendations(location, need, snapshot.Recommendations); err != nil {
|
||||
return NeedResponseSnapshot{}, err
|
||||
}
|
||||
snapshot.Need = need.Snapshot()
|
||||
snapshot.Readiness = cloneNeedReadiness(snapshot.Readiness)
|
||||
snapshot.Recommendations = cloneNeedRecommendations(snapshot.Recommendations)
|
||||
return snapshot, nil
|
||||
}
|
||||
|
||||
func validateNeedReadiness(location string, readiness NeedReadinessReport) error {
|
||||
if readiness.MissingFields == nil || len(readiness.MissingFields) > 9 {
|
||||
return invalidNeed(location, "stored readiness fields are outside their bound")
|
||||
}
|
||||
if readiness.Status != NeedReadinessComplete && readiness.Status != NeedReadinessIncomplete {
|
||||
return invalidNeed(location, "stored readiness status is unknown")
|
||||
}
|
||||
seen := make(map[NeedMissingFieldName]struct{}, len(readiness.MissingFields))
|
||||
for _, missing := range readiness.MissingFields {
|
||||
if !knownNeedMissingField(missing.Field) || (missing.Reason != NeedMissingUnknown && missing.Reason != NeedMissingUnconfirmed) || !validNeedText(missing.Question, 300) {
|
||||
return invalidNeed(location, "stored readiness field is invalid")
|
||||
}
|
||||
if _, exists := seen[missing.Field]; exists {
|
||||
return invalidNeed(location, "stored readiness field is duplicated")
|
||||
}
|
||||
seen[missing.Field] = struct{}{}
|
||||
}
|
||||
if (readiness.Status == NeedReadinessComplete) != (len(readiness.MissingFields) == 0) {
|
||||
return invalidNeed(location, "stored readiness status does not match its fields")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func knownNeedMissingField(field NeedMissingFieldName) bool {
|
||||
switch field {
|
||||
case NeedMissingSpecialization, NeedMissingGrade, NeedMissingRequiredSkills, NeedMissingWorkFormats, NeedMissingLocation, NeedMissingSalary:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func validateNeedRecommendations(location string, need Need, recommendations NeedCategoryRecommendations) error {
|
||||
if recommendations.RequirementsVersion != need.RequirementsVersion() || recommendations.Categories == nil || len(recommendations.Categories) > 10 {
|
||||
return invalidNeed(location, "stored recommendation snapshot is outside its bound")
|
||||
}
|
||||
hasConfirmedSkill := hasConfirmedNeedSkill(need.snapshot.Requirements.RequiredSkills) || hasConfirmedNeedSkill(need.snapshot.Requirements.DesiredSkills)
|
||||
switch recommendations.Status {
|
||||
case NeedRecommendationsPending, NeedRecommendationsNotAvailable:
|
||||
return validateUncalculatedRecommendations(location, recommendations, hasConfirmedSkill)
|
||||
case NeedRecommendationsComputed:
|
||||
return validateComputedRecommendations(location, recommendations, hasConfirmedSkill)
|
||||
default:
|
||||
return invalidNeed(location, "stored recommendation status is unknown")
|
||||
}
|
||||
}
|
||||
|
||||
func validateUncalculatedRecommendations(location string, recommendations NeedCategoryRecommendations, hasConfirmedSkill bool) error {
|
||||
shouldBePending := recommendations.Status == NeedRecommendationsPending
|
||||
if recommendations.PolicyVersion != nil || recommendations.AlgorithmVersion != nil || recommendations.ComputedAt != nil || len(recommendations.Categories) != 0 ||
|
||||
shouldBePending != hasConfirmedSkill {
|
||||
return invalidNeed(location, "uncalculated recommendations must not contain calculation data")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateComputedRecommendations(location string, recommendations NeedCategoryRecommendations, hasConfirmedSkill bool) error {
|
||||
if !hasConfirmedSkill || recommendations.PolicyVersion == nil || *recommendations.PolicyVersion < 1 || recommendations.AlgorithmVersion == nil ||
|
||||
!validNeedVersionLabel(*recommendations.AlgorithmVersion) || recommendations.ComputedAt == nil || !validNeedTimestamp(*recommendations.ComputedAt) {
|
||||
return invalidNeed(location, "computed recommendations require a valid policy, algorithm, and timestamp")
|
||||
}
|
||||
return validateNeedRecommendationCategories(location, recommendations.Categories)
|
||||
}
|
||||
|
||||
func validateNeedRecommendationCategories(location string, categories []NeedCategoryRecommendation) error {
|
||||
seen := make(map[string]struct{}, len(categories))
|
||||
for _, category := range categories {
|
||||
if !category.Specialization.IsKnown() || !category.Grade.IsKnown() || !validOptionalNeedScore(category.Score) || !validOptionalNeedScore(&category.SkillOverlap.Share) ||
|
||||
category.SkillOverlap.CoveredSkills == nil || category.SkillOverlap.UncoveredSkills == nil || len(category.SkillOverlap.CoveredSkills) > 60 || len(category.SkillOverlap.UncoveredSkills) > 60 ||
|
||||
!validNeedMoneyFit(category.Money) || !validNeedSupplyBand(category.Supply) {
|
||||
return invalidNeed(location, "stored recommendation category is invalid")
|
||||
}
|
||||
key := string(category.Specialization) + "\x00" + string(category.Grade)
|
||||
if _, exists := seen[key]; exists {
|
||||
return invalidNeed(location, "stored recommendation category is duplicated")
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
for _, skill := range append(slices.Clone(category.SkillOverlap.CoveredSkills), category.SkillOverlap.UncoveredSkills...) {
|
||||
if !validNeedText(skill, maxNeedNameRunes) {
|
||||
return invalidNeed(location, "stored recommendation skill is invalid")
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validOptionalNeedScore(value *float64) bool {
|
||||
return value == nil || !math.IsNaN(*value) && !math.IsInf(*value, 0) && *value >= 0 && *value <= 1
|
||||
}
|
||||
|
||||
func validNeedMoneyFit(value NeedMoneyFit) bool {
|
||||
switch value.Status {
|
||||
case NeedMoneyComputed:
|
||||
if value.Share == nil || !validOptionalNeedScore(value.Share) {
|
||||
return false
|
||||
}
|
||||
case NeedMoneyInsufficientData, NeedMoneyNoSalary, NeedMoneyWithheld:
|
||||
if value.Share != nil {
|
||||
return false
|
||||
}
|
||||
default:
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func validNeedSupplyBand(value NeedSupplyBand) bool {
|
||||
return value == NeedSupplyFewerThanFive || value == NeedSupplyFromFiveTo29 || value == NeedSupply30OrMore
|
||||
}
|
||||
|
||||
func cloneNeedReadiness(readiness NeedReadinessReport) NeedReadinessReport {
|
||||
readiness.MissingFields = slices.Clone(readiness.MissingFields)
|
||||
return readiness
|
||||
}
|
||||
|
||||
func cloneNeedRecommendations(recommendations NeedCategoryRecommendations) NeedCategoryRecommendations {
|
||||
cloned := recommendations
|
||||
if recommendations.PolicyVersion != nil {
|
||||
value := *recommendations.PolicyVersion
|
||||
cloned.PolicyVersion = &value
|
||||
}
|
||||
if recommendations.AlgorithmVersion != nil {
|
||||
value := *recommendations.AlgorithmVersion
|
||||
cloned.AlgorithmVersion = &value
|
||||
}
|
||||
if recommendations.ComputedAt != nil {
|
||||
value := canonicalNeedTime(*recommendations.ComputedAt)
|
||||
cloned.ComputedAt = &value
|
||||
}
|
||||
cloned.Categories = slices.Clone(recommendations.Categories)
|
||||
for index := range cloned.Categories {
|
||||
cloned.Categories[index].Score = cloneNeedPointer(recommendations.Categories[index].Score)
|
||||
cloned.Categories[index].SkillOverlap.CoveredSkills = slices.Clone(recommendations.Categories[index].SkillOverlap.CoveredSkills)
|
||||
cloned.Categories[index].SkillOverlap.UncoveredSkills = slices.Clone(recommendations.Categories[index].SkillOverlap.UncoveredSkills)
|
||||
cloned.Categories[index].Money.Share = cloneNeedPointer(recommendations.Categories[index].Money.Share)
|
||||
}
|
||||
return cloned
|
||||
}
|
||||
|
||||
func (snapshot NeedResponseSnapshot) String() string { return redactedNeed }
|
||||
func (snapshot NeedResponseSnapshot) GoString() string { return redactedNeed }
|
||||
@@ -0,0 +1,75 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestNeedResponseSnapshotPreservesReadinessAndRecommendations(t *testing.T) {
|
||||
snapshot := validNeedSnapshot()
|
||||
need, err := NewNeed(snapshot)
|
||||
if err != nil {
|
||||
t.Fatalf("NewNeed() error = %v", err)
|
||||
}
|
||||
response := need.ResponseSnapshot()
|
||||
if response.Recommendations.Status != NeedRecommendationsNotAvailable || response.Recommendations.Categories == nil {
|
||||
t.Fatalf("recommendations = %+v, want honest not_available state", response.Recommendations)
|
||||
}
|
||||
restored, err := RestoreNeedResponseSnapshot(response)
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreNeedResponseSnapshot() error = %v", err)
|
||||
}
|
||||
if restored.Readiness.Status != response.Readiness.Status || restored.Recommendations.Status != response.Recommendations.Status || restored.Need.ID != need.ID() {
|
||||
t.Fatalf("restored response snapshot = %+v, want original public result", restored)
|
||||
}
|
||||
response.Readiness.MissingFields[0].Question = "changed"
|
||||
if restored.Readiness.MissingFields[0].Question == "changed" {
|
||||
t.Fatal("restored readiness shares the caller's slice")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNeedResponseSnapshotRequiresStatusConsistentWithConfirmedSkills(t *testing.T) {
|
||||
snapshot := validNeedSnapshot()
|
||||
skill := NeedSkill{Name: "Go", Status: NeedItemConfirmed, Source: *manualNeedSource()}
|
||||
snapshot.Requirements.RequiredSkills = []NeedSkill{skill}
|
||||
need, err := NewNeed(snapshot)
|
||||
if err != nil {
|
||||
t.Fatalf("NewNeed() error = %v", err)
|
||||
}
|
||||
response := need.ResponseSnapshot()
|
||||
if response.Recommendations.Status != NeedRecommendationsPending {
|
||||
t.Fatalf("recommendations = %+v, want pending while calculation is unavailable", response.Recommendations)
|
||||
}
|
||||
response.Recommendations.Status = NeedRecommendationsNotAvailable
|
||||
if _, err := RestoreNeedResponseSnapshot(response); err == nil {
|
||||
t.Fatal("RestoreNeedResponseSnapshot() accepted not_available despite a confirmed skill")
|
||||
}
|
||||
response = need.ResponseSnapshot()
|
||||
response.Recommendations.Status = NeedRecommendationsComputed
|
||||
response.Recommendations.PolicyVersion = needPointer(int32(1))
|
||||
response.Recommendations.AlgorithmVersion = needPointer("category.1")
|
||||
computedAt := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
|
||||
response.Recommendations.ComputedAt = &computedAt
|
||||
response.Recommendations.Categories = []NeedCategoryRecommendation{{
|
||||
Specialization: SpecializationBackend, Grade: GradeJunior,
|
||||
Score: needPointer(0.5), SkillOverlap: NeedSkillOverlap{Share: 1, CoveredSkills: []string{"Go"}, UncoveredSkills: []string{}},
|
||||
Money: NeedMoneyFit{Status: NeedMoneyNoSalary}, Supply: NeedSupplyFromFiveTo29,
|
||||
}}
|
||||
restored, err := RestoreNeedResponseSnapshot(response)
|
||||
if err != nil || restored.Recommendations.Status != NeedRecommendationsComputed {
|
||||
t.Fatalf("restore computed creation snapshot = %+v, error %v", restored.Recommendations, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNeedResponseSnapshotRejectsMalformedCalculationMetadata(t *testing.T) {
|
||||
need, err := NewNeed(validNeedSnapshot())
|
||||
if err != nil {
|
||||
t.Fatalf("NewNeed() error = %v", err)
|
||||
}
|
||||
response := need.ResponseSnapshot()
|
||||
response.Recommendations.Status = NeedRecommendationsPending
|
||||
response.Recommendations.PolicyVersion = needPointer(int32(1))
|
||||
if _, err := RestoreNeedResponseSnapshot(response); err == nil {
|
||||
t.Fatal("RestoreNeedResponseSnapshot() accepted calculation metadata on pending recommendations")
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
@@ -53,6 +54,15 @@ func TestNewNeedCanonicalizesTimestampsToStoragePrecision(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestNeedRejectsTimestampsOutsideContractDateTimeRange(t *testing.T) {
|
||||
snapshot := validNeedSnapshot()
|
||||
snapshot.CreatedAt = time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC)
|
||||
snapshot.UpdatedAt = snapshot.CreatedAt
|
||||
if _, err := NewNeed(snapshot); !errors.Is(err, ErrInvalidNeed) {
|
||||
t.Fatalf("NewNeed(year 10000) error = %v, want ErrInvalidNeed", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNeedReadinessRequiresLocationOnlyForConfirmedOfficeOrHybrid(t *testing.T) {
|
||||
snapshot := validNeedSnapshot()
|
||||
formats := []NeedWorkFormat{NeedWorkFormatRemote}
|
||||
@@ -197,6 +207,104 @@ func TestNeedSnapshotIsDefensiveAndRedacted(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestNeedRejectedSuggestionsArePrivateDefensiveAndBounded(t *testing.T) {
|
||||
snapshot := validNeedSnapshot()
|
||||
snapshot.RejectedSuggestions = []NeedRejectedSuggestion{{Field: NeedRejectedSkills, Value: "postgresql"}}
|
||||
need, err := NewNeed(snapshot)
|
||||
if err != nil {
|
||||
t.Fatalf("NewNeed() error = %v", err)
|
||||
}
|
||||
copied := need.Snapshot()
|
||||
copied.RejectedSuggestions[0].Value = "changed"
|
||||
if got := need.Snapshot().RejectedSuggestions[0].Value; got != "postgresql" {
|
||||
t.Fatalf("suppressed value changed through snapshot copy: %q", got)
|
||||
}
|
||||
if printed := fmt.Sprintf("%+v", need); strings.Contains(printed, "postgresql") {
|
||||
t.Fatalf("need formatting exposed a suppressed suggestion: %q", printed)
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
suggestions []NeedRejectedSuggestion
|
||||
}{
|
||||
{name: "unknown field", suggestions: []NeedRejectedSuggestion{{Field: "role", Value: "owner"}}},
|
||||
{name: "empty value", suggestions: []NeedRejectedSuggestion{{Field: NeedRejectedSkills}}},
|
||||
{name: "not normalized", suggestions: []NeedRejectedSuggestion{{Field: NeedRejectedSkills, Value: "PostgreSQL"}}},
|
||||
{name: "duplicate", suggestions: []NeedRejectedSuggestion{
|
||||
{Field: NeedRejectedSkills, Value: "postgresql"}, {Field: NeedRejectedSkills, Value: "postgresql"},
|
||||
}},
|
||||
{name: "too many", suggestions: tooManyNeedRejectedSuggestions()},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
invalid := validNeedSnapshot()
|
||||
invalid.RejectedSuggestions = test.suggestions
|
||||
if _, err := NewNeed(invalid); !errors.Is(err, ErrInvalidNeed) {
|
||||
t.Fatalf("NewNeed() error = %v, want ErrInvalidNeed", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNeedRejectsSnapshotThatExceedsSerializedStorageBound(t *testing.T) {
|
||||
snapshot := validNeedSnapshot()
|
||||
controlText := strings.Repeat("\x01", maxNeedSourceTextRunes)
|
||||
snapshot.SourceText = &controlText
|
||||
snapshot.RejectedSuggestions = make([]NeedRejectedSuggestion, MaxNeedRejectedSuggestions)
|
||||
for index := range snapshot.RejectedSuggestions {
|
||||
value := strings.Repeat("\x01", maxNeedTaskRunes-3) + fmt.Sprintf("%03d", index)
|
||||
snapshot.RejectedSuggestions[index] = NeedRejectedSuggestion{Field: NeedRejectedTasks, Value: value}
|
||||
}
|
||||
for index := 0; index < maxNeedSkillItems; index++ {
|
||||
quote := strings.Repeat("\x01", maxNeedQuoteRunes)
|
||||
snapshot.Requirements.RequiredSkills = append(snapshot.Requirements.RequiredSkills, NeedSkill{
|
||||
Name: fmt.Sprintf("skill-%02d", index), Status: NeedItemExtracted,
|
||||
Source: NeedValueSource{Origin: NeedValueExtractedFromText, Quote: "e,
|
||||
ExtractedInVersion: needPointer(int64(1)), ExtractionVersion: needPointer("rules.1")},
|
||||
})
|
||||
}
|
||||
for index := 0; index < maxNeedSkillItems; index++ {
|
||||
quote := strings.Repeat("\x01", maxNeedQuoteRunes)
|
||||
snapshot.Requirements.DesiredSkills = append(snapshot.Requirements.DesiredSkills, NeedSkill{
|
||||
Name: fmt.Sprintf("other-%02d", index), Status: NeedItemExtracted,
|
||||
Source: NeedValueSource{Origin: NeedValueExtractedFromText, Quote: "e,
|
||||
ExtractedInVersion: needPointer(int64(1)), ExtractionVersion: needPointer("rules.1")},
|
||||
})
|
||||
}
|
||||
|
||||
_, err := NewNeed(snapshot)
|
||||
if !errors.Is(err, ErrInvalidNeed) || !strings.Contains(fmt.Sprint(err), "/rejected_suggestions") {
|
||||
t.Fatalf("NewNeed(oversized snapshot) error = %v, want bounded snapshot validation error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRestoreNeedAcceptsLegacySnapshotWithoutRejectedSuggestions(t *testing.T) {
|
||||
encoded, err := json.Marshal(validNeedSnapshot())
|
||||
if err != nil {
|
||||
t.Fatalf("marshal snapshot: %v", err)
|
||||
}
|
||||
var fields map[string]json.RawMessage
|
||||
if err := json.Unmarshal(encoded, &fields); err != nil {
|
||||
t.Fatalf("decode snapshot fields: %v", err)
|
||||
}
|
||||
delete(fields, "rejected_suggestions")
|
||||
legacy, err := json.Marshal(fields)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal legacy snapshot: %v", err)
|
||||
}
|
||||
var snapshot NeedSnapshot
|
||||
if err := json.Unmarshal(legacy, &snapshot); err != nil {
|
||||
t.Fatalf("decode legacy snapshot: %v", err)
|
||||
}
|
||||
need, err := RestoreNeed(snapshot)
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreNeed(legacy) error = %v", err)
|
||||
}
|
||||
if got := need.Snapshot().RejectedSuggestions; got == nil || len(got) != 0 {
|
||||
t.Fatalf("legacy rejected suggestions = %#v, want an empty list", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNeedRestoresContractProvenanceAndRejectsInvalidValues(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -236,18 +344,24 @@ func TestNeedRestoresContractProvenanceAndRejectsInvalidValues(t *testing.T) {
|
||||
|
||||
func TestNeedRejectsInvalidUTF8InContractText(t *testing.T) {
|
||||
invalid := string([]byte{0xff})
|
||||
nul := "role\x00name"
|
||||
tests := []struct {
|
||||
name string
|
||||
change func(*NeedSnapshot)
|
||||
}{
|
||||
{name: "title", change: func(snapshot *NeedSnapshot) { snapshot.Title = invalid }},
|
||||
{name: "source text", change: func(snapshot *NeedSnapshot) { snapshot.SourceText = &invalid }},
|
||||
{name: "title with NUL", change: func(snapshot *NeedSnapshot) { snapshot.Title = nul }},
|
||||
{name: "source text with NUL", change: func(snapshot *NeedSnapshot) { snapshot.SourceText = &nul }},
|
||||
{name: "provenance quote", change: func(snapshot *NeedSnapshot) {
|
||||
snapshot.Requirements.Specialization = NeedValue[SpecializationCode]{
|
||||
Status: NeedValueExtracted, Value: needPointer(SpecializationBackend), Source: textNeedSource(1),
|
||||
}
|
||||
snapshot.Requirements.Specialization.Source.Quote = &invalid
|
||||
}},
|
||||
{name: "skill name with NUL", change: func(snapshot *NeedSnapshot) {
|
||||
snapshot.Requirements.RequiredSkills = []NeedSkill{{Name: nul, Status: NeedItemConfirmed, Source: *manualNeedSource()}}
|
||||
}},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
@@ -360,6 +474,14 @@ func confirmedNeedValue[T any](value T, source *NeedValueSource) NeedValue[T] {
|
||||
|
||||
func needPointer[T any](value T) *T { return &value }
|
||||
|
||||
func tooManyNeedRejectedSuggestions() []NeedRejectedSuggestion {
|
||||
suggestions := make([]NeedRejectedSuggestion, MaxNeedRejectedSuggestions+1)
|
||||
for index := range suggestions {
|
||||
suggestions[index] = NeedRejectedSuggestion{Field: NeedRejectedTasks, Value: fmt.Sprintf("task-%d", index)}
|
||||
}
|
||||
return suggestions
|
||||
}
|
||||
|
||||
func containsNeedField(fields []NeedMissingField, field NeedMissingFieldName) bool {
|
||||
for _, candidate := range fields {
|
||||
if candidate.Field == field {
|
||||
|
||||
@@ -62,6 +62,12 @@ const (
|
||||
maxSameGradeRetryInterval = CalendarDays(365)
|
||||
maxAssessmentAttemptsPerWindow = 20
|
||||
maxAssessmentAttemptWindow = CalendarDays(730)
|
||||
maxAssessmentLifetime = Hours(30 * 24)
|
||||
maxAssessmentIdleTimeoutSeconds = 24 * 60 * 60
|
||||
maxAssessmentSessions = 10
|
||||
minAssessmentExpressSeconds = 180
|
||||
maxAssessmentExpressSeconds = 300
|
||||
maxAssessmentExpressItems = 20
|
||||
maxPromotionInterval = CalendarDays(730)
|
||||
maxScoredItems = 200
|
||||
maxSeedItems = 20
|
||||
@@ -84,6 +90,9 @@ type ProductPolicy struct {
|
||||
Assessment AssessmentPolicy
|
||||
Identity IdentityPolicy
|
||||
SearchStatus SearchStatusPolicy
|
||||
// Support is absent only in immutable policy documents that predate the
|
||||
// support section. New demo policies should set it explicitly.
|
||||
Support *SupportPolicy
|
||||
}
|
||||
|
||||
// Validate checks every section. A zero value is never valid, so a section
|
||||
@@ -100,6 +109,11 @@ func (policy ProductPolicy) Validate() error {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if policy.Support != nil {
|
||||
if err := policy.Support.Validate(); err != nil {
|
||||
return fmt.Errorf("ProductPolicy.Validate - support section: %w: %w", ErrInvalidPolicy, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -108,6 +122,18 @@ func (policy ProductPolicy) Validate() error {
|
||||
func (policy ProductPolicy) clone() ProductPolicy {
|
||||
copied := policy
|
||||
copied.Invitations.ResponseDeadlineOptions = slices.Clone(policy.Invitations.ResponseDeadlineOptions)
|
||||
if attempt := policy.Assessment.Attempt; attempt != nil {
|
||||
attemptCopy := *attempt
|
||||
copied.Assessment.Attempt = &attemptCopy
|
||||
}
|
||||
if training := policy.Assessment.Training; training != nil {
|
||||
trainingCopy := *training
|
||||
copied.Assessment.Training = &trainingCopy
|
||||
}
|
||||
if support := policy.Support; support != nil {
|
||||
supportCopy := *support
|
||||
copied.Support = &supportCopy
|
||||
}
|
||||
return copied
|
||||
}
|
||||
|
||||
@@ -276,10 +302,9 @@ type AssessmentPolicy struct {
|
||||
// SameGradeRetryAfter is the pause before another attempt at the same
|
||||
// grade.
|
||||
SameGradeRetryAfter CalendarDays
|
||||
// MaxAttemptsPerWindow limits attempts in any AttemptWindow. Whether the
|
||||
// limit counts per grade, per specialty, or across all assessments of a
|
||||
// candidate is an open question for attempt accounting;
|
||||
// the policy stores only the number.
|
||||
// MaxAttemptsPerWindow limits a candidate's root attempts across all
|
||||
// specializations in any AttemptWindow. Corrective and training attempts
|
||||
// do not reserve another root slot.
|
||||
MaxAttemptsPerWindow int32
|
||||
AttemptWindow CalendarDays
|
||||
// PromotionMinInterval is the minimum time between grade promotions.
|
||||
@@ -292,6 +317,92 @@ type AssessmentPolicy struct {
|
||||
// scored attempt.
|
||||
PracticeRequired bool
|
||||
StopRule AssessmentStopRule
|
||||
// Attempt is nil in legacy policy documents that predate the attempt
|
||||
// contract. Attempt creation must fail closed when it is nil; readers keep
|
||||
// those policy versions available for records created under them.
|
||||
Attempt *AssessmentAttemptPolicy
|
||||
// Training is an explicit non-qualification policy section. It is nil in
|
||||
// immutable legacy policies and never inherits real assessment settings.
|
||||
Training *AssessmentTrainingPolicy
|
||||
}
|
||||
|
||||
// AssessmentAttemptPolicy holds the versioned execution limits for a newly
|
||||
// started attempt. It is optional only for immutable legacy policy versions;
|
||||
// callers cannot infer missing values from defaults.
|
||||
type AssessmentAttemptPolicy struct {
|
||||
Lifetime Hours
|
||||
ChainDeadline Hours
|
||||
MaxSessions int32
|
||||
IdleTimeoutSeconds int32
|
||||
RealMode AssessmentRealMode
|
||||
BasicPassMark BasisPoints
|
||||
}
|
||||
|
||||
// AssessmentTrainingPolicy holds settings for a separate training run. Its
|
||||
// bank source is pinned independently from real category openings.
|
||||
type AssessmentTrainingPolicy struct {
|
||||
DemoExpressDurationSeconds int32
|
||||
DemoExpressItemCount int32
|
||||
MaxSessions int32
|
||||
IdleTimeoutSeconds int32
|
||||
}
|
||||
|
||||
// AssessmentRealMode is a server-selected mode for a real assessment.
|
||||
type AssessmentRealMode string
|
||||
|
||||
const (
|
||||
AssessmentRealModeDemoBasic AssessmentRealMode = "demo_basic"
|
||||
AssessmentRealModeAdaptive AssessmentRealMode = "adaptive"
|
||||
)
|
||||
|
||||
func (policy AssessmentAttemptPolicy) validate(calibration AssessmentCalibration) error {
|
||||
const location = "AssessmentAttemptPolicy.Validate"
|
||||
if err := firstError(
|
||||
checkRange(location, "assessment.attempt.lifetime_hours", policy.Lifetime, 1, maxAssessmentLifetime),
|
||||
checkRange(location, "assessment.attempt.chain_deadline_hours", policy.ChainDeadline, 1, maxAssessmentLifetime),
|
||||
checkRange(location, "assessment.attempt.max_sessions", policy.MaxSessions, 1, maxAssessmentSessions),
|
||||
checkRange(location, "assessment.attempt.idle_timeout_seconds", policy.IdleTimeoutSeconds, 60, maxAssessmentIdleTimeoutSeconds),
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
if policy.ChainDeadline > policy.Lifetime {
|
||||
return invalidPolicy(location, "assessment.attempt.chain_deadline_hours must not exceed lifetime_hours")
|
||||
}
|
||||
if int64(policy.IdleTimeoutSeconds) > int64(policy.Lifetime)*60*60 {
|
||||
return invalidPolicy(location, "assessment.attempt.idle_timeout_seconds must not exceed lifetime_hours")
|
||||
}
|
||||
switch policy.RealMode {
|
||||
case AssessmentRealModeDemoBasic:
|
||||
if err := checkRange(location, "assessment.attempt.basic_pass_mark_bp", policy.BasicPassMark, 1, basisPointsPerUnit); err != nil {
|
||||
return err
|
||||
}
|
||||
case AssessmentRealModeAdaptive:
|
||||
if policy.BasicPassMark != 0 {
|
||||
return invalidPolicy(location, "assessment.attempt.basic_pass_mark_bp must be zero in adaptive mode")
|
||||
}
|
||||
if calibration != AssessmentCalibrationCalibrated {
|
||||
return invalidPolicy(location, "adaptive assessment mode requires a calibrated assessment policy")
|
||||
}
|
||||
default:
|
||||
return invalidPolicy(location, "assessment.attempt.real_mode must be demo_basic or adaptive")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (policy AssessmentTrainingPolicy) validate() error {
|
||||
const location = "AssessmentTrainingPolicy.Validate"
|
||||
if err := firstError(
|
||||
checkRange(location, "assessment.training.demo_express_duration_seconds", policy.DemoExpressDurationSeconds, minAssessmentExpressSeconds, maxAssessmentExpressSeconds),
|
||||
checkRange(location, "assessment.training.demo_express_item_count", policy.DemoExpressItemCount, 1, maxAssessmentExpressItems),
|
||||
checkRange(location, "assessment.training.max_sessions", policy.MaxSessions, 1, maxAssessmentSessions),
|
||||
checkRange(location, "assessment.training.idle_timeout_seconds", policy.IdleTimeoutSeconds, 60, maxAssessmentIdleTimeoutSeconds),
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
if policy.IdleTimeoutSeconds > policy.DemoExpressDurationSeconds {
|
||||
return invalidPolicy(location, "assessment.training.idle_timeout_seconds must not exceed demo_express_duration_seconds")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// AssessmentStopRule ends an adaptive attempt. After MinScoredItems the
|
||||
@@ -328,7 +439,20 @@ func (policy AssessmentPolicy) Validate() error {
|
||||
if policy.HighStrengthThreshold < policy.ConfirmationThreshold {
|
||||
return invalidPolicy(location, "assessment.high_strength_threshold_bp must not be below the confirmation threshold")
|
||||
}
|
||||
return policy.StopRule.validate(location, policy.ConfirmationThreshold)
|
||||
if err := policy.StopRule.validate(location, policy.ConfirmationThreshold); err != nil {
|
||||
return err
|
||||
}
|
||||
if policy.Attempt != nil {
|
||||
if err := policy.Attempt.validate(policy.Calibration); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if policy.Training != nil {
|
||||
if err := policy.Training.validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (rule AssessmentStopRule) validate(location string, confirmation BasisPoints) error {
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLegacyPolicyDocumentRestoresWithoutAttemptSettings(t *testing.T) {
|
||||
policy, err := decodeProductPolicy([]byte(demoProductPolicyV1Document))
|
||||
if err != nil {
|
||||
t.Fatalf("decodeProductPolicy(V1) error = %v", err)
|
||||
}
|
||||
if policy.Assessment.Attempt != nil {
|
||||
t.Fatal("legacy V1 policy acquired implicit attempt settings")
|
||||
}
|
||||
encoded, _, err := encodeProductPolicy(policy)
|
||||
if err != nil {
|
||||
t.Fatalf("encodeProductPolicy(V1) error = %v", err)
|
||||
}
|
||||
if !bytes.Equal(encoded, []byte(demoProductPolicyV1Document)) {
|
||||
t.Fatalf("legacy V1 canonical document changed:\n%s\nwant:\n%s", encoded, demoProductPolicyV1Document)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDemoProductPolicyV2PinsAttemptSettings(t *testing.T) {
|
||||
policy := DemoProductPolicyV2()
|
||||
if err := policy.Validate(); err != nil {
|
||||
t.Fatalf("DemoProductPolicyV2().Validate() error = %v", err)
|
||||
}
|
||||
got := policy.Assessment.Attempt
|
||||
if got == nil {
|
||||
t.Fatal("DemoProductPolicyV2() has no attempt settings")
|
||||
}
|
||||
if got.Lifetime != 72 || got.ChainDeadline != 72 || got.MaxSessions != 2 ||
|
||||
got.IdleTimeoutSeconds != 1800 || got.RealMode != AssessmentRealModeDemoBasic ||
|
||||
got.BasicPassMark != 8000 {
|
||||
t.Fatalf("DemoProductPolicyV2().Assessment.Attempt = %+v, want explicitly configured values", got)
|
||||
}
|
||||
if training := policy.Assessment.Training; training == nil || training.DemoExpressDurationSeconds != 240 || training.DemoExpressItemCount != 3 {
|
||||
t.Fatalf("DemoProductPolicyV2().Assessment.Training = %+v, want explicit duration and item count", training)
|
||||
}
|
||||
|
||||
draft, err := NewPolicyVersionDraft(NewPolicyVersionDraftInput{
|
||||
Key: ProductPolicyKey, Kind: PolicyKindDemo, Author: DemoPolicySeedAuthor, Policy: policy,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewPolicyVersionDraft(V2) error = %v", err)
|
||||
}
|
||||
decoded, err := decodeProductPolicy(draft.Document())
|
||||
if err != nil {
|
||||
t.Fatalf("decodeProductPolicy(V2) error = %v", err)
|
||||
}
|
||||
if decoded.Assessment.Attempt == nil || *decoded.Assessment.Attempt != *got ||
|
||||
decoded.Assessment.Training == nil || *decoded.Assessment.Training != *policy.Assessment.Training {
|
||||
t.Fatalf("decoded attempt policy = %+v, want %+v", decoded.Assessment.Attempt, got)
|
||||
}
|
||||
|
||||
returnedPolicy := draft.Policy()
|
||||
returnedPolicy.Assessment.Attempt.IdleTimeoutSeconds++
|
||||
if draft.Policy().Assessment.Attempt.IdleTimeoutSeconds != got.IdleTimeoutSeconds {
|
||||
t.Fatal("changing returned attempt settings changed the policy draft")
|
||||
}
|
||||
returnedPolicy.Assessment.Training.DemoExpressDurationSeconds++
|
||||
if draft.Policy().Assessment.Training.DemoExpressDurationSeconds != policy.Assessment.Training.DemoExpressDurationSeconds {
|
||||
t.Fatal("changing returned training settings changed the policy draft")
|
||||
}
|
||||
}
|
||||
@@ -60,3 +60,29 @@ func DemoProductPolicyV1() ProductPolicy {
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// DemoProductPolicyV2 returns an explicit demo policy with assessment attempt
|
||||
// execution values. The idle timeout, mode, and basic pass mark are initial
|
||||
// product choices, not facts established by the assessment PRD or calibration.
|
||||
// Publishing this value is an explicit operation; startup seeding continues
|
||||
// to publish V1 only and never replaces an immutable stored version.
|
||||
func DemoProductPolicyV2() ProductPolicy {
|
||||
policy := DemoProductPolicyV1()
|
||||
policy.Assessment.Attempt = &AssessmentAttemptPolicy{
|
||||
Lifetime: 72,
|
||||
ChainDeadline: 72,
|
||||
MaxSessions: 2,
|
||||
IdleTimeoutSeconds: 1800,
|
||||
RealMode: AssessmentRealModeDemoBasic,
|
||||
BasicPassMark: 8000,
|
||||
}
|
||||
policy.Assessment.Training = &AssessmentTrainingPolicy{
|
||||
DemoExpressDurationSeconds: 240,
|
||||
DemoExpressItemCount: 3,
|
||||
MaxSessions: 1,
|
||||
IdleTimeoutSeconds: 240,
|
||||
}
|
||||
support := DemoSupportPolicy()
|
||||
policy.Support = &support
|
||||
return policy
|
||||
}
|
||||
@@ -10,10 +10,11 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
// productPolicySchemaVersion is the layout of the stored document. A new
|
||||
// layout adds a decoder for its version; stored versions are never
|
||||
// rewritten.
|
||||
productPolicySchemaVersion = 1
|
||||
// productPolicySchemaVersionV1 is the original immutable policy layout.
|
||||
productPolicySchemaVersionV1 = 1
|
||||
// productPolicySchemaVersionV2 adds optional policy extensions. Stored
|
||||
// versions are never rewritten when a newer layout is introduced.
|
||||
productPolicySchemaVersionV2 = 2
|
||||
// maxPolicyDocumentBytes bounds a document before decoding. The current
|
||||
// layout encodes to well under 2 KiB.
|
||||
maxPolicyDocumentBytes = 64 << 10
|
||||
@@ -22,9 +23,11 @@ const (
|
||||
// PolicyDocumentHash is the SHA-256 of the canonical policy document.
|
||||
type PolicyDocumentHash [sha256.Size]byte
|
||||
|
||||
// The document types mirror ProductPolicy field by field. Every field is a
|
||||
// pointer, so the decoder can tell a missing field from a zero value: a
|
||||
// missing field is an error, never a default. Field names carry their unit.
|
||||
// The document types mirror ProductPolicy field by field. Required fields are
|
||||
// pointers, so the decoder can tell a missing field from a zero value: a
|
||||
// missing field is an error, never a default. Optional attempt, training, and
|
||||
// support sections are absent only in immutable legacy policy documents.
|
||||
// Field names carry their unit.
|
||||
type productPolicyDocument struct {
|
||||
SchemaVersion *int32 `json:"schema_version"`
|
||||
Invitations *invitationPolicyDocument `json:"invitations"`
|
||||
@@ -32,6 +35,18 @@ type productPolicyDocument struct {
|
||||
Assessment *assessmentPolicyDocument `json:"assessment"`
|
||||
Identity *identityPolicyDocument `json:"identity"`
|
||||
SearchStatus *searchStatusDocument `json:"search_status"`
|
||||
Support *supportPolicyDocument `json:"support,omitempty"`
|
||||
}
|
||||
|
||||
// productPolicyV1Document deliberately excludes extension keys. Its strict
|
||||
// decoder keeps old documents unambiguous even when a newer field is null.
|
||||
type productPolicyV1Document struct {
|
||||
SchemaVersion *int32 `json:"schema_version"`
|
||||
Invitations *invitationPolicyDocument `json:"invitations"`
|
||||
OrganizationQuotas *organizationQuotaDocument `json:"organization_quotas"`
|
||||
Assessment *assessmentPolicyV1Document `json:"assessment"`
|
||||
Identity *identityPolicyDocument `json:"identity"`
|
||||
SearchStatus *searchStatusDocument `json:"search_status"`
|
||||
}
|
||||
|
||||
type invitationPolicyDocument struct {
|
||||
@@ -62,6 +77,20 @@ type organizationTierQuotaDocument struct {
|
||||
}
|
||||
|
||||
type assessmentPolicyDocument struct {
|
||||
Calibration *AssessmentCalibration `json:"calibration"`
|
||||
SameGradeRetryAfterDays *CalendarDays `json:"same_grade_retry_after_days"`
|
||||
MaxAttemptsPerWindow *int32 `json:"max_attempts_per_window"`
|
||||
AttemptWindowDays *CalendarDays `json:"attempt_window_days"`
|
||||
PromotionMinIntervalDays *CalendarDays `json:"promotion_min_interval_days"`
|
||||
ConfirmationThresholdBP *BasisPoints `json:"confirmation_threshold_bp"`
|
||||
HighStrengthThresholdBP *BasisPoints `json:"high_strength_threshold_bp"`
|
||||
PracticeRequired *bool `json:"practice_required"`
|
||||
StopRule *assessmentStopDocument `json:"stop_rule"`
|
||||
Attempt *assessmentAttemptDocument `json:"attempt,omitempty"`
|
||||
Training *assessmentTrainingDocument `json:"training,omitempty"`
|
||||
}
|
||||
|
||||
type assessmentPolicyV1Document struct {
|
||||
Calibration *AssessmentCalibration `json:"calibration"`
|
||||
SameGradeRetryAfterDays *CalendarDays `json:"same_grade_retry_after_days"`
|
||||
MaxAttemptsPerWindow *int32 `json:"max_attempts_per_window"`
|
||||
@@ -73,6 +102,22 @@ type assessmentPolicyDocument struct {
|
||||
StopRule *assessmentStopDocument `json:"stop_rule"`
|
||||
}
|
||||
|
||||
type assessmentAttemptDocument struct {
|
||||
LifetimeHours *Hours `json:"lifetime_hours"`
|
||||
ChainDeadlineHours *Hours `json:"chain_deadline_hours"`
|
||||
MaxSessions *int32 `json:"max_sessions"`
|
||||
IdleTimeoutSeconds *int32 `json:"idle_timeout_seconds"`
|
||||
RealMode *AssessmentRealMode `json:"real_mode"`
|
||||
BasicPassMarkBP *BasisPoints `json:"basic_pass_mark_bp"`
|
||||
}
|
||||
|
||||
type assessmentTrainingDocument struct {
|
||||
DemoExpressDurationSeconds *int32 `json:"demo_express_duration_seconds"`
|
||||
DemoExpressItemCount *int32 `json:"demo_express_item_count"`
|
||||
MaxSessions *int32 `json:"max_sessions"`
|
||||
IdleTimeoutSeconds *int32 `json:"idle_timeout_seconds"`
|
||||
}
|
||||
|
||||
type assessmentStopDocument struct {
|
||||
MinScoredItems *int32 `json:"min_scored_items"`
|
||||
MaxScoredItems *int32 `json:"max_scored_items"`
|
||||
@@ -101,8 +146,20 @@ func encodeProductPolicy(policy ProductPolicy) ([]byte, PolicyDocumentHash, erro
|
||||
quotas := policy.OrganizationQuotas
|
||||
assessment := policy.Assessment
|
||||
identity := policy.Identity
|
||||
var support *supportPolicyDocument
|
||||
if policy.Support != nil {
|
||||
var err error
|
||||
support, err = encodeSupportPolicy(*policy.Support)
|
||||
if err != nil {
|
||||
return nil, PolicyDocumentHash{}, err
|
||||
}
|
||||
}
|
||||
schemaVersion := int32(productPolicySchemaVersionV1)
|
||||
if policy.Assessment.Attempt != nil || policy.Assessment.Training != nil || policy.Support != nil {
|
||||
schemaVersion = productPolicySchemaVersionV2
|
||||
}
|
||||
document := productPolicyDocument{
|
||||
SchemaVersion: pointer(int32(productPolicySchemaVersion)),
|
||||
SchemaVersion: pointer(schemaVersion),
|
||||
Invitations: &invitationPolicyDocument{
|
||||
ResponseDeadlineOptionsDays: pointer(invitations.ResponseDeadlineOptions),
|
||||
DefaultResponseDeadlineDays: pointer(invitations.DefaultResponseDeadline),
|
||||
@@ -137,6 +194,8 @@ func encodeProductPolicy(policy ProductPolicy) ([]byte, PolicyDocumentHash, erro
|
||||
LowerProbabilityBP: pointer(assessment.StopRule.LowerProbability),
|
||||
MaxStandardErrorBP: pointer(assessment.StopRule.MaxStandardError),
|
||||
},
|
||||
Attempt: encodeAssessmentAttemptPolicy(assessment.Attempt),
|
||||
Training: encodeAssessmentTrainingPolicy(assessment.Training),
|
||||
},
|
||||
Identity: &identityPolicyDocument{
|
||||
VerificationTokenLifetimeHours: pointer(identity.VerificationTokenLifetime),
|
||||
@@ -147,6 +206,7 @@ func encodeProductPolicy(policy ProductPolicy) ([]byte, PolicyDocumentHash, erro
|
||||
SearchStatus: &searchStatusDocument{
|
||||
SearchingConfirmationIntervalDays: pointer(policy.SearchStatus.SearchingConfirmationInterval),
|
||||
},
|
||||
Support: support,
|
||||
}
|
||||
encoded, err := json.Marshal(document)
|
||||
if err != nil {
|
||||
@@ -155,6 +215,32 @@ func encodeProductPolicy(policy ProductPolicy) ([]byte, PolicyDocumentHash, erro
|
||||
return encoded, sha256.Sum256(encoded), nil
|
||||
}
|
||||
|
||||
func encodeAssessmentAttemptPolicy(policy *AssessmentAttemptPolicy) *assessmentAttemptDocument {
|
||||
if policy == nil {
|
||||
return nil
|
||||
}
|
||||
return &assessmentAttemptDocument{
|
||||
LifetimeHours: pointer(policy.Lifetime),
|
||||
ChainDeadlineHours: pointer(policy.ChainDeadline),
|
||||
MaxSessions: pointer(policy.MaxSessions),
|
||||
IdleTimeoutSeconds: pointer(policy.IdleTimeoutSeconds),
|
||||
RealMode: pointer(policy.RealMode),
|
||||
BasicPassMarkBP: pointer(policy.BasicPassMark),
|
||||
}
|
||||
}
|
||||
|
||||
func encodeAssessmentTrainingPolicy(policy *AssessmentTrainingPolicy) *assessmentTrainingDocument {
|
||||
if policy == nil {
|
||||
return nil
|
||||
}
|
||||
return &assessmentTrainingDocument{
|
||||
DemoExpressDurationSeconds: pointer(policy.DemoExpressDurationSeconds),
|
||||
DemoExpressItemCount: pointer(policy.DemoExpressItemCount),
|
||||
MaxSessions: pointer(policy.MaxSessions),
|
||||
IdleTimeoutSeconds: pointer(policy.IdleTimeoutSeconds),
|
||||
}
|
||||
}
|
||||
|
||||
func encodeTierQuota(quota OrganizationTierQuota) *organizationTierQuotaDocument {
|
||||
return &organizationTierQuotaDocument{
|
||||
Active: pointer(quota.Active),
|
||||
@@ -163,30 +249,98 @@ func encodeTierQuota(quota OrganizationTierQuota) *organizationTierQuotaDocument
|
||||
}
|
||||
}
|
||||
|
||||
// decodeProductPolicy reads a document strictly: it rejects unknown fields,
|
||||
// missing fields, null values, values of the wrong type or out of the int32
|
||||
// range, an unknown schema version, and trailing data. It checks structure
|
||||
// only; ProductPolicy.Validate checks the values. encoding/json matches field
|
||||
// names without regard to letter case and keeps the last of duplicate keys;
|
||||
// the document hash, computed over the canonical re-encoding, is what pins
|
||||
// the content.
|
||||
// decodeProductPolicy reads a versioned document strictly. It rejects unknown
|
||||
// fields, missing fields, null required values, values of the wrong type or
|
||||
// out of the int32 range, unknown schema versions, and trailing data. It
|
||||
// checks structure only; ProductPolicy.Validate checks the values.
|
||||
func decodeProductPolicy(document []byte) (ProductPolicy, error) {
|
||||
const location = "domain.decodeProductPolicy"
|
||||
if len(document) > maxPolicyDocumentBytes {
|
||||
return ProductPolicy{}, invalidPolicy(location, fmt.Sprintf("document must have at most %d bytes", maxPolicyDocumentBytes))
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewReader(document))
|
||||
decoder.DisallowUnknownFields()
|
||||
version, err := decodeProductPolicySchemaVersion(document)
|
||||
if err != nil {
|
||||
return ProductPolicy{}, err
|
||||
}
|
||||
var parsed productPolicyDocument
|
||||
if err := decoder.Decode(&parsed); err != nil {
|
||||
return ProductPolicy{}, fmt.Errorf("%s - decode document: %w: %w", location, ErrInvalidPolicy, err)
|
||||
switch version {
|
||||
case productPolicySchemaVersionV1:
|
||||
var legacy productPolicyV1Document
|
||||
if err := decodeStrictPolicyDocument(document, &legacy); err != nil {
|
||||
return ProductPolicy{}, err
|
||||
}
|
||||
parsed = productPolicyDocument{
|
||||
SchemaVersion: legacy.SchemaVersion,
|
||||
Invitations: legacy.Invitations,
|
||||
OrganizationQuotas: legacy.OrganizationQuotas,
|
||||
Identity: legacy.Identity,
|
||||
SearchStatus: legacy.SearchStatus,
|
||||
}
|
||||
if legacy.Assessment != nil {
|
||||
assessment := legacy.Assessment
|
||||
parsed.Assessment = &assessmentPolicyDocument{
|
||||
Calibration: assessment.Calibration,
|
||||
SameGradeRetryAfterDays: assessment.SameGradeRetryAfterDays,
|
||||
MaxAttemptsPerWindow: assessment.MaxAttemptsPerWindow,
|
||||
AttemptWindowDays: assessment.AttemptWindowDays,
|
||||
PromotionMinIntervalDays: assessment.PromotionMinIntervalDays,
|
||||
ConfirmationThresholdBP: assessment.ConfirmationThresholdBP,
|
||||
HighStrengthThresholdBP: assessment.HighStrengthThresholdBP,
|
||||
PracticeRequired: assessment.PracticeRequired,
|
||||
StopRule: assessment.StopRule,
|
||||
}
|
||||
}
|
||||
case productPolicySchemaVersionV2:
|
||||
if err := decodeStrictPolicyDocument(document, &parsed); err != nil {
|
||||
return ProductPolicy{}, err
|
||||
}
|
||||
assessment := parsed.Assessment
|
||||
hasAssessmentExtension := assessment != nil && (assessment.Attempt != nil || assessment.Training != nil)
|
||||
if !hasAssessmentExtension && parsed.Support == nil {
|
||||
return ProductPolicy{}, invalidPolicy(location, "schema_version 2 requires at least one policy extension")
|
||||
}
|
||||
default:
|
||||
return ProductPolicy{}, invalidPolicy(location, fmt.Sprintf("schema_version must be %d or %d", productPolicySchemaVersionV1, productPolicySchemaVersionV2))
|
||||
}
|
||||
return decodeProductPolicyFields(parsed, version)
|
||||
}
|
||||
|
||||
func decodeProductPolicySchemaVersion(document []byte) (int32, error) {
|
||||
const location = "domain.decodeProductPolicy"
|
||||
var envelope struct {
|
||||
SchemaVersion *int32 `json:"schema_version"`
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewReader(document))
|
||||
if err := decoder.Decode(&envelope); err != nil {
|
||||
return 0, fmt.Errorf("%s - decode document: %w: %w", location, ErrInvalidPolicy, err)
|
||||
}
|
||||
if _, err := decoder.Token(); !errors.Is(err, io.EOF) {
|
||||
return ProductPolicy{}, invalidPolicy(location, "document must contain one JSON object")
|
||||
return 0, invalidPolicy(location, "document must contain one JSON object")
|
||||
}
|
||||
if envelope.SchemaVersion == nil {
|
||||
return 0, invalidPolicy(location, "schema_version is required and must be an integer")
|
||||
}
|
||||
return *envelope.SchemaVersion, nil
|
||||
}
|
||||
|
||||
func decodeStrictPolicyDocument[T any](document []byte, parsed *T) error {
|
||||
const location = "domain.decodeProductPolicy"
|
||||
decoder := json.NewDecoder(bytes.NewReader(document))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(parsed); err != nil {
|
||||
return fmt.Errorf("%s - decode document: %w: %w", location, ErrInvalidPolicy, err)
|
||||
}
|
||||
if _, err := decoder.Token(); !errors.Is(err, io.EOF) {
|
||||
return invalidPolicy(location, "document must contain one JSON object")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func decodeProductPolicyFields(parsed productPolicyDocument, schemaVersion int32) (ProductPolicy, error) {
|
||||
const location = "domain.decodeProductPolicy"
|
||||
reader := documentReader{}
|
||||
if version := require(&reader, "schema_version", parsed.SchemaVersion); reader.missing == "" && version != productPolicySchemaVersion {
|
||||
return ProductPolicy{}, invalidPolicy(location, fmt.Sprintf("schema_version must be %d", productPolicySchemaVersion))
|
||||
if version := require(&reader, "schema_version", parsed.SchemaVersion); reader.missing == "" && version != schemaVersion {
|
||||
return ProductPolicy{}, invalidPolicy(location, fmt.Sprintf("schema_version must be %d", schemaVersion))
|
||||
}
|
||||
invitations := require(&reader, "invitations", parsed.Invitations)
|
||||
quotas := require(&reader, "organization_quotas", parsed.OrganizationQuotas)
|
||||
@@ -195,6 +349,28 @@ func decodeProductPolicy(document []byte) (ProductPolicy, error) {
|
||||
stopRule := require(&reader, "assessment.stop_rule", assessment.StopRule)
|
||||
identity := require(&reader, "identity", parsed.Identity)
|
||||
searchStatus := require(&reader, "search_status", parsed.SearchStatus)
|
||||
var attemptPolicy *AssessmentAttemptPolicy
|
||||
if assessment.Attempt != nil {
|
||||
attempt := assessment.Attempt
|
||||
attemptPolicy = &AssessmentAttemptPolicy{
|
||||
Lifetime: require(&reader, "assessment.attempt.lifetime_hours", attempt.LifetimeHours),
|
||||
ChainDeadline: require(&reader, "assessment.attempt.chain_deadline_hours", attempt.ChainDeadlineHours),
|
||||
MaxSessions: require(&reader, "assessment.attempt.max_sessions", attempt.MaxSessions),
|
||||
IdleTimeoutSeconds: require(&reader, "assessment.attempt.idle_timeout_seconds", attempt.IdleTimeoutSeconds),
|
||||
RealMode: require(&reader, "assessment.attempt.real_mode", attempt.RealMode),
|
||||
BasicPassMark: require(&reader, "assessment.attempt.basic_pass_mark_bp", attempt.BasicPassMarkBP),
|
||||
}
|
||||
}
|
||||
var trainingPolicy *AssessmentTrainingPolicy
|
||||
if assessment.Training != nil {
|
||||
training := assessment.Training
|
||||
trainingPolicy = &AssessmentTrainingPolicy{
|
||||
DemoExpressDurationSeconds: require(&reader, "assessment.training.demo_express_duration_seconds", training.DemoExpressDurationSeconds),
|
||||
DemoExpressItemCount: require(&reader, "assessment.training.demo_express_item_count", training.DemoExpressItemCount),
|
||||
MaxSessions: require(&reader, "assessment.training.max_sessions", training.MaxSessions),
|
||||
IdleTimeoutSeconds: require(&reader, "assessment.training.idle_timeout_seconds", training.IdleTimeoutSeconds),
|
||||
}
|
||||
}
|
||||
policy := ProductPolicy{
|
||||
Invitations: InvitationPolicy{
|
||||
ResponseDeadlineOptions: require(&reader, "invitations.response_deadline_options_days", invitations.ResponseDeadlineOptionsDays),
|
||||
@@ -228,6 +404,8 @@ func decodeProductPolicy(document []byte) (ProductPolicy, error) {
|
||||
LowerProbability: require(&reader, "assessment.stop_rule.lower_probability_bp", stopRule.LowerProbabilityBP),
|
||||
MaxStandardError: require(&reader, "assessment.stop_rule.max_standard_error_bp", stopRule.MaxStandardErrorBP),
|
||||
},
|
||||
Attempt: attemptPolicy,
|
||||
Training: trainingPolicy,
|
||||
},
|
||||
Identity: IdentityPolicy{
|
||||
VerificationTokenLifetime: require(&reader, "identity.verification_token_lifetime_hours", identity.VerificationTokenLifetimeHours),
|
||||
@@ -238,6 +416,7 @@ func decodeProductPolicy(document []byte) (ProductPolicy, error) {
|
||||
SearchStatus: SearchStatusPolicy{
|
||||
SearchingConfirmationInterval: require(&reader, "search_status.searching_confirmation_interval_days", searchStatus.SearchingConfirmationIntervalDays),
|
||||
},
|
||||
Support: decodeOptionalSupportPolicy(&reader, parsed.Support),
|
||||
}
|
||||
if reader.missing != "" {
|
||||
return ProductPolicy{}, invalidPolicy(location, reader.missing+" is required")
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPolicySchemaVersionsPreserveLegacyAndRequireExtensions(t *testing.T) {
|
||||
t.Run("schema 1 rejects every extension key even when null", func(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
edit func(map[string]any)
|
||||
}{
|
||||
{name: "attempt", edit: func(document map[string]any) { policySection(t, document, "assessment")["attempt"] = nil }},
|
||||
{name: "training", edit: func(document map[string]any) { policySection(t, document, "assessment")["training"] = nil }},
|
||||
{name: "support", edit: func(document map[string]any) { document["support"] = nil }},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
encoded := editPolicySchemaDocument(t, []byte(demoProductPolicyV1Document), test.edit)
|
||||
if _, err := decodeProductPolicy(encoded); !errors.Is(err, ErrInvalidPolicy) {
|
||||
t.Fatalf("decodeProductPolicy(schema 1 with null %s) error = %v, want ErrInvalidPolicy", test.name, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("schema 2 requires at least one extension", func(t *testing.T) {
|
||||
encoded := editPolicySchemaDocument(t, []byte(demoProductPolicyV1Document), func(document map[string]any) {
|
||||
document["schema_version"] = 2
|
||||
})
|
||||
if _, err := decodeProductPolicy(encoded); !errors.Is(err, ErrInvalidPolicy) {
|
||||
t.Fatalf("decodeProductPolicy(schema 2 without extensions) error = %v, want ErrInvalidPolicy", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("unknown schema version is rejected", func(t *testing.T) {
|
||||
encoded := editPolicySchemaDocument(t, []byte(demoProductPolicyV1Document), func(document map[string]any) {
|
||||
document["schema_version"] = 3
|
||||
})
|
||||
if _, err := decodeProductPolicy(encoded); !errors.Is(err, ErrInvalidPolicy) {
|
||||
t.Fatalf("decodeProductPolicy(schema 3) error = %v, want ErrInvalidPolicy", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestPolicySchemaV2RoundTripsEachExtensionIndependently(t *testing.T) {
|
||||
base := DemoProductPolicyV1()
|
||||
configured := DemoProductPolicyV2()
|
||||
tests := []struct {
|
||||
name string
|
||||
change func(*ProductPolicy)
|
||||
check func(*testing.T, ProductPolicy)
|
||||
}{
|
||||
{
|
||||
name: "attempt",
|
||||
change: func(policy *ProductPolicy) {
|
||||
attempt := *configured.Assessment.Attempt
|
||||
policy.Assessment.Attempt = &attempt
|
||||
},
|
||||
check: func(t *testing.T, policy ProductPolicy) {
|
||||
t.Helper()
|
||||
if policy.Assessment.Attempt == nil || policy.Assessment.Training != nil || policy.Support != nil {
|
||||
t.Fatalf("decoded extensions = attempt:%v training:%v support:%v", policy.Assessment.Attempt != nil, policy.Assessment.Training != nil, policy.Support != nil)
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "training",
|
||||
change: func(policy *ProductPolicy) {
|
||||
training := *configured.Assessment.Training
|
||||
policy.Assessment.Training = &training
|
||||
},
|
||||
check: func(t *testing.T, policy ProductPolicy) {
|
||||
t.Helper()
|
||||
if policy.Assessment.Attempt != nil || policy.Assessment.Training == nil || policy.Support != nil {
|
||||
t.Fatalf("decoded extensions = attempt:%v training:%v support:%v", policy.Assessment.Attempt != nil, policy.Assessment.Training != nil, policy.Support != nil)
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "support",
|
||||
change: func(policy *ProductPolicy) {
|
||||
support := *configured.Support
|
||||
policy.Support = &support
|
||||
},
|
||||
check: func(t *testing.T, policy ProductPolicy) {
|
||||
t.Helper()
|
||||
if policy.Assessment.Attempt != nil || policy.Assessment.Training != nil || policy.Support == nil {
|
||||
t.Fatalf("decoded extensions = attempt:%v training:%v support:%v", policy.Assessment.Attempt != nil, policy.Assessment.Training != nil, policy.Support != nil)
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
policy := base.clone()
|
||||
test.change(&policy)
|
||||
encoded, _, err := encodeProductPolicy(policy)
|
||||
if err != nil {
|
||||
t.Fatalf("encodeProductPolicy() error = %v", err)
|
||||
}
|
||||
var envelope struct {
|
||||
SchemaVersion int32 `json:"schema_version"`
|
||||
}
|
||||
if err := json.Unmarshal(encoded, &envelope); err != nil || envelope.SchemaVersion != productPolicySchemaVersionV2 {
|
||||
t.Fatalf("encoded schema version = %d (error %v), want 2", envelope.SchemaVersion, err)
|
||||
}
|
||||
decoded, err := decodeProductPolicy(encoded)
|
||||
if err != nil {
|
||||
t.Fatalf("decodeProductPolicy() error = %v", err)
|
||||
}
|
||||
test.check(t, decoded)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func editPolicySchemaDocument(t *testing.T, source []byte, edit func(map[string]any)) []byte {
|
||||
t.Helper()
|
||||
var document map[string]any
|
||||
if err := json.Unmarshal(source, &document); err != nil {
|
||||
t.Fatalf("unmarshal policy document: %v", err)
|
||||
}
|
||||
edit(document)
|
||||
encoded, err := json.Marshal(document)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal policy document: %v", err)
|
||||
}
|
||||
return encoded
|
||||
}
|
||||
|
||||
func policySection(t *testing.T, document map[string]any, name string) map[string]any {
|
||||
t.Helper()
|
||||
section, ok := document[name].(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("policy document %q section is missing or invalid", name)
|
||||
}
|
||||
return section
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// supportPolicyDocument is the strict stored representation of the support
|
||||
// section. Pointer fields make omission distinct from a configured zero.
|
||||
type supportPolicyDocument struct {
|
||||
SupportResponseDays *BusinessDays `json:"support_response_business_days"`
|
||||
ComplaintResponseDays *BusinessDays `json:"complaint_response_business_days"`
|
||||
ManualAssessmentResponseDays *BusinessDays `json:"manual_assessment_response_business_days"`
|
||||
AppealResponseDays *BusinessDays `json:"appeal_response_business_days"`
|
||||
MaxRequestsPerWindow *int32 `json:"max_requests_per_window"`
|
||||
RequestWindowSeconds *int32 `json:"request_window_seconds"`
|
||||
MaxAppealsPerTarget *int32 `json:"max_appeals_per_target"`
|
||||
PauseWhenWaitingForUser *bool `json:"pause_when_waiting_for_user"`
|
||||
BusinessCalendarVersion *int32 `json:"business_calendar_version"`
|
||||
}
|
||||
|
||||
func encodeSupportPolicy(policy SupportPolicy) (*supportPolicyDocument, error) {
|
||||
requestWindowSeconds := int64(policy.requestWindow / time.Second)
|
||||
if requestWindowSeconds < 1 || policy.requestWindow%time.Second != 0 || requestWindowSeconds > 1<<31-1 {
|
||||
return nil, fmt.Errorf("encodeSupportPolicy - request window must fit whole int32 seconds: %w", ErrInvalidSupportPolicy)
|
||||
}
|
||||
return &supportPolicyDocument{
|
||||
SupportResponseDays: pointer(policy.supportResponseDays),
|
||||
ComplaintResponseDays: pointer(policy.complaintResponseDays),
|
||||
ManualAssessmentResponseDays: pointer(policy.manualAssessmentResponseDays),
|
||||
AppealResponseDays: pointer(policy.appealResponseDays),
|
||||
MaxRequestsPerWindow: pointer(policy.maxRequestsPerWindow),
|
||||
RequestWindowSeconds: pointer(int32(requestWindowSeconds)),
|
||||
MaxAppealsPerTarget: pointer(policy.maxAppealsPerTarget),
|
||||
PauseWhenWaitingForUser: pointer(policy.pauseWhenWaitingForUser),
|
||||
BusinessCalendarVersion: pointer(policy.businessCalendarVersion),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// decodeSupportPolicy reads every required support field. Unknown fields are
|
||||
// rejected by the enclosing product-policy decoder, which uses
|
||||
// DisallowUnknownFields.
|
||||
func decodeSupportPolicy(reader *documentReader, document *supportPolicyDocument) SupportPolicy {
|
||||
return SupportPolicy{
|
||||
supportResponseDays: require(reader, "support.support_response_business_days", document.SupportResponseDays),
|
||||
complaintResponseDays: require(reader, "support.complaint_response_business_days", document.ComplaintResponseDays),
|
||||
manualAssessmentResponseDays: require(reader, "support.manual_assessment_response_business_days", document.ManualAssessmentResponseDays),
|
||||
appealResponseDays: require(reader, "support.appeal_response_business_days", document.AppealResponseDays),
|
||||
maxRequestsPerWindow: require(reader, "support.max_requests_per_window", document.MaxRequestsPerWindow),
|
||||
requestWindow: time.Duration(require(reader, "support.request_window_seconds", document.RequestWindowSeconds)) * time.Second,
|
||||
maxAppealsPerTarget: require(reader, "support.max_appeals_per_target", document.MaxAppealsPerTarget),
|
||||
pauseWhenWaitingForUser: require(reader, "support.pause_when_waiting_for_user", document.PauseWhenWaitingForUser),
|
||||
businessCalendarVersion: require(reader, "support.business_calendar_version", document.BusinessCalendarVersion),
|
||||
}
|
||||
}
|
||||
|
||||
// decodeOptionalSupportPolicy preserves immutable legacy documents that were
|
||||
// published before the support section existed. It never fills an omitted
|
||||
// section with demo values.
|
||||
func decodeOptionalSupportPolicy(reader *documentReader, document *supportPolicyDocument) *SupportPolicy {
|
||||
if document == nil {
|
||||
return nil
|
||||
}
|
||||
policy := decodeSupportPolicy(reader, document)
|
||||
return &policy
|
||||
}
|
||||
|
||||
// Validate rejects an absent or unsupported support-policy section. Product
|
||||
// policies may leave the optional section nil only for immutable legacy
|
||||
// documents; policy creation uses an explicit SupportPolicy value.
|
||||
func (policy SupportPolicy) Validate() error {
|
||||
if policy.IsZero() {
|
||||
return ErrInvalidSupportPolicy
|
||||
}
|
||||
_, err := NewSupportPolicy(SupportPolicyInput{
|
||||
SupportResponseDays: policy.supportResponseDays,
|
||||
ComplaintResponseDays: policy.complaintResponseDays,
|
||||
ManualAssessmentResponseDays: policy.manualAssessmentResponseDays,
|
||||
AppealResponseDays: policy.appealResponseDays,
|
||||
MaxRequestsPerWindow: policy.maxRequestsPerWindow,
|
||||
RequestWindow: policy.requestWindow,
|
||||
MaxAppealsPerTarget: policy.maxAppealsPerTarget,
|
||||
PauseWhenWaitingForUser: policy.pauseWhenWaitingForUser,
|
||||
BusinessCalendarVersion: policy.businessCalendarVersion,
|
||||
})
|
||||
return err
|
||||
}
|
||||
@@ -202,6 +202,37 @@ func TestProductPolicyValidateRejectsEachSection(t *testing.T) {
|
||||
"upper stop below confirmation": func(policy *ProductPolicy) { policy.Assessment.StopRule.UpperProbability = 7000 },
|
||||
"zero standard error": func(policy *ProductPolicy) { policy.Assessment.StopRule.MaxStandardError = 0 },
|
||||
"standard error above one": func(policy *ProductPolicy) { policy.Assessment.StopRule.MaxStandardError = 10001 },
|
||||
"zero attempt lifetime": func(policy *ProductPolicy) {
|
||||
policy.Assessment.Attempt.Lifetime = 0
|
||||
},
|
||||
"chain exceeds attempt lifetime": func(policy *ProductPolicy) {
|
||||
policy.Assessment.Attempt.Lifetime = 24
|
||||
policy.Assessment.Attempt.ChainDeadline = 25
|
||||
},
|
||||
"idle timeout above lifetime": func(policy *ProductPolicy) {
|
||||
policy.Assessment.Attempt.Lifetime = 1
|
||||
policy.Assessment.Attempt.IdleTimeoutSeconds = 3601
|
||||
},
|
||||
"unknown real attempt mode": func(policy *ProductPolicy) {
|
||||
policy.Assessment.Attempt.RealMode = "client_selected"
|
||||
},
|
||||
"basic mode missing pass mark": func(policy *ProductPolicy) {
|
||||
policy.Assessment.Attempt.BasicPassMark = 0
|
||||
},
|
||||
"adaptive mode with basic mark": func(policy *ProductPolicy) {
|
||||
policy.Assessment.Attempt.RealMode = AssessmentRealModeAdaptive
|
||||
},
|
||||
"adaptive mode without calibration": func(policy *ProductPolicy) {
|
||||
policy.Assessment.Calibration = AssessmentCalibrationUncalibratedInitial
|
||||
policy.Assessment.Attempt.RealMode = AssessmentRealModeAdaptive
|
||||
policy.Assessment.Attempt.BasicPassMark = 0
|
||||
},
|
||||
"invalid express duration": func(policy *ProductPolicy) {
|
||||
policy.Assessment.Training.DemoExpressDurationSeconds = 179
|
||||
},
|
||||
"invalid express item count": func(policy *ProductPolicy) {
|
||||
policy.Assessment.Training.DemoExpressItemCount = 0
|
||||
},
|
||||
"zero token lifetime": func(policy *ProductPolicy) { policy.Identity.VerificationTokenLifetime = 0 },
|
||||
"zero unverified account lifetime": func(policy *ProductPolicy) { policy.Identity.UnverifiedAccountLifetime = 0 },
|
||||
"zero idle timeout": func(policy *ProductPolicy) { policy.Identity.SessionIdleTimeout = 0 },
|
||||
@@ -220,6 +251,11 @@ func TestProductPolicyValidateRejectsEachSection(t *testing.T) {
|
||||
for name, mutate := range tests {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
policy := testPolicy()
|
||||
preset := DemoProductPolicyV2().Assessment
|
||||
attempt := *preset.Attempt
|
||||
training := *preset.Training
|
||||
policy.Assessment.Attempt = &attempt
|
||||
policy.Assessment.Training = &training
|
||||
mutate(&policy)
|
||||
if err := policy.Validate(); !errors.Is(err, ErrInvalidPolicy) {
|
||||
t.Fatalf("Validate() error = %v, want ErrInvalidPolicy", err)
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDemoProductPolicyV2PinsTrainingSessionLimits(t *testing.T) {
|
||||
policy := DemoProductPolicyV2()
|
||||
if err := policy.Validate(); err != nil {
|
||||
t.Fatalf("DemoProductPolicyV2().Validate() error = %v", err)
|
||||
}
|
||||
training := policy.Assessment.Training
|
||||
if training == nil || training.DemoExpressDurationSeconds != 240 || training.DemoExpressItemCount != 3 ||
|
||||
training.MaxSessions != 1 || training.IdleTimeoutSeconds != 240 {
|
||||
t.Fatalf("DemoProductPolicyV2().Assessment.Training = %+v, want explicit demo limits", training)
|
||||
}
|
||||
|
||||
encoded, _, err := encodeProductPolicy(policy)
|
||||
if err != nil {
|
||||
t.Fatalf("encodeProductPolicy() error = %v", err)
|
||||
}
|
||||
decoded, err := decodeProductPolicy(encoded)
|
||||
if err != nil {
|
||||
t.Fatalf("decodeProductPolicy() error = %v", err)
|
||||
}
|
||||
if decoded.Assessment.Training == nil || *decoded.Assessment.Training != *training {
|
||||
t.Fatalf("decoded training policy = %+v, want %+v", decoded.Assessment.Training, training)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTrainingPolicyRequiresAllDocumentFieldsAndRejectsUnknownFields(t *testing.T) {
|
||||
encoded, _, err := encodeProductPolicy(DemoProductPolicyV2())
|
||||
if err != nil {
|
||||
t.Fatalf("encodeProductPolicy() error = %v", err)
|
||||
}
|
||||
|
||||
missing := bytes.Replace(encoded, []byte(`,"max_sessions":1`), nil, 1)
|
||||
if bytes.Equal(missing, encoded) {
|
||||
t.Fatal("encoded training section did not contain max_sessions")
|
||||
}
|
||||
if _, err := decodeProductPolicy(missing); !errors.Is(err, ErrInvalidPolicy) {
|
||||
t.Fatalf("decodeProductPolicy(missing max_sessions) error = %v, want ErrInvalidPolicy", err)
|
||||
}
|
||||
|
||||
unknown := bytes.Replace(encoded, []byte(`"max_sessions":1`), []byte(`"max_sessions":1,"unknown":true`), 1)
|
||||
if bytes.Equal(unknown, encoded) {
|
||||
t.Fatal("encoded training section did not contain max_sessions")
|
||||
}
|
||||
if _, err := decodeProductPolicy(unknown); !errors.Is(err, ErrInvalidPolicy) {
|
||||
t.Fatalf("decodeProductPolicy(unknown training field) error = %v, want ErrInvalidPolicy", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAssessmentTrainingPolicyRejectsInvalidSessionLimits(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
change func(*AssessmentTrainingPolicy)
|
||||
}{
|
||||
{name: "zero sessions", change: func(policy *AssessmentTrainingPolicy) { policy.MaxSessions = 0 }},
|
||||
{name: "too many sessions", change: func(policy *AssessmentTrainingPolicy) { policy.MaxSessions = 11 }},
|
||||
{name: "idle timeout below minimum", change: func(policy *AssessmentTrainingPolicy) { policy.IdleTimeoutSeconds = 59 }},
|
||||
{name: "idle timeout above duration", change: func(policy *AssessmentTrainingPolicy) { policy.IdleTimeoutSeconds = 241 }},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
policy := DemoProductPolicyV2()
|
||||
test.change(policy.Assessment.Training)
|
||||
if err := policy.Validate(); !errors.Is(err, ErrInvalidPolicy) {
|
||||
t.Fatalf("ProductPolicy.Validate() error = %v, want ErrInvalidPolicy", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTrainingPolicyDocumentUsesSnakeCaseSessionFields(t *testing.T) {
|
||||
encoded, _, err := encodeProductPolicy(DemoProductPolicyV2())
|
||||
if err != nil {
|
||||
t.Fatalf("encodeProductPolicy() error = %v", err)
|
||||
}
|
||||
text := string(encoded)
|
||||
for _, field := range []string{`"max_sessions":1`, `"idle_timeout_seconds":240`} {
|
||||
if !strings.Contains(text, field) {
|
||||
t.Errorf("encoded policy %q does not contain %s", text, field)
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,542 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var testSupportCaseCreatedAt = time.Date(2026, time.October, 7, 10, 0, 0, 0, time.UTC)
|
||||
|
||||
func newTestSupportCase(t *testing.T, caseType SupportCaseType) SupportCase {
|
||||
t.Helper()
|
||||
policy := DemoSupportPolicy()
|
||||
target, err := policy.ResponseTarget(caseType, 3, testSupportCaseCreatedAt)
|
||||
if err != nil {
|
||||
t.Fatalf("ResponseTarget() error = %v", err)
|
||||
}
|
||||
input := NewSupportCaseInput{
|
||||
Number: "SC-2026-000123", OwnerID: uuid.New(), Type: caseType,
|
||||
Description: "Please review this request.", ResponseTarget: target, CreatedAt: testSupportCaseCreatedAt,
|
||||
}
|
||||
switch caseType {
|
||||
case SupportCaseTypeSupport:
|
||||
// A support case has no required type-specific fields.
|
||||
case SupportCaseTypeComplaint:
|
||||
reason := SupportComplaintOrganizationConduct
|
||||
input.ComplaintReason = &reason
|
||||
input.Object = &SupportCaseReference{Type: SupportCaseObjectOrganization, ID: uuid.New()}
|
||||
case SupportCaseTypeGradeAppeal:
|
||||
input.Object = &SupportCaseReference{Type: SupportCaseObjectAssessmentAttempt, ID: uuid.New()}
|
||||
case SupportCaseTypeAnticheatAppeal:
|
||||
input.Object = &SupportCaseReference{Type: SupportCaseObjectAssessmentAttempt, ID: uuid.New()}
|
||||
case SupportCaseTypeManualAssessment:
|
||||
target := SupportCaseAssessmentTarget{Specialization: SpecializationBackend, Grade: GradeJunior}
|
||||
input.AssessmentTarget = &target
|
||||
}
|
||||
supportCase, err := NewSupportCase(input)
|
||||
if err != nil {
|
||||
t.Fatalf("NewSupportCase(%s) error = %v", caseType, err)
|
||||
}
|
||||
return supportCase
|
||||
}
|
||||
|
||||
func TestNewSupportCaseSetsOwnerAndTypeSpecificInitialHistory(t *testing.T) {
|
||||
tests := []struct {
|
||||
caseType SupportCaseType
|
||||
status SupportCaseStatus
|
||||
events int
|
||||
}{
|
||||
{caseType: SupportCaseTypeSupport, status: SupportCaseStatusSubmitted, events: 1},
|
||||
{caseType: SupportCaseTypeComplaint, status: SupportCaseStatusSubmitted, events: 1},
|
||||
{caseType: SupportCaseTypeGradeAppeal, status: SupportCaseStatusWaitingExpert, events: 2},
|
||||
{caseType: SupportCaseTypeAnticheatAppeal, status: SupportCaseStatusWaitingExpert, events: 2},
|
||||
{caseType: SupportCaseTypeManualAssessment, status: SupportCaseStatusWaitingExpert, events: 2},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(string(test.caseType), func(t *testing.T) {
|
||||
supportCase := newTestSupportCase(t, test.caseType)
|
||||
snapshot := supportCase.Snapshot()
|
||||
if supportCase.IsZero() || supportCase.OwnerID() == uuid.Nil || supportCase.Type() != test.caseType ||
|
||||
supportCase.Status() != test.status || snapshot.Number != "SC-2026-000123" ||
|
||||
len(snapshot.History) != test.events || !snapshot.CreatedAt.Equal(snapshot.UpdatedAt) {
|
||||
t.Fatalf("new case snapshot = %+v", snapshot)
|
||||
}
|
||||
created := snapshot.History[0]
|
||||
if created.Sequence != 1 || created.Kind != SupportCaseEventCreated || created.Actor != SupportCaseActorUser ||
|
||||
created.Status == nil || *created.Status != SupportCaseStatusSubmitted || created.Message != nil {
|
||||
t.Fatalf("first history event = %+v, want author-created submitted event", created)
|
||||
}
|
||||
if test.events == 2 {
|
||||
routed := snapshot.History[1]
|
||||
if routed.Sequence != 2 || routed.Kind != SupportCaseEventStatusChanged || routed.Actor != SupportCaseActorSystem ||
|
||||
routed.Status == nil || *routed.Status != SupportCaseStatusWaitingExpert || routed.Message != nil {
|
||||
t.Fatalf("expert routing event = %+v", routed)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRestoreSupportCaseSummaryValidatesAndClonesProjection(t *testing.T) {
|
||||
for _, caseType := range []SupportCaseType{
|
||||
SupportCaseTypeSupport, SupportCaseTypeComplaint, SupportCaseTypeGradeAppeal,
|
||||
SupportCaseTypeAnticheatAppeal, SupportCaseTypeManualAssessment,
|
||||
} {
|
||||
t.Run(string(caseType), func(t *testing.T) {
|
||||
original := newTestSupportCase(t, caseType).Summary()
|
||||
restored, err := RestoreSupportCaseSummary(original)
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreSupportCaseSummary() error = %v", err)
|
||||
}
|
||||
if restored.ID != original.ID || restored.Type != caseType || restored.CreatedAt != original.CreatedAt {
|
||||
t.Fatalf("restored summary = %+v, want %+v", restored, original)
|
||||
}
|
||||
if original.Object != nil {
|
||||
original.Object.ID = uuid.New()
|
||||
if restored.Object.ID == original.Object.ID {
|
||||
t.Fatal("restored object reference aliases the input")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRestoreSupportCaseSummaryRejectsInconsistentStorageProjection(t *testing.T) {
|
||||
valid := newTestSupportCase(t, SupportCaseTypeSupport).Summary()
|
||||
tests := []struct {
|
||||
name string
|
||||
change func(*SupportCaseSummary)
|
||||
}{
|
||||
{name: "bad number year", change: func(summary *SupportCaseSummary) { summary.Number = "SC-2025-000123" }},
|
||||
{name: "unknown status", change: func(summary *SupportCaseSummary) { summary.Status = "unknown" }},
|
||||
{name: "unsupported target version", change: func(summary *SupportCaseSummary) { summary.ResponseTarget.CalendarVersion = 0 }},
|
||||
{name: "unresolved decision", change: func(summary *SupportCaseSummary) {
|
||||
outcome := SupportCaseDecisionAnswered
|
||||
summary.DecisionOutcome = &outcome
|
||||
}},
|
||||
{name: "missing complaint object", change: func(summary *SupportCaseSummary) {
|
||||
summary.Type = SupportCaseTypeComplaint
|
||||
}},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
summary := cloneSupportCaseSummary(valid)
|
||||
test.change(&summary)
|
||||
if _, err := RestoreSupportCaseSummary(summary); !errors.Is(err, ErrInvalidSupportCase) {
|
||||
t.Fatalf("RestoreSupportCaseSummary() error = %v, want ErrInvalidSupportCase", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateSupportCaseRequestReportsFieldsBeforeObjectResolution(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input NewSupportCaseInput
|
||||
pointer string
|
||||
}{
|
||||
{
|
||||
name: "unicode whitespace description",
|
||||
input: NewSupportCaseInput{Type: SupportCaseTypeSupport, Description: "\u0085"},
|
||||
pointer: "/description",
|
||||
},
|
||||
{
|
||||
name: "invitation complaint reason with organization reference",
|
||||
input: NewSupportCaseInput{
|
||||
Type: SupportCaseTypeComplaint, Description: "Please review this offer.",
|
||||
Object: &SupportCaseReference{Type: SupportCaseObjectOrganization, ID: uuid.New()},
|
||||
ComplaintReason: supportCaseComplaintReasonPointer(SupportComplaintSalaryTermsViolation),
|
||||
},
|
||||
pointer: "/object/type",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
err := ValidateSupportCaseRequest(test.input)
|
||||
fieldError, ok := errors.AsType[*SupportCaseFieldError](err)
|
||||
if !ok || fieldError.Pointer != test.pointer || !errors.Is(err, ErrInvalidSupportCase) {
|
||||
t.Fatalf("ValidateSupportCaseRequest() error = %v, want invalid field %s", err, test.pointer)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateSupportCaseRequestAllowsManualAssessmentWithoutAttemptOrRubric(t *testing.T) {
|
||||
input := NewSupportCaseInput{
|
||||
Type: SupportCaseTypeManualAssessment, Description: "Please assess my Go skills.",
|
||||
AssessmentTarget: &SupportCaseAssessmentTarget{Specialization: SpecializationBackend, Grade: GradeJunior},
|
||||
}
|
||||
if err := ValidateSupportCaseRequest(input); err != nil {
|
||||
t.Fatalf("ValidateSupportCaseRequest(manual assessment) error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestManualAssessmentNeedsNoAttemptOrConsentField(t *testing.T) {
|
||||
supportCase := newTestSupportCase(t, SupportCaseTypeManualAssessment)
|
||||
if supportCase.Object() != nil || supportCase.RubricVersion() != nil ||
|
||||
supportCase.Status() != SupportCaseStatusWaitingExpert || len(supportCase.History()) != 2 {
|
||||
t.Fatalf("manual assessment should be accepted without a prior attempt, rubric, or consent: %+v", supportCase.Snapshot())
|
||||
}
|
||||
}
|
||||
|
||||
func TestManualAssessmentRubricPinsAreValidatedAndCloned(t *testing.T) {
|
||||
snapshot := newTestSupportCase(t, SupportCaseTypeManualAssessment).Snapshot()
|
||||
version := int32(7)
|
||||
openingID := uuid.New()
|
||||
policyID := PolicyVersionID(uuid.New())
|
||||
expectedOpeningID := openingID
|
||||
expectedPolicyID := policyID
|
||||
snapshot.RubricVersion = &version
|
||||
snapshot.RubricOpeningID = &openingID
|
||||
snapshot.RubricPolicyID = &policyID
|
||||
|
||||
manualCase, err := RestoreSupportCase(snapshot)
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreSupportCase(valid rubric pin) error = %v", err)
|
||||
}
|
||||
version = 8
|
||||
openingID = uuid.New()
|
||||
policyID = PolicyVersionID(uuid.New())
|
||||
|
||||
stored := manualCase.Snapshot()
|
||||
if stored.RubricVersion == nil || *stored.RubricVersion != 7 || stored.RubricOpeningID == nil ||
|
||||
*stored.RubricOpeningID == openingID || stored.RubricPolicyID == nil || *stored.RubricPolicyID == policyID {
|
||||
t.Fatalf("stored rubric pin aliases caller input: %+v", stored)
|
||||
}
|
||||
*stored.RubricVersion = 9
|
||||
*stored.RubricOpeningID = uuid.New()
|
||||
*stored.RubricPolicyID = PolicyVersionID(uuid.New())
|
||||
again := manualCase.Snapshot()
|
||||
if again.RubricVersion == nil || *again.RubricVersion != 7 || again.RubricOpeningID == nil ||
|
||||
*again.RubricOpeningID != expectedOpeningID || again.RubricPolicyID == nil ||
|
||||
*again.RubricPolicyID != expectedPolicyID {
|
||||
t.Fatalf("snapshot mutation changed stored rubric pin: %+v", again)
|
||||
}
|
||||
}
|
||||
|
||||
func TestManualAssessmentRubricPinsMustBeCompleteAndTypeSpecific(t *testing.T) {
|
||||
base := newTestSupportCase(t, SupportCaseTypeManualAssessment).Snapshot()
|
||||
openingID := uuid.New()
|
||||
policyID := PolicyVersionID(uuid.New())
|
||||
version := int32(2)
|
||||
tests := []struct {
|
||||
name string
|
||||
change func(*SupportCaseSnapshot)
|
||||
}{
|
||||
{name: "version only", change: func(snapshot *SupportCaseSnapshot) { snapshot.RubricVersion = &version }},
|
||||
{name: "opening only", change: func(snapshot *SupportCaseSnapshot) { snapshot.RubricOpeningID = &openingID }},
|
||||
{name: "policy only", change: func(snapshot *SupportCaseSnapshot) { snapshot.RubricPolicyID = &policyID }},
|
||||
{name: "pins on non-manual case", change: func(snapshot *SupportCaseSnapshot) {
|
||||
snapshot.Type = SupportCaseTypeSupport
|
||||
snapshot.AssessmentTarget = nil
|
||||
snapshot.RubricVersion = &version
|
||||
snapshot.RubricOpeningID = &openingID
|
||||
snapshot.RubricPolicyID = &policyID
|
||||
}},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
snapshot := cloneSupportCaseSnapshot(base)
|
||||
test.change(&snapshot)
|
||||
if _, err := RestoreSupportCase(snapshot); !errors.Is(err, ErrInvalidSupportCase) {
|
||||
t.Fatalf("RestoreSupportCase() error = %v, want ErrInvalidSupportCase", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewSupportCaseValidatesDescriptionAndTypeSpecificFields(t *testing.T) {
|
||||
valid := newTestSupportCase(t, SupportCaseTypeSupport).Snapshot()
|
||||
tests := []struct {
|
||||
name string
|
||||
change func(*SupportCaseSnapshot)
|
||||
}{
|
||||
{name: "blank description", change: func(snapshot *SupportCaseSnapshot) { snapshot.Description = "\u0085\uFEFF" }},
|
||||
{name: "unknown type", change: func(snapshot *SupportCaseSnapshot) { snapshot.Type = "unknown" }},
|
||||
{name: "foreign-shaped reference", change: func(snapshot *SupportCaseSnapshot) {
|
||||
snapshot.Object = &SupportCaseReference{Type: "unknown", ID: uuid.New()}
|
||||
}},
|
||||
{name: "nil object identifier", change: func(snapshot *SupportCaseSnapshot) {
|
||||
snapshot.Object = &SupportCaseReference{Type: SupportCaseObjectOrganization}
|
||||
}},
|
||||
{name: "bad number year", change: func(snapshot *SupportCaseSnapshot) { snapshot.Number = "SC-2025-000123" }},
|
||||
{name: "zero response target version", change: func(snapshot *SupportCaseSnapshot) { snapshot.ResponseTarget.PolicyVersion = 0 }},
|
||||
{name: "history status mismatch", change: func(snapshot *SupportCaseSnapshot) {
|
||||
snapshot.History[0].Status = supportCaseStatusPointer(SupportCaseStatusClosed)
|
||||
}},
|
||||
{name: "created event repeated", change: func(snapshot *SupportCaseSnapshot) {
|
||||
created := cloneSupportCaseEventSnapshot(snapshot.History[0])
|
||||
created.Sequence = 2
|
||||
created.OccurredAt = snapshot.CreatedAt.Add(time.Minute)
|
||||
snapshot.History = append(snapshot.History, created)
|
||||
snapshot.UpdatedAt = created.OccurredAt
|
||||
}},
|
||||
{name: "unanswered target has calendar version", change: func(snapshot *SupportCaseSnapshot) {
|
||||
snapshot.ResponseTarget.CalendarVersion = 0
|
||||
}},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
snapshot := cloneSupportCaseSnapshot(valid)
|
||||
test.change(&snapshot)
|
||||
if _, err := RestoreSupportCase(snapshot); !errors.Is(err, ErrInvalidSupportCase) {
|
||||
t.Fatalf("RestoreSupportCase() error = %v, want ErrInvalidSupportCase", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestComplaintReasonsThatRequireInvitationRejectOtherObjectTypes(t *testing.T) {
|
||||
for _, reason := range []SupportCaseComplaintReason{SupportComplaintOfferContent, SupportComplaintSalaryTermsViolation} {
|
||||
t.Run(string(reason), func(t *testing.T) {
|
||||
supportCase := newTestSupportCase(t, SupportCaseTypeComplaint)
|
||||
snapshot := supportCase.Snapshot()
|
||||
snapshot.ComplaintReason = &reason
|
||||
if _, err := RestoreSupportCase(snapshot); !errors.Is(err, ErrInvalidSupportCase) {
|
||||
t.Fatalf("RestoreSupportCase() error = %v, want ErrInvalidSupportCase", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSupportCaseSnapshotsClonePointersAndHistory(t *testing.T) {
|
||||
objectID := uuid.New()
|
||||
assessmentTarget := SupportCaseAssessmentTarget{Specialization: SpecializationBackend, Grade: GradeJunior}
|
||||
policy := DemoSupportPolicy()
|
||||
responseTarget, err := policy.ResponseTarget(SupportCaseTypeSupport, 3, testSupportCaseCreatedAt)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
input := NewSupportCaseInput{
|
||||
Number: "SC-2026-000124", OwnerID: uuid.New(), Type: SupportCaseTypeSupport,
|
||||
Description: "A private description", Object: &SupportCaseReference{Type: SupportCaseObjectOrganization, ID: objectID},
|
||||
AssessmentTarget: &assessmentTarget, ResponseTarget: responseTarget, CreatedAt: testSupportCaseCreatedAt,
|
||||
}
|
||||
supportCase, err := NewSupportCase(input)
|
||||
if err != nil {
|
||||
t.Fatalf("NewSupportCase() error = %v", err)
|
||||
}
|
||||
input.Object.ID = uuid.New()
|
||||
input.AssessmentTarget.Grade = GradeSenior
|
||||
snapshot := supportCase.Snapshot()
|
||||
snapshot.Object.ID = uuid.New()
|
||||
snapshot.AssessmentTarget.Grade = GradeSenior
|
||||
*snapshot.History[0].Status = SupportCaseStatusClosed
|
||||
if supportCase.Object().ID != objectID || supportCase.AssessmentTarget().Grade != GradeJunior ||
|
||||
supportCase.History()[0].Snapshot().Status == nil || *supportCase.History()[0].Snapshot().Status != SupportCaseStatusSubmitted {
|
||||
t.Fatalf("caller mutated the stored support case through an input or snapshot alias: %+v", supportCase.Snapshot())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSupportCaseFormattingAndLoggingRedactUserAndObjectContent(t *testing.T) {
|
||||
supportCase := newTestSupportCase(t, SupportCaseTypeSupport)
|
||||
snapshot := supportCase.Snapshot()
|
||||
snapshot.Description = "private-description-marker"
|
||||
snapshot.Object = &SupportCaseReference{Type: SupportCaseObjectOrganization, ID: uuid.New()}
|
||||
message := "private-public-message-marker"
|
||||
snapshot.History = append(snapshot.History, SupportCaseEventSnapshot{
|
||||
Sequence: 2, Kind: SupportCaseEventReply, Actor: SupportCaseActorSupport,
|
||||
OccurredAt: testSupportCaseCreatedAt.Add(time.Minute), Message: &message,
|
||||
})
|
||||
answeredAt := testSupportCaseCreatedAt.Add(time.Minute)
|
||||
snapshot.ResponseTarget.AnsweredAt = &answeredAt
|
||||
snapshot.Status = SupportCaseStatusSubmitted
|
||||
snapshot.UpdatedAt = testSupportCaseCreatedAt.Add(time.Minute)
|
||||
if _, err := RestoreSupportCase(snapshot); err != nil {
|
||||
t.Fatalf("RestoreSupportCase() error = %v", err)
|
||||
}
|
||||
values := []any{supportCase, snapshot, snapshot.History[1], *snapshot.Object}
|
||||
for _, value := range values {
|
||||
formatted := fmt.Sprintf("%+v %#v", value, value)
|
||||
if strings.Contains(formatted, "private-description-marker") || strings.Contains(formatted, "private-public-message-marker") {
|
||||
t.Fatalf("formatted %T leaked private content: %s", value, formatted)
|
||||
}
|
||||
}
|
||||
var buffer bytes.Buffer
|
||||
logger := slog.New(slog.NewJSONHandler(&buffer, nil))
|
||||
logger.Info("case", slog.Any("case", snapshot), slog.Any("event", snapshot.History[1]), slog.Any("object", *snapshot.Object))
|
||||
if strings.Contains(buffer.String(), "private-description-marker") || strings.Contains(buffer.String(), "private-public-message-marker") ||
|
||||
strings.Contains(buffer.String(), snapshot.Object.ID.String()) {
|
||||
t.Fatalf("structured log leaked private content or object ID: %s", buffer.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSupportCaseRequiresMatchingFirstResponseAndTerminalClosureEvent(t *testing.T) {
|
||||
supportCase := newTestSupportCase(t, SupportCaseTypeSupport)
|
||||
snapshot := supportCase.Snapshot()
|
||||
firstReplyAt := testSupportCaseCreatedAt.Add(time.Minute)
|
||||
replyMessage := "We are reviewing this request."
|
||||
snapshot.History = append(snapshot.History, SupportCaseEventSnapshot{
|
||||
Sequence: 2, Kind: SupportCaseEventReply, Actor: SupportCaseActorSupport,
|
||||
OccurredAt: firstReplyAt, Message: &replyMessage,
|
||||
})
|
||||
snapshot.ResponseTarget.AnsweredAt = &firstReplyAt
|
||||
snapshot.UpdatedAt = firstReplyAt
|
||||
if _, err := RestoreSupportCase(snapshot); err != nil {
|
||||
t.Fatalf("RestoreSupportCase(first reply) error = %v", err)
|
||||
}
|
||||
|
||||
wrongAnswerAt := firstReplyAt.Add(time.Second)
|
||||
snapshot.ResponseTarget.AnsweredAt = &wrongAnswerAt
|
||||
if _, err := RestoreSupportCase(snapshot); !errors.Is(err, ErrInvalidSupportCase) {
|
||||
t.Fatalf("RestoreSupportCase(wrong answered time) error = %v, want ErrInvalidSupportCase", err)
|
||||
}
|
||||
futureAnswerAt := firstReplyAt.Add(time.Hour)
|
||||
snapshot.ResponseTarget.AnsweredAt = &futureAnswerAt
|
||||
snapshot.History[1].OccurredAt = futureAnswerAt
|
||||
if err := validateSupportCaseResponseTargetAnswer("test", snapshot); !errors.Is(err, ErrInvalidSupportCase) {
|
||||
t.Fatalf("future answer time error = %v, want ErrInvalidSupportCase", err)
|
||||
}
|
||||
|
||||
closed := supportCase.Snapshot()
|
||||
closed.Status = SupportCaseStatusClosed
|
||||
closedAt := firstReplyAt.Add(time.Minute)
|
||||
closed.UpdatedAt = closedAt
|
||||
closed.History = append(closed.History, SupportCaseEventSnapshot{
|
||||
Sequence: 2, Kind: SupportCaseEventStatusChanged, Actor: SupportCaseActorSupport,
|
||||
OccurredAt: closedAt, Status: supportCaseStatusPointer(SupportCaseStatusClosed),
|
||||
})
|
||||
closed.ResponseTarget.AnsweredAt = &closedAt
|
||||
if _, err := RestoreSupportCase(closed); !errors.Is(err, ErrInvalidSupportCase) {
|
||||
t.Fatalf("RestoreSupportCase(closed without reason) error = %v, want ErrInvalidSupportCase", err)
|
||||
}
|
||||
closureReason := "This case was closed as a duplicate."
|
||||
closed.History[1].Message = &closureReason
|
||||
if _, err := RestoreSupportCase(closed); err != nil {
|
||||
t.Fatalf("RestoreSupportCase(closed with reason) error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSupportCaseReservesOneHistoryEventForTerminalState(t *testing.T) {
|
||||
supportCase := newTestSupportCase(t, SupportCaseTypeSupport)
|
||||
snapshot := supportCase.Snapshot()
|
||||
firstReplyAt := testSupportCaseCreatedAt.Add(time.Minute)
|
||||
message := "A public reply."
|
||||
snapshot.ResponseTarget.AnsweredAt = &firstReplyAt
|
||||
snapshot.History = append(snapshot.History, SupportCaseEventSnapshot{
|
||||
Sequence: 2, Kind: SupportCaseEventReply, Actor: SupportCaseActorSupport,
|
||||
OccurredAt: firstReplyAt, Message: &message,
|
||||
})
|
||||
for sequence := int32(3); sequence <= 199; sequence++ {
|
||||
occurredAt := firstReplyAt.Add(time.Duration(sequence-2) * time.Minute)
|
||||
snapshot.History = append(snapshot.History, SupportCaseEventSnapshot{
|
||||
Sequence: sequence, Kind: SupportCaseEventReply, Actor: SupportCaseActorSupport,
|
||||
OccurredAt: occurredAt, Message: &message,
|
||||
})
|
||||
}
|
||||
snapshot.UpdatedAt = snapshot.History[len(snapshot.History)-1].OccurredAt
|
||||
if _, err := RestoreSupportCase(snapshot); err != nil {
|
||||
t.Fatalf("RestoreSupportCase(199 nonterminal events) error = %v", err)
|
||||
}
|
||||
snapshot.History = append(snapshot.History, SupportCaseEventSnapshot{
|
||||
Sequence: 200, Kind: SupportCaseEventReply, Actor: SupportCaseActorSupport,
|
||||
OccurredAt: snapshot.UpdatedAt.Add(time.Minute), Message: &message,
|
||||
})
|
||||
snapshot.UpdatedAt = snapshot.History[len(snapshot.History)-1].OccurredAt
|
||||
if _, err := RestoreSupportCase(snapshot); !errors.Is(err, ErrInvalidSupportCase) {
|
||||
t.Fatalf("RestoreSupportCase(200 nonterminal events) error = %v, want ErrInvalidSupportCase", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSupportCaseCanonicalizesPersistedTimesToUTCMicroseconds(t *testing.T) {
|
||||
createdAt := time.Date(2026, time.October, 7, 13, 0, 0, 1234567, time.FixedZone("local", 3*60*60))
|
||||
policy := DemoSupportPolicy()
|
||||
target, err := policy.ResponseTarget(SupportCaseTypeSupport, 3, createdAt)
|
||||
if err != nil {
|
||||
t.Fatalf("ResponseTarget() error = %v", err)
|
||||
}
|
||||
supportCase, err := NewSupportCase(NewSupportCaseInput{
|
||||
Number: "SC-2026-000125", OwnerID: uuid.New(), Type: SupportCaseTypeSupport,
|
||||
Description: "Canonical timestamps", ResponseTarget: target, CreatedAt: createdAt,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewSupportCase() error = %v", err)
|
||||
}
|
||||
wantCreatedAt := time.Date(2026, time.October, 7, 10, 0, 0, 1234000, time.UTC)
|
||||
snapshot := supportCase.Snapshot()
|
||||
if snapshot.CreatedAt != wantCreatedAt || snapshot.UpdatedAt != wantCreatedAt ||
|
||||
snapshot.History[0].OccurredAt != wantCreatedAt || snapshot.ResponseTarget.DueAt.Nanosecond()%1000 != 0 ||
|
||||
snapshot.ResponseTarget.DueAt.Location() != time.UTC {
|
||||
t.Fatalf("persisted times are not canonical UTC microseconds: %+v", snapshot)
|
||||
}
|
||||
|
||||
decision, err := NewSupportCaseDecision(SupportCaseDecisionSnapshot{
|
||||
Outcome: SupportCaseDecisionAnswered, Reason: "Resolved", DecidedAt: createdAt,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewSupportCaseDecision() error = %v", err)
|
||||
}
|
||||
if decision.DecidedAt() != wantCreatedAt {
|
||||
t.Fatalf("decision time = %s, want canonical %s", decision.DecidedAt(), wantCreatedAt)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSupportCaseCreateOutcomePreservesOriginalCreationSnapshot(t *testing.T) {
|
||||
supportCase := newTestSupportCase(t, SupportCaseTypeSupport)
|
||||
outcome, err := NewSupportCaseCreatedOutcome(supportCase)
|
||||
if err != nil {
|
||||
t.Fatalf("NewSupportCaseCreatedOutcome() error = %v", err)
|
||||
}
|
||||
snapshot := outcome.Snapshot()
|
||||
snapshot.Case.Description = "mutated-replay"
|
||||
replayed, ok := outcome.Case()
|
||||
if !ok || replayed.Description() != "Please review this request." || outcome.Kind() != SupportCaseCreateOutcomeCreated {
|
||||
t.Fatalf("outcome did not preserve the original create snapshot: %+v", outcome.Snapshot())
|
||||
}
|
||||
if late, ok := outcome.CreationTargetWasLate(); !ok || late {
|
||||
t.Fatalf("creation target lateness = %t, %t; want the original not-late response", late, ok)
|
||||
}
|
||||
progressedSnapshot := supportCase.Snapshot()
|
||||
progressedSnapshot.Status = SupportCaseStatusInReview
|
||||
progressedAt := testSupportCaseCreatedAt.Add(time.Minute)
|
||||
progressedSnapshot.UpdatedAt = progressedAt
|
||||
progressedSnapshot.History = append(progressedSnapshot.History, SupportCaseEventSnapshot{
|
||||
Sequence: 2, Kind: SupportCaseEventStatusChanged, Actor: SupportCaseActorSupport,
|
||||
OccurredAt: progressedAt, Status: supportCaseStatusPointer(SupportCaseStatusInReview),
|
||||
})
|
||||
progressed, err := RestoreSupportCase(progressedSnapshot)
|
||||
if err != nil {
|
||||
t.Fatalf("RestoreSupportCase(progressed) error = %v", err)
|
||||
}
|
||||
if _, err := NewSupportCaseCreatedOutcome(progressed); !errors.Is(err, ErrInvalidSupportCase) {
|
||||
t.Fatalf("NewSupportCaseCreatedOutcome(progressed) error = %v, want ErrInvalidSupportCase", err)
|
||||
}
|
||||
for _, failure := range []SupportCaseCreateOutcome{NewSupportCaseNotFoundOutcome(), NewSupportCaseStateConflictOutcome()} {
|
||||
if failure.IsZero() || failure.Snapshot().Case != nil {
|
||||
t.Fatalf("failure outcome carries a case or is zero: %+v", failure.Snapshot())
|
||||
}
|
||||
}
|
||||
if _, err := RestoreSupportCaseCreateOutcome(SupportCaseCreateOutcomeSnapshot{Kind: SupportCaseCreateOutcomeCreated}); !errors.Is(err, ErrInvalidSupportCase) {
|
||||
t.Fatalf("created outcome without a snapshot error = %v, want ErrInvalidSupportCase", err)
|
||||
}
|
||||
if _, err := RestoreSupportCaseCreateOutcome(SupportCaseCreateOutcomeSnapshot{
|
||||
Kind: SupportCaseCreateOutcomeNotFound, Case: func() *SupportCaseSnapshot { value := supportCase.Snapshot(); return &value }(),
|
||||
}); !errors.Is(err, ErrInvalidSupportCase) {
|
||||
t.Fatalf("failure outcome with a case error = %v, want ErrInvalidSupportCase", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSupportCaseNumberRequiresExpectedFormatAndUTCYear(t *testing.T) {
|
||||
if _, err := ParseSupportCaseNumber("SC-2026-123"); !errors.Is(err, ErrInvalidSupportCase) {
|
||||
t.Fatalf("short number error = %v, want ErrInvalidSupportCase", err)
|
||||
}
|
||||
parsed, err := ParseSupportCaseNumber("SC-2026-000123")
|
||||
if err != nil || !parsed.validFor(testSupportCaseCreatedAt) {
|
||||
t.Fatalf("ParseSupportCaseNumber() = %q, %v; want a valid 2026 number", parsed, err)
|
||||
}
|
||||
if parsed.validFor(time.Date(2027, time.January, 1, 0, 0, 0, 0, time.UTC)) {
|
||||
t.Fatal("number year must match case creation year")
|
||||
}
|
||||
}
|
||||
|
||||
func supportCaseComplaintReasonPointer(reason SupportCaseComplaintReason) *SupportCaseComplaintReason {
|
||||
return &reason
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
var ErrInvalidSupportPolicy = errors.New("invalid support policy")
|
||||
|
||||
const (
|
||||
// MaxSupportRequestWindow bounds the rolling-window quota that an
|
||||
// implementation must support and retain request events for.
|
||||
MaxSupportRequestWindow = 24 * time.Hour
|
||||
maxSupportResponseBusinessDays = BusinessDays(60)
|
||||
maxSupportRequestsPerWindow = int32(1000)
|
||||
supportBusinessCalendarV1 = int32(1)
|
||||
supportAppealsPerTargetV1 = int32(1)
|
||||
)
|
||||
|
||||
// SupportPolicyInput describes the operational targets and request budget for
|
||||
// support cases. Targets are operational goals, never legal deadlines.
|
||||
type SupportPolicyInput struct {
|
||||
SupportResponseDays BusinessDays
|
||||
ComplaintResponseDays BusinessDays
|
||||
ManualAssessmentResponseDays BusinessDays
|
||||
AppealResponseDays BusinessDays
|
||||
MaxRequestsPerWindow int32
|
||||
RequestWindow time.Duration
|
||||
MaxAppealsPerTarget int32
|
||||
PauseWhenWaitingForUser bool
|
||||
BusinessCalendarVersion int32
|
||||
}
|
||||
|
||||
// SupportPolicy is an immutable set of support-case operating rules. Its
|
||||
// calendar is versioned weekdays-only UTC and does not include public
|
||||
// holidays. Waiting for the user does not pause the target. Manual assessment
|
||||
// does not depend on C3 consent.
|
||||
type SupportPolicy struct {
|
||||
supportResponseDays BusinessDays
|
||||
complaintResponseDays BusinessDays
|
||||
manualAssessmentResponseDays BusinessDays
|
||||
appealResponseDays BusinessDays
|
||||
maxRequestsPerWindow int32
|
||||
requestWindow time.Duration
|
||||
maxAppealsPerTarget int32
|
||||
pauseWhenWaitingForUser bool
|
||||
businessCalendarVersion int32
|
||||
}
|
||||
|
||||
// NewSupportPolicy validates and freezes explicit support settings. The
|
||||
// caller still has to pin the containing product policy version when it
|
||||
// creates a response target.
|
||||
func NewSupportPolicy(input SupportPolicyInput) (SupportPolicy, error) {
|
||||
const location = "domain.NewSupportPolicy"
|
||||
for _, value := range []struct {
|
||||
name string
|
||||
days BusinessDays
|
||||
}{
|
||||
{name: "support response days", days: input.SupportResponseDays},
|
||||
{name: "complaint response days", days: input.ComplaintResponseDays},
|
||||
{name: "manual assessment response days", days: input.ManualAssessmentResponseDays},
|
||||
{name: "appeal response days", days: input.AppealResponseDays},
|
||||
} {
|
||||
if value.days < 1 || value.days > maxSupportResponseBusinessDays {
|
||||
return SupportPolicy{}, fmt.Errorf("%s - %s must be 1 to %d business days: %w",
|
||||
location, value.name, maxSupportResponseBusinessDays, ErrInvalidSupportPolicy)
|
||||
}
|
||||
}
|
||||
if input.MaxRequestsPerWindow < 1 || input.MaxRequestsPerWindow > maxSupportRequestsPerWindow {
|
||||
return SupportPolicy{}, fmt.Errorf("%s - request limit must be 1 to %d: %w",
|
||||
location, maxSupportRequestsPerWindow, ErrInvalidSupportPolicy)
|
||||
}
|
||||
if input.RequestWindow <= 0 || input.RequestWindow > MaxSupportRequestWindow || input.RequestWindow%time.Second != 0 {
|
||||
return SupportPolicy{}, fmt.Errorf("%s - request window must be whole seconds, positive, and no longer than 24 hours: %w",
|
||||
location, ErrInvalidSupportPolicy)
|
||||
}
|
||||
if input.MaxAppealsPerTarget != supportAppealsPerTargetV1 {
|
||||
return SupportPolicy{}, fmt.Errorf("%s - MVP allows exactly one appeal per target and type: %w",
|
||||
location, ErrInvalidSupportPolicy)
|
||||
}
|
||||
if input.PauseWhenWaitingForUser {
|
||||
return SupportPolicy{}, fmt.Errorf("%s - waiting for the user cannot pause an MVP response target: %w",
|
||||
location, ErrInvalidSupportPolicy)
|
||||
}
|
||||
if input.BusinessCalendarVersion != supportBusinessCalendarV1 {
|
||||
return SupportPolicy{}, fmt.Errorf("%s - unsupported business calendar version: %w",
|
||||
location, ErrInvalidSupportPolicy)
|
||||
}
|
||||
return SupportPolicy{
|
||||
supportResponseDays: input.SupportResponseDays,
|
||||
complaintResponseDays: input.ComplaintResponseDays,
|
||||
manualAssessmentResponseDays: input.ManualAssessmentResponseDays,
|
||||
appealResponseDays: input.AppealResponseDays,
|
||||
maxRequestsPerWindow: input.MaxRequestsPerWindow,
|
||||
requestWindow: input.RequestWindow,
|
||||
maxAppealsPerTarget: input.MaxAppealsPerTarget,
|
||||
pauseWhenWaitingForUser: input.PauseWhenWaitingForUser,
|
||||
businessCalendarVersion: input.BusinessCalendarVersion,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// DemoSupportPolicy returns explicit demo defaults. These values are not a
|
||||
// calibrated service commitment and do not describe a legal deadline.
|
||||
func DemoSupportPolicy() SupportPolicy {
|
||||
return SupportPolicy{
|
||||
supportResponseDays: 5,
|
||||
complaintResponseDays: 5,
|
||||
manualAssessmentResponseDays: 5,
|
||||
appealResponseDays: 10,
|
||||
maxRequestsPerWindow: 10,
|
||||
requestWindow: time.Hour,
|
||||
maxAppealsPerTarget: supportAppealsPerTargetV1,
|
||||
businessCalendarVersion: supportBusinessCalendarV1,
|
||||
}
|
||||
}
|
||||
|
||||
func (policy SupportPolicy) IsZero() bool {
|
||||
return policy.supportResponseDays == 0 || policy.complaintResponseDays == 0 ||
|
||||
policy.manualAssessmentResponseDays == 0 || policy.appealResponseDays == 0 ||
|
||||
policy.maxRequestsPerWindow == 0 || policy.requestWindow == 0 ||
|
||||
policy.maxAppealsPerTarget == 0 || policy.businessCalendarVersion == 0
|
||||
}
|
||||
|
||||
func (policy SupportPolicy) SupportResponseDays() BusinessDays {
|
||||
return policy.supportResponseDays
|
||||
}
|
||||
|
||||
func (policy SupportPolicy) ComplaintResponseDays() BusinessDays {
|
||||
return policy.complaintResponseDays
|
||||
}
|
||||
|
||||
func (policy SupportPolicy) ManualAssessmentResponseDays() BusinessDays {
|
||||
return policy.manualAssessmentResponseDays
|
||||
}
|
||||
|
||||
func (policy SupportPolicy) AppealResponseDays() BusinessDays {
|
||||
return policy.appealResponseDays
|
||||
}
|
||||
|
||||
func (policy SupportPolicy) MaxRequestsPerWindow() int32 { return policy.maxRequestsPerWindow }
|
||||
|
||||
func (policy SupportPolicy) RequestWindow() time.Duration { return policy.requestWindow }
|
||||
|
||||
// MaxAppealsPerTarget fixes the MVP rule: an appeal type may be opened once
|
||||
// for one target, regardless of the status of the first case.
|
||||
func (policy SupportPolicy) MaxAppealsPerTarget() int32 { return policy.maxAppealsPerTarget }
|
||||
|
||||
// PausesWhenWaitingForUser reports the fixed MVP rule that response targets
|
||||
// continue to run while a case waits for the author.
|
||||
func (policy SupportPolicy) PausesWhenWaitingForUser() bool { return policy.pauseWhenWaitingForUser }
|
||||
|
||||
func (policy SupportPolicy) BusinessCalendarVersion() int32 {
|
||||
return policy.businessCalendarVersion
|
||||
}
|
||||
|
||||
// ResponseTarget fixes the business-day target and its policy version at case
|
||||
// creation. Its UTC calendar excludes Saturdays and Sundays only.
|
||||
func (policy SupportPolicy) ResponseTarget(
|
||||
caseType SupportCaseType,
|
||||
policyVersion int32,
|
||||
createdAt time.Time,
|
||||
) (SupportResponseTarget, error) {
|
||||
const location = "SupportPolicy.ResponseTarget"
|
||||
if policy.IsZero() {
|
||||
return SupportResponseTarget{}, fmt.Errorf("%s - policy must be set: %w", location, ErrInvalidSupportPolicy)
|
||||
}
|
||||
if policyVersion < 1 || createdAt.IsZero() {
|
||||
return SupportResponseTarget{}, fmt.Errorf("%s - version and creation time must be set: %w", location, ErrInvalidSupportPolicy)
|
||||
}
|
||||
days, err := policy.responseDays(caseType)
|
||||
if err != nil {
|
||||
return SupportResponseTarget{}, fmt.Errorf("%s - resolve response target: %w", location, err)
|
||||
}
|
||||
dueAt := addWeekdaysUTC(createdAt, days)
|
||||
target, err := NewSupportResponseTarget(SupportResponseTargetSnapshot{
|
||||
BusinessDays: days,
|
||||
DueAt: dueAt,
|
||||
PolicyVersion: policyVersion,
|
||||
CalendarVersion: policy.BusinessCalendarVersion(),
|
||||
})
|
||||
if err != nil {
|
||||
return SupportResponseTarget{}, fmt.Errorf("%s - build response target: %w", location, err)
|
||||
}
|
||||
return target, nil
|
||||
}
|
||||
|
||||
func (policy SupportPolicy) responseDays(caseType SupportCaseType) (BusinessDays, error) {
|
||||
switch caseType {
|
||||
case SupportCaseTypeSupport:
|
||||
return policy.supportResponseDays, nil
|
||||
case SupportCaseTypeComplaint:
|
||||
return policy.complaintResponseDays, nil
|
||||
case SupportCaseTypeManualAssessment:
|
||||
return policy.manualAssessmentResponseDays, nil
|
||||
case SupportCaseTypeGradeAppeal, SupportCaseTypeAnticheatAppeal:
|
||||
return policy.appealResponseDays, nil
|
||||
default:
|
||||
return 0, fmt.Errorf("unknown case type: %w", ErrInvalidSupportPolicy)
|
||||
}
|
||||
}
|
||||
|
||||
func addWeekdaysUTC(start time.Time, days BusinessDays) time.Time {
|
||||
dueAt := start.UTC()
|
||||
remaining := int(days)
|
||||
for remaining > 0 {
|
||||
dueAt = dueAt.AddDate(0, 0, 1)
|
||||
if dueAt.Weekday() != time.Saturday && dueAt.Weekday() != time.Sunday {
|
||||
remaining--
|
||||
}
|
||||
}
|
||||
return dueAt
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestDemoSupportPolicyUsesExplicitDemoTargetsAndRequestLimit(t *testing.T) {
|
||||
policy := DemoSupportPolicy()
|
||||
if policy.SupportResponseDays() != 5 || policy.ComplaintResponseDays() != 5 ||
|
||||
policy.ManualAssessmentResponseDays() != 5 || policy.AppealResponseDays() != 10 ||
|
||||
policy.MaxRequestsPerWindow() != 10 || policy.RequestWindow() != time.Hour ||
|
||||
policy.MaxAppealsPerTarget() != 1 || policy.PausesWhenWaitingForUser() || policy.BusinessCalendarVersion() != 1 {
|
||||
t.Fatalf("DemoSupportPolicy() = %+v, want the documented demo defaults", policy)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewSupportPolicyRejectsOutOfRangeInputs(t *testing.T) {
|
||||
valid := SupportPolicyInput{
|
||||
SupportResponseDays: 5, ComplaintResponseDays: 5, ManualAssessmentResponseDays: 5,
|
||||
AppealResponseDays: 10, MaxRequestsPerWindow: 10, RequestWindow: time.Hour,
|
||||
MaxAppealsPerTarget: 1, BusinessCalendarVersion: 1,
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
change func(*SupportPolicyInput)
|
||||
}{
|
||||
{name: "zero target", change: func(input *SupportPolicyInput) { input.SupportResponseDays = 0 }},
|
||||
{name: "target above bound", change: func(input *SupportPolicyInput) { input.AppealResponseDays = 61 }},
|
||||
{name: "zero request limit", change: func(input *SupportPolicyInput) { input.MaxRequestsPerWindow = 0 }},
|
||||
{name: "request limit above bound", change: func(input *SupportPolicyInput) { input.MaxRequestsPerWindow = 1001 }},
|
||||
{name: "zero window", change: func(input *SupportPolicyInput) { input.RequestWindow = 0 }},
|
||||
{name: "window above bound", change: func(input *SupportPolicyInput) { input.RequestWindow = 24*time.Hour + time.Nanosecond }},
|
||||
{name: "fractional-second window", change: func(input *SupportPolicyInput) { input.RequestWindow = time.Second + time.Nanosecond }},
|
||||
{name: "appeals per target above bound", change: func(input *SupportPolicyInput) { input.MaxAppealsPerTarget = 2 }},
|
||||
{name: "paused while waiting", change: func(input *SupportPolicyInput) { input.PauseWhenWaitingForUser = true }},
|
||||
{name: "unsupported calendar", change: func(input *SupportPolicyInput) { input.BusinessCalendarVersion = 2 }},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
input := valid
|
||||
test.change(&input)
|
||||
if _, err := NewSupportPolicy(input); !errors.Is(err, ErrInvalidSupportPolicy) {
|
||||
t.Fatalf("NewSupportPolicy() error = %v, want ErrInvalidSupportPolicy", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSupportPolicyDocumentRoundTripAndLegacyOmission(t *testing.T) {
|
||||
reader := documentReader{}
|
||||
if decoded := decodeOptionalSupportPolicy(&reader, nil); decoded != nil || reader.missing != "" {
|
||||
t.Fatalf("omitted support section decoded as %v with missing field %q, want no policy and no error", decoded, reader.missing)
|
||||
}
|
||||
policy := DemoSupportPolicy()
|
||||
encodedDocument, err := encodeSupportPolicy(policy)
|
||||
if err != nil {
|
||||
t.Fatalf("encodeSupportPolicy() error = %v", err)
|
||||
}
|
||||
encoded, err := json.Marshal(encodedDocument)
|
||||
if err != nil {
|
||||
t.Fatalf("Marshal(support policy) error = %v", err)
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewReader(encoded))
|
||||
decoder.DisallowUnknownFields()
|
||||
var parsedDocument supportPolicyDocument
|
||||
if err := decoder.Decode(&parsedDocument); err != nil {
|
||||
t.Fatalf("Decode(support policy document) error = %v", err)
|
||||
}
|
||||
reader = documentReader{}
|
||||
decoded := decodeOptionalSupportPolicy(&reader, &parsedDocument)
|
||||
if reader.missing != "" || decoded == nil || !reflect.DeepEqual(*decoded, policy) {
|
||||
t.Fatalf("decoded policy = %+v, missing = %q, want %+v", decoded, reader.missing, policy)
|
||||
}
|
||||
if err := decoded.Validate(); err != nil {
|
||||
t.Fatalf("decoded.Validate() error = %v", err)
|
||||
}
|
||||
if !strings.Contains(string(encoded), `"pause_when_waiting_for_user":false`) ||
|
||||
!strings.Contains(string(encoded), `"business_calendar_version":1`) {
|
||||
t.Fatalf("document omitted explicit false or calendar version: %s", encoded)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSupportPolicyDocumentRequiresEveryFieldAndRejectsUnknownFields(t *testing.T) {
|
||||
encodedDocument, err := encodeSupportPolicy(DemoSupportPolicy())
|
||||
if err != nil {
|
||||
t.Fatalf("encodeSupportPolicy() error = %v", err)
|
||||
}
|
||||
encoded, err := json.Marshal(encodedDocument)
|
||||
if err != nil {
|
||||
t.Fatalf("Marshal(support policy) error = %v", err)
|
||||
}
|
||||
var parsedDocument supportPolicyDocument
|
||||
decoder := json.NewDecoder(bytes.NewReader(append(encoded[:len(encoded)-1], []byte(`,"unexpected":true}`)...)))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&parsedDocument); err == nil {
|
||||
t.Fatal("support policy document accepted an unknown field")
|
||||
}
|
||||
|
||||
var complete supportPolicyDocument
|
||||
if err := json.Unmarshal(encoded, &complete); err != nil {
|
||||
t.Fatalf("Unmarshal(support policy) error = %v", err)
|
||||
}
|
||||
complete.RequestWindowSeconds = nil
|
||||
reader := documentReader{}
|
||||
decoded := decodeSupportPolicy(&reader, &complete)
|
||||
if reader.missing != "support.request_window_seconds" || !decoded.IsZero() {
|
||||
t.Fatalf("missing field = %q and decoded = %+v, want exact missing-field path and zero policy", reader.missing, decoded)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSupportPolicyValidationDoesNotFillOmittedValues(t *testing.T) {
|
||||
if err := (SupportPolicy{}).Validate(); !errors.Is(err, ErrInvalidSupportPolicy) {
|
||||
t.Fatalf("zero SupportPolicy.Validate() error = %v, want ErrInvalidSupportPolicy", err)
|
||||
}
|
||||
policy := DemoProductPolicyV1()
|
||||
if policy.Support != nil {
|
||||
t.Fatal("legacy DemoProductPolicyV1 unexpectedly contains support defaults")
|
||||
}
|
||||
if err := policy.Validate(); err != nil {
|
||||
t.Fatalf("legacy policy without optional support section must remain valid: %v", err)
|
||||
}
|
||||
v2 := DemoProductPolicyV2()
|
||||
if v2.Support == nil || v2.Support.SupportResponseDays() != 5 || v2.Support.AppealResponseDays() != 10 {
|
||||
t.Fatalf("DemoProductPolicyV2 support section = %+v, want explicit support demo values", v2.Support)
|
||||
}
|
||||
v2.Support = &SupportPolicy{}
|
||||
if err := v2.Validate(); !errors.Is(err, ErrInvalidPolicy) || !errors.Is(err, ErrInvalidSupportPolicy) {
|
||||
t.Fatalf("ProductPolicy.Validate() error = %v, want both policy and support policy errors", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSupportPolicyResponseTargetUsesVersionedWeekdaysInUTC(t *testing.T) {
|
||||
policy := DemoSupportPolicy()
|
||||
createdAt := time.Date(2026, time.October, 9, 15, 30, 0, 0, time.FixedZone("local", 3*60*60)) // Friday in UTC.
|
||||
tests := []struct {
|
||||
caseType SupportCaseType
|
||||
wantDays BusinessDays
|
||||
}{
|
||||
{caseType: SupportCaseTypeSupport, wantDays: 5},
|
||||
{caseType: SupportCaseTypeComplaint, wantDays: 5},
|
||||
{caseType: SupportCaseTypeManualAssessment, wantDays: 5},
|
||||
{caseType: SupportCaseTypeGradeAppeal, wantDays: 10},
|
||||
{caseType: SupportCaseTypeAnticheatAppeal, wantDays: 10},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(string(test.caseType), func(t *testing.T) {
|
||||
target, err := policy.ResponseTarget(test.caseType, 7, createdAt)
|
||||
if err != nil {
|
||||
t.Fatalf("ResponseTarget() error = %v", err)
|
||||
}
|
||||
wantDueAt := time.Date(2026, time.October, 16, 12, 30, 0, 0, time.UTC)
|
||||
if test.wantDays == 10 {
|
||||
wantDueAt = time.Date(2026, time.October, 23, 12, 30, 0, 0, time.UTC)
|
||||
}
|
||||
if target.BusinessDays() != test.wantDays || target.DueAt() != wantDueAt || target.PolicyVersion() != 7 ||
|
||||
target.BusinessCalendarVersion() != 1 || target.Snapshot().CalendarVersion != 1 ||
|
||||
target.Kind() != SupportResponseTargetOperationalGoal {
|
||||
t.Fatalf("target = %+v, want %d business days through %s at policy 7", target, test.wantDays, wantDueAt)
|
||||
}
|
||||
})
|
||||
}
|
||||
if DemoSupportPolicy().PausesWhenWaitingForUser() {
|
||||
t.Fatal("waiting for the user must not pause an MVP response target")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSupportPolicyRejectsUnsetPolicyUnknownCaseAndInvalidVersion(t *testing.T) {
|
||||
createdAt := time.Date(2026, time.October, 7, 10, 0, 0, 0, time.UTC)
|
||||
if _, err := (SupportPolicy{}).ResponseTarget(SupportCaseTypeSupport, 1, createdAt); !errors.Is(err, ErrInvalidSupportPolicy) {
|
||||
t.Fatalf("zero policy error = %v, want ErrInvalidSupportPolicy", err)
|
||||
}
|
||||
policy := DemoSupportPolicy()
|
||||
if _, err := policy.ResponseTarget("unknown", 1, createdAt); !errors.Is(err, ErrInvalidSupportPolicy) {
|
||||
t.Fatalf("unknown case type error = %v, want ErrInvalidSupportPolicy", err)
|
||||
}
|
||||
if _, err := policy.ResponseTarget(SupportCaseTypeSupport, 0, createdAt); !errors.Is(err, ErrInvalidSupportPolicy) {
|
||||
t.Fatalf("zero policy version error = %v, want ErrInvalidSupportPolicy", err)
|
||||
}
|
||||
if _, err := policy.ResponseTarget(SupportCaseTypeSupport, 1, time.Time{}); !errors.Is(err, ErrInvalidSupportPolicy) {
|
||||
t.Fatalf("zero creation time error = %v, want ErrInvalidSupportPolicy", err)
|
||||
}
|
||||
}
|
||||
Loaded 100 of 339 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user